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