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 * The portion of this file denoted by 'Copied from com.google.protobuf.CodedInputStream'
019 * is from Protocol Buffers v2.5.0 under the following license
020 *
021 * Copyright 2008 Google Inc.  All rights reserved.
022 * http://code.google.com/p/protobuf/
023 *
024 * Redistribution and use in source and binary forms, with or without
025 * modification, are permitted provided that the following conditions are
026 * met:
027 *
028 *     * Redistributions of source code must retain the above copyright
029 * notice, this list of conditions and the following disclaimer.
030 *     * Redistributions in binary form must reproduce the above
031 * copyright notice, this list of conditions and the following disclaimer
032 * in the documentation and/or other materials provided with the
033 * distribution.
034 *     * Neither the name of Google Inc. nor the names of its
035 * contributors may be used to endorse or promote products derived from
036 * this software without specific prior written permission.
037 *
038 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
039 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
040 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
041 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
042 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
043 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
044 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
045 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
046 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
047 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
048 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
049 *
050 */
051package org.apache.hadoop.hbase.util;
052
053import org.apache.yetus.audience.InterfaceAudience;
054import org.apache.yetus.audience.InterfaceStability;
055
056/**
057 * An abstract implementation of the ByteRange API
058 */
059@InterfaceAudience.Private
060@InterfaceStability.Evolving
061public abstract class AbstractByteRange implements ByteRange {
062  public static final int UNSET_HASH_VALUE = -1;
063
064  // Note to maintainers: Do not make these final, as the intention is to
065  // reuse objects of this class
066
067  /**
068   * The array containing the bytes in this range. It will be >= length.
069   */
070  protected byte[] bytes;
071
072  /**
073   * The index of the first byte in this range. {@code ByteRange.get(0)} will
074   * return bytes[offset].
075   */
076  protected int offset;
077
078  /**
079   * The number of bytes in the range. Offset + length must be <= bytes.length
080   */
081  protected int length;
082
083  /**
084   * Variable for lazy-caching the hashCode of this range. Useful for frequently
085   * used ranges, long-lived ranges, or long ranges.
086   */
087  protected int hash = UNSET_HASH_VALUE;
088
089  //
090  // methods for managing the backing array and range viewport
091  //
092  @Override
093  public byte[] getBytes() {
094    return bytes;
095  }
096
097  @Override
098  public ByteRange set(int capacity) {
099    return set(new byte[capacity]);
100  }
101
102  @Override
103  public ByteRange set(byte[] bytes) {
104    if (null == bytes) {
105      return unset();
106    }
107
108    clearHashCache();
109    this.bytes = bytes;
110    this.offset = 0;
111    this.length = bytes.length;
112    return this;
113  }
114
115  @Override
116  public ByteRange set(byte[] bytes, int offset, int length) {
117    if (null == bytes) {
118      return unset();
119    }
120
121    clearHashCache();
122    this.bytes = bytes;
123    this.offset = offset;
124    this.length = length;
125    return this;
126  }
127
128  @Override
129  public int getOffset() {
130    return offset;
131  }
132
133  @Override
134  public ByteRange setOffset(int offset) {
135    clearHashCache();
136    this.offset = offset;
137    return this;
138  }
139
140  @Override
141  public int getLength() {
142    return length;
143  }
144
145  @Override
146  public ByteRange setLength(int length) {
147    clearHashCache();
148    this.length = length;
149    return this;
150  }
151
152  @Override
153  public boolean isEmpty() {
154    return isEmpty(this);
155  }
156
157  /**
158   * @return true when {@code range} is of zero length, false otherwise.
159   */
160  public static boolean isEmpty(ByteRange range) {
161    return range == null || range.getLength() == 0;
162  }
163
164  //
165  // methods for retrieving data
166  //
167
168  @Override
169  public byte get(int index) {
170    return bytes[offset + index];
171  }
172
173  @Override
174  public ByteRange get(int index, byte[] dst) {
175    if (0 == dst.length) {
176      return this;
177    }
178
179    return get(index, dst, 0, dst.length);
180  }
181
182  @Override
183  public ByteRange get(int index, byte[] dst, int offset, int length) {
184    if (0 == length) {
185      return this;
186    }
187
188    System.arraycopy(this.bytes, this.offset + index, dst, offset, length);
189    return this;
190  }
191
192  @Override
193  public short getShort(int index) {
194    int offset = this.offset + index;
195    short n = 0;
196    n = (short) ((n ^ bytes[offset]) & 0xFF);
197    n = (short) (n << 8);
198    n = (short) ((n ^ bytes[offset + 1]) & 0xFF);
199    return n;
200  }
201
202  @Override
203  public int getInt(int index) {
204    int offset = this.offset + index;
205    int n = 0;
206    for (int i = offset; i < (offset + Bytes.SIZEOF_INT); i++) {
207      n <<= 8;
208      n ^= bytes[i] & 0xFF;
209    }
210    return n;
211  }
212
213  @Override
214  public long getLong(int index) {
215    int offset = this.offset + index;
216    long l = 0;
217    for (int i = offset; i < offset + Bytes.SIZEOF_LONG; i++) {
218      l <<= 8;
219      l ^= bytes[i] & 0xFF;
220    }
221    return l;
222  }
223
224  // Copied from com.google.protobuf.CodedInputStream v2.5.0 readRawVarint64
225  @Override
226  public long getVLong(int index) {
227    int shift = 0;
228    long result = 0;
229    while (shift < 64) {
230      final byte b = get(index++);
231      result |= (long) (b & 0x7F) << shift;
232      if ((b & 0x80) == 0) {
233        break;
234      }
235      shift += 7;
236    }
237    return result;
238  }
239  // end of copied from protobuf
240
241  public static int getVLongSize(long val) {
242    int rPos = 0;
243    while ((val & ~0x7F) != 0) {
244      val >>>= 7;
245      rPos++;
246    }
247    return rPos + 1;
248  }
249
250  //
251  // methods for duplicating the current instance
252  //
253
254  @Override
255  public byte[] deepCopyToNewArray() {
256    byte[] result = new byte[length];
257    System.arraycopy(bytes, offset, result, 0, length);
258    return result;
259  }
260
261  @Override
262  public void deepCopyTo(byte[] destination, int destinationOffset) {
263    System.arraycopy(bytes, offset, destination, destinationOffset, length);
264  }
265
266  @Override
267  public void deepCopySubRangeTo(int innerOffset, int copyLength, byte[] destination,
268      int destinationOffset) {
269    System.arraycopy(bytes, offset + innerOffset, destination, destinationOffset, copyLength);
270  }
271
272  //
273  // methods used for comparison
274  //
275
276  @Override
277  public int hashCode() {
278    if (isHashCached()) {// hash is already calculated and cached
279      return hash;
280    }
281    if (this.isEmpty()) {// return 0 for empty ByteRange
282      hash = 0;
283      return hash;
284    }
285    int off = offset;
286    hash = 0;
287    for (int i = 0; i < length; i++) {
288      hash = 31 * hash + bytes[off++];
289    }
290    return hash;
291  }
292
293  protected boolean isHashCached() {
294    return hash != UNSET_HASH_VALUE;
295  }
296
297  protected void clearHashCache() {
298    hash = UNSET_HASH_VALUE;
299  }
300
301  @Override
302  public boolean equals(Object obj) {
303    if (this == obj) {
304      return true;
305    }
306    if (obj == null) {
307      return false;
308    }
309    if (!(obj instanceof ByteRange)) {
310      return false;
311    }
312    return compareTo((ByteRange) obj) == 0;
313  }
314
315  /**
316   * Bitwise comparison of each byte in the array. Unsigned comparison, not
317   * paying attention to java's signed bytes.
318   */
319  @Override
320  public int compareTo(ByteRange other) {
321    return Bytes.compareTo(bytes, offset, length, other.getBytes(), other.getOffset(),
322        other.getLength());
323  }
324
325  @Override
326  public String toString() {
327    return Bytes.toStringBinary(bytes, offset, length);
328  }
329}