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