View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.hbase.io;
20  
21  import java.io.IOException;
22  import java.io.DataInput;
23  import java.io.DataOutput;
24  import java.util.Arrays;
25  import java.util.List;
26  
27  import org.apache.hadoop.hbase.classification.InterfaceAudience;
28  import org.apache.hadoop.hbase.classification.InterfaceStability;
29  import org.apache.hadoop.io.BytesWritable;
30  import org.apache.hadoop.io.WritableComparable;
31  import org.apache.hadoop.io.WritableComparator;
32  
33  /**
34   * A byte sequence that is usable as a key or value.  Based on
35   * {@link org.apache.hadoop.io.BytesWritable} only this class is NOT resizable
36   * and DOES NOT distinguish between the size of the sequence and the current
37   * capacity as {@link org.apache.hadoop.io.BytesWritable} does. Hence its
38   * comparatively 'immutable'. When creating a new instance of this class,
39   * the underlying byte [] is not copied, just referenced.  The backing
40   * buffer is accessed when we go to serialize.
41   */
42  @InterfaceAudience.Public
43  @InterfaceStability.Stable
44  @edu.umd.cs.findbugs.annotations.SuppressWarnings(
45      value="EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS",
46      justification="It has been like this forever")
47  public class ImmutableBytesWritable
48  implements WritableComparable<ImmutableBytesWritable> {
49    private byte[] bytes;
50    private int offset;
51    private int length;
52  
53    /**
54     * Create a zero-size sequence.
55     */
56    public ImmutableBytesWritable() {
57      super();
58    }
59  
60    /**
61     * Create a ImmutableBytesWritable using the byte array as the initial value.
62     * @param bytes This array becomes the backing storage for the object.
63     */
64    public ImmutableBytesWritable(byte[] bytes) {
65      this(bytes, 0, bytes.length);
66    }
67  
68    /**
69     * Set the new ImmutableBytesWritable to the contents of the passed
70     * <code>ibw</code>.
71     * @param ibw the value to set this ImmutableBytesWritable to.
72     */
73    public ImmutableBytesWritable(final ImmutableBytesWritable ibw) {
74      this(ibw.get(), ibw.getOffset(), ibw.getLength());
75    }
76  
77    /**
78     * Set the value to a given byte range
79     * @param bytes the new byte range to set to
80     * @param offset the offset in newData to start at
81     * @param length the number of bytes in the range
82     */
83    public ImmutableBytesWritable(final byte[] bytes, final int offset,
84        final int length) {
85      this.bytes = bytes;
86      this.offset = offset;
87      this.length = length;
88    }
89  
90    /**
91     * Get the data from the BytesWritable.
92     * @return The data is only valid between offset and offset+length.
93     */
94    public byte [] get() {
95      if (this.bytes == null) {
96        throw new IllegalStateException("Uninitialiized. Null constructor " +
97          "called w/o accompaying readFields invocation");
98      }
99      return this.bytes;
100   }
101 
102   /**
103    * @param b Use passed bytes as backing array for this instance.
104    */
105   public void set(final byte [] b) {
106     set(b, 0, b.length);
107   }
108 
109   /**
110    * @param b Use passed bytes as backing array for this instance.
111    * @param offset
112    * @param length
113    */
114   public void set(final byte [] b, final int offset, final int length) {
115     this.bytes = b;
116     this.offset = offset;
117     this.length = length;
118   }
119 
120   /**
121    * @return the number of valid bytes in the buffer
122    * @deprecated since 0.98.5. Use {@link #getLength()} instead
123    * @see #getLength()
124    * @see <a href="https://issues.apache.org/jira/browse/HBASE-11561">HBASE-11561</a>
125    */
126   @Deprecated
127   public int getSize() {
128     if (this.bytes == null) {
129       throw new IllegalStateException("Uninitialiized. Null constructor " +
130         "called w/o accompaying readFields invocation");
131     }
132     return this.length;
133   }
134 
135   /**
136    * @return the number of valid bytes in the buffer
137    */
138   public int getLength() {
139     if (this.bytes == null) {
140       throw new IllegalStateException("Uninitialiized. Null constructor " +
141         "called w/o accompaying readFields invocation");
142     }
143     return this.length;
144   }
145 
146   /**
147    * @return offset
148    */
149   public int getOffset(){
150     return this.offset;
151   }
152 
153   public void readFields(final DataInput in) throws IOException {
154     this.length = in.readInt();
155     this.bytes = new byte[this.length];
156     in.readFully(this.bytes, 0, this.length);
157     this.offset = 0;
158   }
159 
160   public void write(final DataOutput out) throws IOException {
161     out.writeInt(this.length);
162     out.write(this.bytes, this.offset, this.length);
163   }
164 
165   // Below methods copied from BytesWritable
166   @Override
167   public int hashCode() {
168     int hash = 1;
169     for (int i = offset; i < offset + length; i++)
170       hash = (31 * hash) + (int)bytes[i];
171     return hash;
172   }
173 
174   /**
175    * Define the sort order of the BytesWritable.
176    * @param that The other bytes writable
177    * @return Positive if left is bigger than right, 0 if they are equal, and
178    *         negative if left is smaller than right.
179    */
180   public int compareTo(ImmutableBytesWritable that) {
181     return WritableComparator.compareBytes(
182       this.bytes, this.offset, this.length,
183       that.bytes, that.offset, that.length);
184   }
185 
186   /**
187    * Compares the bytes in this object to the specified byte array
188    * @param that
189    * @return Positive if left is bigger than right, 0 if they are equal, and
190    *         negative if left is smaller than right.
191    */
192   public int compareTo(final byte [] that) {
193     return WritableComparator.compareBytes(
194       this.bytes, this.offset, this.length,
195       that, 0, that.length);
196   }
197 
198   /**
199    * @see java.lang.Object#equals(java.lang.Object)
200    */
201   @Override
202   public boolean equals(Object right_obj) {
203     if (right_obj instanceof byte []) {
204       return compareTo((byte [])right_obj) == 0;
205     }
206     if (right_obj instanceof ImmutableBytesWritable) {
207       return compareTo((ImmutableBytesWritable)right_obj) == 0;
208     }
209     return false;
210   }
211 
212   /**
213    * @see java.lang.Object#toString()
214    */
215   @Override
216   public String toString() {
217     StringBuilder sb = new StringBuilder(3*this.length);
218     final int endIdx = this.offset + this.length;
219     for (int idx = this.offset; idx < endIdx ; idx++) {
220       sb.append(' ');
221       String num = Integer.toHexString(0xff & this.bytes[idx]);
222       // if it is only one digit, add a leading 0.
223       if (num.length() < 2) {
224         sb.append('0');
225       }
226       sb.append(num);
227     }
228     return sb.length() > 0 ? sb.substring(1) : "";
229   }
230 
231   /** A Comparator optimized for ImmutableBytesWritable.
232    */
233   @InterfaceAudience.Public
234   @InterfaceStability.Stable
235   public static class Comparator extends WritableComparator {
236     private BytesWritable.Comparator comparator =
237       new BytesWritable.Comparator();
238 
239     /** constructor */
240     public Comparator() {
241       super(ImmutableBytesWritable.class);
242     }
243 
244     /**
245      * @see org.apache.hadoop.io.WritableComparator#compare(byte[], int, int, byte[], int, int)
246      */
247     @Override
248     public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
249       return comparator.compare(b1, s1, l1, b2, s2, l2);
250     }
251   }
252 
253   static { // register this comparator
254     WritableComparator.define(ImmutableBytesWritable.class, new Comparator());
255   }
256 
257   /**
258    * @param array List of byte [].
259    * @return Array of byte [].
260    */
261   public static byte [][] toArray(final List<byte []> array) {
262     // List#toArray doesn't work on lists of byte [].
263     byte[][] results = new byte[array.size()][];
264     for (int i = 0; i < array.size(); i++) {
265       results[i] = array.get(i);
266     }
267     return results;
268   }
269 
270   /**
271    * Returns a copy of the bytes referred to by this writable
272    */
273   public byte[] copyBytes() {
274     return Arrays.copyOfRange(bytes, offset, offset+length);
275   }
276 }