01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright
03: * notice. All rights reserved.
04: */
05: package com.tc.object.dna.impl;
06:
07: import java.io.Serializable;
08: import java.io.UnsupportedEncodingException;
09: import java.util.Arrays;
10:
11: /**
12: * Holds byte data for strings. The main purpose of this class is to simply hold the bytes data for a String (no sense
13: * turning actually into a String instance in L2)
14: * <p>
15: * The reason it is UTF8ByteDataHolder and not ByteDataHolder is that asString() assumes that the byte data is a valid
16: * UTF-8 encoded bytes and creates String as <code> new String(bytes, "UTF-8"); </code>
17: */
18: public class UTF8ByteDataHolder implements Serializable {
19:
20: private final byte[] bytes;
21: private final int uncompressedLength;
22:
23: // Used for tests
24: public UTF8ByteDataHolder(String str) {
25: this .uncompressedLength = -1;
26: try {
27: this .bytes = str.getBytes("UTF-8");
28: } catch (UnsupportedEncodingException e) {
29: throw new AssertionError(e);
30: }
31: }
32:
33: public UTF8ByteDataHolder(byte[] b) {
34: this (b, -1);
35: }
36:
37: public UTF8ByteDataHolder(byte[] b, int uncompressedLenght) {
38: this .bytes = b;
39: this .uncompressedLength = uncompressedLenght;
40: }
41:
42: public byte[] getBytes() {
43: return bytes;
44: }
45:
46: public String asString() {
47: return (isCompressed() ? inflate() : getString());
48: }
49:
50: private String inflate() {
51: return DNAEncodingImpl.inflateCompressedString(bytes,
52: uncompressedLength);
53: }
54:
55: private String getString() {
56: try {
57: return new String(bytes, "UTF-8");
58: } catch (UnsupportedEncodingException e) {
59: throw new AssertionError(e);
60: }
61: }
62:
63: public String toString() {
64: return asString();
65: }
66:
67: public int hashCode() {
68: int hash = isCompressed() ? 21 : 37;
69: for (int i = 0, n = bytes.length; i < n; i++) {
70: hash = 31 * hash + bytes[i++];
71: }
72: return hash;
73: }
74:
75: public boolean equals(Object obj) {
76: if (obj instanceof UTF8ByteDataHolder) {
77: UTF8ByteDataHolder other = (UTF8ByteDataHolder) obj;
78: return ((uncompressedLength == other.uncompressedLength)
79: && (Arrays.equals(this .bytes, other.bytes)) && this
80: .getClass().equals(other.getClass()));
81: }
82: return false;
83: }
84:
85: public boolean isCompressed() {
86: return uncompressedLength != -1;
87: }
88:
89: public int getUnCompressedStringLength() {
90: return uncompressedLength;
91: }
92: }
|