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