001/* 002 * Copyright (C) 2008 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.primitives; 016 017import static com.google.common.base.Preconditions.checkArgument; 018import static com.google.common.base.Preconditions.checkElementIndex; 019import static com.google.common.base.Preconditions.checkNotNull; 020import static com.google.common.base.Preconditions.checkPositionIndexes; 021 022import com.google.common.annotations.GwtCompatible; 023import java.io.Serializable; 024import java.util.AbstractList; 025import java.util.Arrays; 026import java.util.Collection; 027import java.util.Collections; 028import java.util.List; 029import java.util.RandomAccess; 030import javax.annotation.CheckForNull; 031 032/** 033 * Static utility methods pertaining to {@code byte} primitives, that are not already found in 034 * either {@link Byte} or {@link Arrays}, <i>and interpret bytes as neither signed nor unsigned</i>. 035 * The methods which specifically treat bytes as signed or unsigned are found in {@link SignedBytes} 036 * and {@link UnsignedBytes}. 037 * 038 * <p>See the Guava User Guide article on <a 039 * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>. 040 * 041 * @author Kevin Bourrillion 042 * @since 1.0 043 */ 044// TODO(kevinb): how to prevent warning on UnsignedBytes when building GWT 045// javadoc? 046@GwtCompatible 047@ElementTypesAreNonnullByDefault 048public final class Bytes { 049 private Bytes() {} 050 051 /** 052 * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Byte) 053 * value).hashCode()}. 054 * 055 * <p><b>Java 8+ users:</b> use {@link Byte#hashCode(byte)} instead. 056 * 057 * @param value a primitive {@code byte} value 058 * @return a hash code for the value 059 */ 060 public static int hashCode(byte value) { 061 return value; 062 } 063 064 /** 065 * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}. 066 * 067 * @param array an array of {@code byte} values, possibly empty 068 * @param target a primitive {@code byte} value 069 * @return {@code true} if {@code array[i] == target} for some value of {@code i} 070 */ 071 public static boolean contains(byte[] array, byte target) { 072 for (byte value : array) { 073 if (value == target) { 074 return true; 075 } 076 } 077 return false; 078 } 079 080 /** 081 * Returns the index of the first appearance of the value {@code target} in {@code array}. 082 * 083 * @param array an array of {@code byte} values, possibly empty 084 * @param target a primitive {@code byte} value 085 * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no 086 * such index exists. 087 */ 088 public static int indexOf(byte[] array, byte target) { 089 return indexOf(array, target, 0, array.length); 090 } 091 092 // TODO(kevinb): consider making this public 093 private static int indexOf(byte[] array, byte target, int start, int end) { 094 for (int i = start; i < end; i++) { 095 if (array[i] == target) { 096 return i; 097 } 098 } 099 return -1; 100 } 101 102 /** 103 * Returns the start position of the first occurrence of the specified {@code target} within 104 * {@code array}, or {@code -1} if there is no such occurrence. 105 * 106 * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array, 107 * i, i + target.length)} contains exactly the same elements as {@code target}. 108 * 109 * @param array the array to search for the sequence {@code target} 110 * @param target the array to search for as a sub-sequence of {@code array} 111 */ 112 public static int indexOf(byte[] array, byte[] target) { 113 checkNotNull(array, "array"); 114 checkNotNull(target, "target"); 115 if (target.length == 0) { 116 return 0; 117 } 118 119 outer: 120 for (int i = 0; i < array.length - target.length + 1; i++) { 121 for (int j = 0; j < target.length; j++) { 122 if (array[i + j] != target[j]) { 123 continue outer; 124 } 125 } 126 return i; 127 } 128 return -1; 129 } 130 131 /** 132 * Returns the index of the last appearance of the value {@code target} in {@code array}. 133 * 134 * @param array an array of {@code byte} values, possibly empty 135 * @param target a primitive {@code byte} value 136 * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no 137 * such index exists. 138 */ 139 public static int lastIndexOf(byte[] array, byte target) { 140 return lastIndexOf(array, target, 0, array.length); 141 } 142 143 // TODO(kevinb): consider making this public 144 private static int lastIndexOf(byte[] array, byte target, int start, int end) { 145 for (int i = end - 1; i >= start; i--) { 146 if (array[i] == target) { 147 return i; 148 } 149 } 150 return -1; 151 } 152 153 /** 154 * Returns the values from each provided array combined into a single array. For example, {@code 155 * concat(new byte[] {a, b}, new byte[] {}, new byte[] {c}} returns the array {@code {a, b, c}}. 156 * 157 * @param arrays zero or more {@code byte} arrays 158 * @return a single array containing all the values from the source arrays, in order 159 * @throws IllegalArgumentException if the total number of elements in {@code arrays} does not fit 160 * in an {@code int} 161 */ 162 public static byte[] concat(byte[]... arrays) { 163 long length = 0; 164 for (byte[] array : arrays) { 165 length += array.length; 166 } 167 byte[] result = new byte[checkNoOverflow(length)]; 168 int pos = 0; 169 for (byte[] array : arrays) { 170 System.arraycopy(array, 0, result, pos, array.length); 171 pos += array.length; 172 } 173 return result; 174 } 175 176 private static int checkNoOverflow(long result) { 177 checkArgument( 178 result == (int) result, 179 "the total number of elements (%s) in the arrays must fit in an int", 180 result); 181 return (int) result; 182 } 183 184 /** 185 * Returns an array containing the same values as {@code array}, but guaranteed to be of a 186 * specified minimum length. If {@code array} already has a length of at least {@code minLength}, 187 * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is 188 * returned, containing the values of {@code array}, and zeroes in the remaining places. 189 * 190 * @param array the source array 191 * @param minLength the minimum length the returned array must guarantee 192 * @param padding an extra amount to "grow" the array by if growth is necessary 193 * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative 194 * @return an array containing the values of {@code array}, with guaranteed minimum length {@code 195 * minLength} 196 */ 197 public static byte[] ensureCapacity(byte[] array, int minLength, int padding) { 198 checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); 199 checkArgument(padding >= 0, "Invalid padding: %s", padding); 200 return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; 201 } 202 203 /** 204 * Returns an array containing each value of {@code collection}, converted to a {@code byte} value 205 * in the manner of {@link Number#byteValue}. 206 * 207 * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}. 208 * Calling this method is as thread-safe as calling that method. 209 * 210 * @param collection a collection of {@code Number} instances 211 * @return an array containing the same values as {@code collection}, in the same order, converted 212 * to primitives 213 * @throws NullPointerException if {@code collection} or any of its elements is null 214 * @since 1.0 (parameter was {@code Collection<Byte>} before 12.0) 215 */ 216 public static byte[] toArray(Collection<? extends Number> collection) { 217 if (collection instanceof ByteArrayAsList) { 218 return ((ByteArrayAsList) collection).toByteArray(); 219 } 220 221 Object[] boxedArray = collection.toArray(); 222 int len = boxedArray.length; 223 byte[] array = new byte[len]; 224 for (int i = 0; i < len; i++) { 225 // checkNotNull for GWT (do not optimize) 226 array[i] = ((Number) checkNotNull(boxedArray[i])).byteValue(); 227 } 228 return array; 229 } 230 231 /** 232 * Returns a fixed-size list backed by the specified array, similar to {@link 233 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to 234 * set a value to {@code null} will result in a {@link NullPointerException}. 235 * 236 * <p>The returned list maintains the values, but not the identities, of {@code Byte} objects 237 * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for 238 * the returned list is unspecified. 239 * 240 * <p>The returned list is serializable. 241 * 242 * @param backingArray the array to back the list 243 * @return a list view of the array 244 */ 245 public static List<Byte> asList(byte... backingArray) { 246 if (backingArray.length == 0) { 247 return Collections.emptyList(); 248 } 249 return new ByteArrayAsList(backingArray); 250 } 251 252 @GwtCompatible 253 private static class ByteArrayAsList extends AbstractList<Byte> 254 implements RandomAccess, Serializable { 255 final byte[] array; 256 final int start; 257 final int end; 258 259 ByteArrayAsList(byte[] array) { 260 this(array, 0, array.length); 261 } 262 263 ByteArrayAsList(byte[] array, int start, int end) { 264 this.array = array; 265 this.start = start; 266 this.end = end; 267 } 268 269 @Override 270 public int size() { 271 return end - start; 272 } 273 274 @Override 275 public boolean isEmpty() { 276 return false; 277 } 278 279 @Override 280 public Byte get(int index) { 281 checkElementIndex(index, size()); 282 return array[start + index]; 283 } 284 285 @Override 286 public boolean contains(@CheckForNull Object target) { 287 // Overridden to prevent a ton of boxing 288 return (target instanceof Byte) && Bytes.indexOf(array, (Byte) target, start, end) != -1; 289 } 290 291 @Override 292 public int indexOf(@CheckForNull Object target) { 293 // Overridden to prevent a ton of boxing 294 if (target instanceof Byte) { 295 int i = Bytes.indexOf(array, (Byte) target, start, end); 296 if (i >= 0) { 297 return i - start; 298 } 299 } 300 return -1; 301 } 302 303 @Override 304 public int lastIndexOf(@CheckForNull Object target) { 305 // Overridden to prevent a ton of boxing 306 if (target instanceof Byte) { 307 int i = Bytes.lastIndexOf(array, (Byte) target, start, end); 308 if (i >= 0) { 309 return i - start; 310 } 311 } 312 return -1; 313 } 314 315 @Override 316 public Byte set(int index, Byte element) { 317 checkElementIndex(index, size()); 318 byte oldValue = array[start + index]; 319 // checkNotNull for GWT (do not optimize) 320 array[start + index] = checkNotNull(element); 321 return oldValue; 322 } 323 324 @Override 325 public List<Byte> subList(int fromIndex, int toIndex) { 326 int size = size(); 327 checkPositionIndexes(fromIndex, toIndex, size); 328 if (fromIndex == toIndex) { 329 return Collections.emptyList(); 330 } 331 return new ByteArrayAsList(array, start + fromIndex, start + toIndex); 332 } 333 334 @Override 335 public boolean equals(@CheckForNull Object object) { 336 if (object == this) { 337 return true; 338 } 339 if (object instanceof ByteArrayAsList) { 340 ByteArrayAsList that = (ByteArrayAsList) object; 341 int size = size(); 342 if (that.size() != size) { 343 return false; 344 } 345 for (int i = 0; i < size; i++) { 346 if (array[start + i] != that.array[that.start + i]) { 347 return false; 348 } 349 } 350 return true; 351 } 352 return super.equals(object); 353 } 354 355 @Override 356 public int hashCode() { 357 int result = 1; 358 for (int i = start; i < end; i++) { 359 result = 31 * result + Bytes.hashCode(array[i]); 360 } 361 return result; 362 } 363 364 @Override 365 public String toString() { 366 StringBuilder builder = new StringBuilder(size() * 5); 367 builder.append('[').append(array[start]); 368 for (int i = start + 1; i < end; i++) { 369 builder.append(", ").append(array[i]); 370 } 371 return builder.append(']').toString(); 372 } 373 374 byte[] toByteArray() { 375 return Arrays.copyOfRange(array, start, end); 376 } 377 378 private static final long serialVersionUID = 0; 379 } 380 381 /** 382 * Reverses the elements of {@code array}. This is equivalent to {@code 383 * Collections.reverse(Bytes.asList(array))}, but is likely to be more efficient. 384 * 385 * @since 23.1 386 */ 387 public static void reverse(byte[] array) { 388 checkNotNull(array); 389 reverse(array, 0, array.length); 390 } 391 392 /** 393 * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} 394 * exclusive. This is equivalent to {@code 395 * Collections.reverse(Bytes.asList(array).subList(fromIndex, toIndex))}, but is likely to be more 396 * efficient. 397 * 398 * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or 399 * {@code toIndex > fromIndex} 400 * @since 23.1 401 */ 402 public static void reverse(byte[] array, int fromIndex, int toIndex) { 403 checkNotNull(array); 404 checkPositionIndexes(fromIndex, toIndex, array.length); 405 for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) { 406 byte tmp = array[i]; 407 array[i] = array[j]; 408 array[j] = tmp; 409 } 410 } 411 412 /** 413 * Performs a right rotation of {@code array} of "distance" places, so that the first element is 414 * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance 415 * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Bytes.asList(array), 416 * distance)}, but is somewhat faster. 417 * 418 * <p>The provided "distance" may be negative, which will rotate left. 419 * 420 * @since 32.0.0 421 */ 422 public static void rotate(byte[] array, int distance) { 423 rotate(array, distance, 0, array.length); 424 } 425 426 /** 427 * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code 428 * toIndex} exclusive. This is equivalent to {@code 429 * Collections.rotate(Bytes.asList(array).subList(fromIndex, toIndex), distance)}, but is somewhat 430 * faster. 431 * 432 * <p>The provided "distance" may be negative, which will rotate left. 433 * 434 * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or 435 * {@code toIndex > fromIndex} 436 * @since 32.0.0 437 */ 438 public static void rotate(byte[] array, int distance, int fromIndex, int toIndex) { 439 // See Ints.rotate for more details about possible algorithms here. 440 checkNotNull(array); 441 checkPositionIndexes(fromIndex, toIndex, array.length); 442 if (array.length <= 1) { 443 return; 444 } 445 446 int length = toIndex - fromIndex; 447 // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many 448 // places left to rotate. 449 int m = -distance % length; 450 m = (m < 0) ? m + length : m; 451 // The current index of what will become the first element of the rotated section. 452 int newFirstIndex = m + fromIndex; 453 if (newFirstIndex == fromIndex) { 454 return; 455 } 456 457 reverse(array, fromIndex, newFirstIndex); 458 reverse(array, newFirstIndex, toIndex); 459 reverse(array, fromIndex, toIndex); 460 } 461}