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   */
160  public static byte[] concat(byte[]... arrays) {
161    int length = 0;
162    for (byte[] array : arrays) {
163      length += array.length;
164    }
165    byte[] result = new byte[length];
166    int pos = 0;
167    for (byte[] array : arrays) {
168      System.arraycopy(array, 0, result, pos, array.length);
169      pos += array.length;
170    }
171    return result;
172  }
173
174  /**
175   * Returns an array containing the same values as {@code array}, but guaranteed to be of a
176   * specified minimum length. If {@code array} already has a length of at least {@code minLength},
177   * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is
178   * returned, containing the values of {@code array}, and zeroes in the remaining places.
179   *
180   * @param array the source array
181   * @param minLength the minimum length the returned array must guarantee
182   * @param padding an extra amount to "grow" the array by if growth is necessary
183   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative
184   * @return an array containing the values of {@code array}, with guaranteed minimum length {@code
185   *     minLength}
186   */
187  public static byte[] ensureCapacity(byte[] array, int minLength, int padding) {
188    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
189    checkArgument(padding >= 0, "Invalid padding: %s", padding);
190    return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array;
191  }
192
193  /**
194   * Returns an array containing each value of {@code collection}, converted to a {@code byte} value
195   * in the manner of {@link Number#byteValue}.
196   *
197   * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}.
198   * Calling this method is as thread-safe as calling that method.
199   *
200   * @param collection a collection of {@code Number} instances
201   * @return an array containing the same values as {@code collection}, in the same order, converted
202   *     to primitives
203   * @throws NullPointerException if {@code collection} or any of its elements is null
204   * @since 1.0 (parameter was {@code Collection<Byte>} before 12.0)
205   */
206  public static byte[] toArray(Collection<? extends Number> collection) {
207    if (collection instanceof ByteArrayAsList) {
208      return ((ByteArrayAsList) collection).toByteArray();
209    }
210
211    Object[] boxedArray = collection.toArray();
212    int len = boxedArray.length;
213    byte[] array = new byte[len];
214    for (int i = 0; i < len; i++) {
215      // checkNotNull for GWT (do not optimize)
216      array[i] = ((Number) checkNotNull(boxedArray[i])).byteValue();
217    }
218    return array;
219  }
220
221  /**
222   * Returns a fixed-size list backed by the specified array, similar to {@link
223   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
224   * set a value to {@code null} will result in a {@link NullPointerException}.
225   *
226   * <p>The returned list maintains the values, but not the identities, of {@code Byte} objects
227   * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
228   * the returned list is unspecified.
229   *
230   * <p>The returned list is serializable.
231   *
232   * @param backingArray the array to back the list
233   * @return a list view of the array
234   */
235  public static List<Byte> asList(byte... backingArray) {
236    if (backingArray.length == 0) {
237      return Collections.emptyList();
238    }
239    return new ByteArrayAsList(backingArray);
240  }
241
242  @GwtCompatible
243  private static class ByteArrayAsList extends AbstractList<Byte>
244      implements RandomAccess, Serializable {
245    final byte[] array;
246    final int start;
247    final int end;
248
249    ByteArrayAsList(byte[] array) {
250      this(array, 0, array.length);
251    }
252
253    ByteArrayAsList(byte[] array, int start, int end) {
254      this.array = array;
255      this.start = start;
256      this.end = end;
257    }
258
259    @Override
260    public int size() {
261      return end - start;
262    }
263
264    @Override
265    public boolean isEmpty() {
266      return false;
267    }
268
269    @Override
270    public Byte get(int index) {
271      checkElementIndex(index, size());
272      return array[start + index];
273    }
274
275    @Override
276    public boolean contains(@CheckForNull Object target) {
277      // Overridden to prevent a ton of boxing
278      return (target instanceof Byte) && Bytes.indexOf(array, (Byte) target, start, end) != -1;
279    }
280
281    @Override
282    public int indexOf(@CheckForNull Object target) {
283      // Overridden to prevent a ton of boxing
284      if (target instanceof Byte) {
285        int i = Bytes.indexOf(array, (Byte) target, start, end);
286        if (i >= 0) {
287          return i - start;
288        }
289      }
290      return -1;
291    }
292
293    @Override
294    public int lastIndexOf(@CheckForNull Object target) {
295      // Overridden to prevent a ton of boxing
296      if (target instanceof Byte) {
297        int i = Bytes.lastIndexOf(array, (Byte) target, start, end);
298        if (i >= 0) {
299          return i - start;
300        }
301      }
302      return -1;
303    }
304
305    @Override
306    public Byte set(int index, Byte element) {
307      checkElementIndex(index, size());
308      byte oldValue = array[start + index];
309      // checkNotNull for GWT (do not optimize)
310      array[start + index] = checkNotNull(element);
311      return oldValue;
312    }
313
314    @Override
315    public List<Byte> subList(int fromIndex, int toIndex) {
316      int size = size();
317      checkPositionIndexes(fromIndex, toIndex, size);
318      if (fromIndex == toIndex) {
319        return Collections.emptyList();
320      }
321      return new ByteArrayAsList(array, start + fromIndex, start + toIndex);
322    }
323
324    @Override
325    public boolean equals(@CheckForNull Object object) {
326      if (object == this) {
327        return true;
328      }
329      if (object instanceof ByteArrayAsList) {
330        ByteArrayAsList that = (ByteArrayAsList) object;
331        int size = size();
332        if (that.size() != size) {
333          return false;
334        }
335        for (int i = 0; i < size; i++) {
336          if (array[start + i] != that.array[that.start + i]) {
337            return false;
338          }
339        }
340        return true;
341      }
342      return super.equals(object);
343    }
344
345    @Override
346    public int hashCode() {
347      int result = 1;
348      for (int i = start; i < end; i++) {
349        result = 31 * result + Bytes.hashCode(array[i]);
350      }
351      return result;
352    }
353
354    @Override
355    public String toString() {
356      StringBuilder builder = new StringBuilder(size() * 5);
357      builder.append('[').append(array[start]);
358      for (int i = start + 1; i < end; i++) {
359        builder.append(", ").append(array[i]);
360      }
361      return builder.append(']').toString();
362    }
363
364    byte[] toByteArray() {
365      return Arrays.copyOfRange(array, start, end);
366    }
367
368    private static final long serialVersionUID = 0;
369  }
370
371  /**
372   * Reverses the elements of {@code array}. This is equivalent to {@code
373   * Collections.reverse(Bytes.asList(array))}, but is likely to be more efficient.
374   *
375   * @since 23.1
376   */
377  public static void reverse(byte[] array) {
378    checkNotNull(array);
379    reverse(array, 0, array.length);
380  }
381
382  /**
383   * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
384   * exclusive. This is equivalent to {@code
385   * Collections.reverse(Bytes.asList(array).subList(fromIndex, toIndex))}, but is likely to be more
386   * efficient.
387   *
388   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
389   *     {@code toIndex > fromIndex}
390   * @since 23.1
391   */
392  public static void reverse(byte[] array, int fromIndex, int toIndex) {
393    checkNotNull(array);
394    checkPositionIndexes(fromIndex, toIndex, array.length);
395    for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) {
396      byte tmp = array[i];
397      array[i] = array[j];
398      array[j] = tmp;
399    }
400  }
401
402  /**
403   * Performs a right rotation of {@code array} of "distance" places, so that the first element is
404   * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
405   * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Bytes.asList(array),
406   * distance)}, but is somewhat faster.
407   *
408   * <p>The provided "distance" may be negative, which will rotate left.
409   *
410   * @since 32.0.0
411   */
412  public static void rotate(byte[] array, int distance) {
413    rotate(array, distance, 0, array.length);
414  }
415
416  /**
417   * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
418   * toIndex} exclusive. This is equivalent to {@code
419   * Collections.rotate(Bytes.asList(array).subList(fromIndex, toIndex), distance)}, but is somewhat
420   * faster.
421   *
422   * <p>The provided "distance" may be negative, which will rotate left.
423   *
424   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
425   *     {@code toIndex > fromIndex}
426   * @since 32.0.0
427   */
428  public static void rotate(byte[] array, int distance, int fromIndex, int toIndex) {
429    // See Ints.rotate for more details about possible algorithms here.
430    checkNotNull(array);
431    checkPositionIndexes(fromIndex, toIndex, array.length);
432    if (array.length <= 1) {
433      return;
434    }
435
436    int length = toIndex - fromIndex;
437    // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
438    // places left to rotate.
439    int m = -distance % length;
440    m = (m < 0) ? m + length : m;
441    // The current index of what will become the first element of the rotated section.
442    int newFirstIndex = m + fromIndex;
443    if (newFirstIndex == fromIndex) {
444      return;
445    }
446
447    reverse(array, fromIndex, newFirstIndex);
448    reverse(array, newFirstIndex, toIndex);
449    reverse(array, fromIndex, toIndex);
450  }
451}