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