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