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