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