Fixing Bugs
[iotcloud.git] / version2 / src / java / iotcloud / IoTString.java
1 package iotcloud;
2
3 import java.util.Arrays;
4
5 /**
6  * IoTString is wraps the underlying byte string.  We don't use the
7  * standard String class as we have bytes and not chars.
8  * @author Brian Demsky <bdemsky@uci.edu>
9  * @version 1.0
10  */
11
12
13 final public class IoTString {
14         byte[] array;
15         int hashcode;
16
17         private IoTString() {
18         }
19
20         /**
21          * Builds an IoTString object around the byte array.  This
22          * constructor makes a copy, so the caller is free to modify the byte array.
23          */
24
25         public IoTString(byte[] _array) {
26                 array=(byte[]) _array.clone();
27                 hashcode=Arrays.hashCode(array);
28         }
29
30         /**
31          * Converts the String object to a byte representation and stores it
32          * into the IoTString object.
33          */
34
35         public IoTString(String str) {
36                 array=str.getBytes();
37                 hashcode=Arrays.hashCode(array);
38         }
39
40          /**
41          * Internal methods to build an IoTString using the byte[] passed
42          * in.  Caller is responsible for ensuring the byte[] is never
43          * modified.
44          */
45
46         static IoTString shallow(byte[] _array) {
47                 IoTString i=new IoTString();
48                 i.array = _array;
49                 i.hashcode = Arrays.hashCode(_array);
50                 return i;
51         }
52
53         /**
54          * Internal method to grab a reference to our byte array.  Caller
55          * must not modify it.
56          */
57
58         byte[] internalBytes() {
59                 return array;
60         }
61
62         /**
63          * Returns the hashCode as computed by Arrays.hashcode(byte[]).
64          */
65
66         public int hashCode() {
67                 return hashcode;
68         }
69
70         /**
71          * Returns a String representation of the IoTString.
72          */
73
74         public String toString() {
75                 return new String(array);
76         }
77
78         /**
79          * Returns a copy of the underlying byte string.
80          */
81
82         public byte[] getBytes() {
83                 return (byte[]) array.clone();
84         }
85
86         /**
87          * Returns true if two byte strings have the same content.
88          */
89
90         public boolean equals(Object o) {
91                 if (o instanceof IoTString) {
92                         IoTString i=(IoTString)o;
93                         return Arrays.equals(array, i.array);
94                 }
95                 return false;
96         }
97
98         /**
99          * Returns the length in bytes of the IoTString.
100          */
101
102         public int length() {
103                 return array.length;
104         }
105 }