View Javadoc

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