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  /** Use passed bytes as backing array for this instance. */
095  public void set(final byte[] b) {
096    set(b, 0, b.length);
097  }
098
099  /** Use passed bytes as backing array for this instance. */
100  public void set(final byte[] b, final int offset, final int length) {
101    this.bytes = b;
102    this.offset = offset;
103    this.length = length;
104  }
105
106  /**
107   * @return the number of valid bytes in the buffer
108   * @deprecated since 0.98.5. Use {@link #getLength()} instead
109   * @see #getLength()
110   * @see <a href="https://issues.apache.org/jira/browse/HBASE-11561">HBASE-11561</a>
111   */
112  @Deprecated
113  public int getSize() {
114    if (this.bytes == null) {
115      throw new IllegalStateException(
116        "Uninitialiized. Null constructor " + "called w/o accompaying readFields invocation");
117    }
118    return this.length;
119  }
120
121  /** Returns the number of valid bytes in the buffer */
122  public int getLength() {
123    if (this.bytes == null) {
124      throw new IllegalStateException(
125        "Uninitialiized. Null constructor " + "called w/o accompaying readFields invocation");
126    }
127    return this.length;
128  }
129
130  /** Return the offset into the buffer. */
131  public int getOffset() {
132    return this.offset;
133  }
134
135  @Override
136  public void readFields(final DataInput in) throws IOException {
137    this.length = in.readInt();
138    this.bytes = new byte[this.length];
139    in.readFully(this.bytes, 0, this.length);
140    this.offset = 0;
141  }
142
143  @Override
144  public void write(final DataOutput out) throws IOException {
145    out.writeInt(this.length);
146    out.write(this.bytes, this.offset, this.length);
147  }
148
149  // Below methods copied from BytesWritable
150
151  @Override
152  public int hashCode() {
153    int hash = 1;
154    for (int i = offset; i < offset + length; i++)
155      hash = (31 * hash) + (int) bytes[i];
156    return hash;
157  }
158
159  /**
160   * Define the sort order of the BytesWritable.
161   * @param that The other bytes writable
162   * @return Positive if left is bigger than right, 0 if they are equal, and negative if left is
163   *         smaller than right.
164   */
165  @Override
166  public int compareTo(ImmutableBytesWritable that) {
167    return WritableComparator.compareBytes(this.bytes, this.offset, this.length, that.bytes,
168      that.offset, that.length);
169  }
170
171  /**
172   * Compares the bytes in this object to the specified byte array n * @return Positive if left is
173   * bigger than right, 0 if they are equal, and negative if left is smaller than right.
174   */
175  public int compareTo(final byte[] that) {
176    return WritableComparator.compareBytes(this.bytes, this.offset, this.length, that, 0,
177      that.length);
178  }
179
180  @Override
181  public boolean equals(Object right_obj) {
182    if (right_obj instanceof byte[]) {
183      return compareTo((byte[]) right_obj) == 0;
184    }
185    if (right_obj instanceof ImmutableBytesWritable) {
186      return compareTo((ImmutableBytesWritable) right_obj) == 0;
187    }
188    return false;
189  }
190
191  @Override
192  public String toString() {
193    StringBuilder sb = new StringBuilder(3 * this.length);
194    final int endIdx = this.offset + this.length;
195    for (int idx = this.offset; idx < endIdx; idx++) {
196      sb.append(' ');
197      String num = Integer.toHexString(0xff & this.bytes[idx]);
198      // if it is only one digit, add a leading 0.
199      if (num.length() < 2) {
200        sb.append('0');
201      }
202      sb.append(num);
203    }
204    return sb.length() > 0 ? sb.substring(1) : "";
205  }
206
207  /** A Comparator optimized for ImmutableBytesWritable. */
208  @InterfaceAudience.Public
209  public static class Comparator extends WritableComparator {
210    private BytesWritable.Comparator comparator = new BytesWritable.Comparator();
211
212    public Comparator() {
213      super(ImmutableBytesWritable.class);
214    }
215
216    @Override
217    public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
218      return comparator.compare(b1, s1, l1, b2, s2, l2);
219    }
220  }
221
222  static { // register this comparator
223    WritableComparator.define(ImmutableBytesWritable.class, new Comparator());
224  }
225
226  /**
227   * Convert a list of byte arrays into an array of byte arrays
228   * @param array List of byte [].
229   * @return Array of byte [].
230   */
231  public static byte[][] toArray(final List<byte[]> array) {
232    // List#toArray doesn't work on lists of byte [].
233    byte[][] results = new byte[array.size()][];
234    for (int i = 0; i < array.size(); i++) {
235      results[i] = array.get(i);
236    }
237    return results;
238  }
239
240  /** Returns a copy of the bytes referred to by this writable */
241  public byte[] copyBytes() {
242    return Arrays.copyOfRange(bytes, offset, offset + length);
243  }
244}