001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.apache.hadoop.hbase.io;
020
021import java.io.DataInput;
022import java.io.DataOutput;
023import java.io.IOException;
024import java.util.Arrays;
025import java.util.List;
026
027import org.apache.hadoop.io.BytesWritable;
028import org.apache.hadoop.io.WritableComparable;
029import org.apache.hadoop.io.WritableComparator;
030import org.apache.yetus.audience.InterfaceAudience;
031
032/**
033 * A byte sequence that is usable as a key or value.  Based on
034 * {@link org.apache.hadoop.io.BytesWritable} only this class is NOT resizable
035 * and DOES NOT distinguish between the size of the sequence and the current
036 * capacity as {@link org.apache.hadoop.io.BytesWritable} does. Hence its
037 * comparatively 'immutable'. When creating a new instance of this class,
038 * the underlying byte [] is not copied, just referenced.  The backing
039 * buffer is accessed when we go to serialize.
040 */
041@InterfaceAudience.Public
042@edu.umd.cs.findbugs.annotations.SuppressWarnings(
043    value="EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS",
044    justification="It has been like this forever")
045public class ImmutableBytesWritable
046implements WritableComparable<ImmutableBytesWritable> {
047  private byte[] bytes;
048  private int offset;
049  private int length;
050
051  /**
052   * Create a zero-size sequence.
053   */
054  public ImmutableBytesWritable() {
055    super();
056  }
057
058  /**
059   * Create a ImmutableBytesWritable using the byte array as the initial value.
060   * @param bytes This array becomes the backing storage for the object.
061   */
062  public ImmutableBytesWritable(byte[] bytes) {
063    this(bytes, 0, bytes.length);
064  }
065
066  /**
067   * Set the new ImmutableBytesWritable to the contents of the passed
068   * <code>ibw</code>.
069   * @param ibw the value to set this ImmutableBytesWritable to.
070   */
071  public ImmutableBytesWritable(final ImmutableBytesWritable ibw) {
072    this(ibw.get(), ibw.getOffset(), ibw.getLength());
073  }
074
075  /**
076   * Set the value to a given byte range
077   * @param bytes the new byte range to set to
078   * @param offset the offset in newData to start at
079   * @param length the number of bytes in the range
080   */
081  public ImmutableBytesWritable(final byte[] bytes, final int offset,
082      final int length) {
083    this.bytes = bytes;
084    this.offset = offset;
085    this.length = length;
086  }
087
088  /**
089   * Get the data from the BytesWritable.
090   * @return The data is only valid between offset and offset+length.
091   */
092  public byte [] get() {
093    if (this.bytes == null) {
094      throw new IllegalStateException("Uninitialiized. Null constructor " +
095        "called w/o accompaying readFields invocation");
096    }
097    return this.bytes;
098  }
099
100  /**
101   * @param b Use passed bytes as backing array for this instance.
102   */
103  public void set(final byte [] b) {
104    set(b, 0, b.length);
105  }
106
107  /**
108   * @param b Use passed bytes as backing array for this instance.
109   * @param offset
110   * @param length
111   */
112  public void set(final byte [] b, final int offset, final int length) {
113    this.bytes = b;
114    this.offset = offset;
115    this.length = length;
116  }
117
118  /**
119   * @return the number of valid bytes in the buffer
120   * @deprecated use {@link #getLength()} instead
121   */
122  @Deprecated
123  public int getSize() {
124    if (this.bytes == null) {
125      throw new IllegalStateException("Uninitialiized. Null constructor " +
126        "called w/o accompaying readFields invocation");
127    }
128    return this.length;
129  }
130
131  /**
132   * @return the number of valid bytes in the buffer
133   */
134  public int getLength() {
135    if (this.bytes == null) {
136      throw new IllegalStateException("Uninitialiized. Null constructor " +
137        "called w/o accompaying readFields invocation");
138    }
139    return this.length;
140  }
141
142  /**
143   * @return offset
144   */
145  public int getOffset(){
146    return this.offset;
147  }
148
149  @Override
150  public void readFields(final DataInput in) throws IOException {
151    this.length = in.readInt();
152    this.bytes = new byte[this.length];
153    in.readFully(this.bytes, 0, this.length);
154    this.offset = 0;
155  }
156
157  @Override
158  public void write(final DataOutput out) throws IOException {
159    out.writeInt(this.length);
160    out.write(this.bytes, this.offset, this.length);
161  }
162
163  // Below methods copied from BytesWritable
164  @Override
165  public int hashCode() {
166    int hash = 1;
167    for (int i = offset; i < offset + length; i++)
168      hash = (31 * hash) + (int)bytes[i];
169    return hash;
170  }
171
172  /**
173   * Define the sort order of the BytesWritable.
174   * @param that The other bytes writable
175   * @return Positive if left is bigger than right, 0 if they are equal, and
176   *         negative if left is smaller than right.
177   */
178  @Override
179  public int compareTo(ImmutableBytesWritable that) {
180    return WritableComparator.compareBytes(
181      this.bytes, this.offset, this.length,
182      that.bytes, that.offset, that.length);
183  }
184
185  /**
186   * Compares the bytes in this object to the specified byte array
187   * @param that
188   * @return Positive if left is bigger than right, 0 if they are equal, and
189   *         negative if left is smaller than right.
190   */
191  public int compareTo(final byte [] that) {
192    return WritableComparator.compareBytes(
193      this.bytes, this.offset, this.length,
194      that, 0, that.length);
195  }
196
197  /**
198   * @see java.lang.Object#equals(java.lang.Object)
199   */
200  @Override
201  public boolean equals(Object right_obj) {
202    if (right_obj instanceof byte []) {
203      return compareTo((byte [])right_obj) == 0;
204    }
205    if (right_obj instanceof ImmutableBytesWritable) {
206      return compareTo((ImmutableBytesWritable)right_obj) == 0;
207    }
208    return false;
209  }
210
211  /**
212   * @see java.lang.Object#toString()
213   */
214  @Override
215  public String toString() {
216    StringBuilder sb = new StringBuilder(3*this.length);
217    final int endIdx = this.offset + this.length;
218    for (int idx = this.offset; idx < endIdx ; idx++) {
219      sb.append(' ');
220      String num = Integer.toHexString(0xff & this.bytes[idx]);
221      // if it is only one digit, add a leading 0.
222      if (num.length() < 2) {
223        sb.append('0');
224      }
225      sb.append(num);
226    }
227    return sb.length() > 0 ? sb.substring(1) : "";
228  }
229
230  /** A Comparator optimized for ImmutableBytesWritable.
231   */
232  @InterfaceAudience.Public
233  public static class Comparator extends WritableComparator {
234    private BytesWritable.Comparator comparator =
235      new BytesWritable.Comparator();
236
237    /** constructor */
238    public Comparator() {
239      super(ImmutableBytesWritable.class);
240    }
241
242    /**
243     * @see org.apache.hadoop.io.WritableComparator#compare(byte[], int, int, byte[], int, int)
244     */
245    @Override
246    public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
247      return comparator.compare(b1, s1, l1, b2, s2, l2);
248    }
249  }
250
251  static { // register this comparator
252    WritableComparator.define(ImmutableBytesWritable.class, new Comparator());
253  }
254
255  /**
256   * @param array List of byte [].
257   * @return Array of byte [].
258   */
259  public static byte [][] toArray(final List<byte []> array) {
260    // List#toArray doesn't work on lists of byte [].
261    byte[][] results = new byte[array.size()][];
262    for (int i = 0; i < array.size(); i++) {
263      results[i] = array.get(i);
264    }
265    return results;
266  }
267
268  /**
269   * Returns a copy of the bytes referred to by this writable
270   */
271  public byte[] copyBytes() {
272    return Arrays.copyOfRange(bytes, offset, offset+length);
273  }
274}