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.util; 019 020import java.io.IOException; 021import java.io.OutputStream; 022import java.util.ArrayList; 023import java.util.Collection; 024import org.apache.yetus.audience.InterfaceAudience; 025 026import org.apache.hbase.thirdparty.com.google.common.collect.Lists; 027 028/** 029 * Utility methods for working with {@link ByteRange}. 030 */ 031@InterfaceAudience.Public 032public class ByteRangeUtils { 033 public static int numEqualPrefixBytes(ByteRange left, ByteRange right, int rightInnerOffset) { 034 int maxCompares = Math.min(left.getLength(), right.getLength() - rightInnerOffset); 035 final byte[] lbytes = left.getBytes(); 036 final byte[] rbytes = right.getBytes(); 037 final int loffset = left.getOffset(); 038 final int roffset = right.getOffset(); 039 for (int i = 0; i < maxCompares; ++i) { 040 if (lbytes[loffset + i] != rbytes[roffset + rightInnerOffset + i]) { 041 return i; 042 } 043 } 044 return maxCompares; 045 } 046 047 public static ArrayList<byte[]> copyToNewArrays(Collection<ByteRange> ranges) { 048 if (ranges == null) { 049 return new ArrayList<>(0); 050 } 051 ArrayList<byte[]> arrays = Lists.newArrayListWithCapacity(ranges.size()); 052 for (ByteRange range : ranges) { 053 arrays.add(range.deepCopyToNewArray()); 054 } 055 return arrays; 056 } 057 058 public static ArrayList<ByteRange> fromArrays(Collection<byte[]> arrays) { 059 if (arrays == null) { 060 return new ArrayList<>(0); 061 } 062 ArrayList<ByteRange> ranges = Lists.newArrayListWithCapacity(arrays.size()); 063 for (byte[] array : arrays) { 064 ranges.add(new SimpleMutableByteRange(array)); 065 } 066 return ranges; 067 } 068 069 public static void write(OutputStream os, ByteRange byteRange) throws IOException { 070 os.write(byteRange.getBytes(), byteRange.getOffset(), byteRange.getLength()); 071 } 072 073 public static void write(OutputStream os, ByteRange byteRange, int byteRangeInnerOffset) 074 throws IOException { 075 os.write(byteRange.getBytes(), byteRange.getOffset() + byteRangeInnerOffset, 076 byteRange.getLength() - byteRangeInnerOffset); 077 } 078}