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   * @param backingArray the array to back the list
231   * @return a list view of the array
232   */
233  public static List<Byte> asList(byte... backingArray) {
234    if (backingArray.length == 0) {
235      return Collections.emptyList();
236    }
237    return new ByteArrayAsList(backingArray);
238  }
239
240  @GwtCompatible
241  private static class ByteArrayAsList extends AbstractList<Byte>
242      implements RandomAccess, Serializable {
243    final byte[] array;
244    final int start;
245    final int end;
246
247    ByteArrayAsList(byte[] array) {
248      this(array, 0, array.length);
249    }
250
251    ByteArrayAsList(byte[] array, int start, int end) {
252      this.array = array;
253      this.start = start;
254      this.end = end;
255    }
256
257    @Override
258    public int size() {
259      return end - start;
260    }
261
262    @Override
263    public boolean isEmpty() {
264      return false;
265    }
266
267    @Override
268    public Byte get(int index) {
269      checkElementIndex(index, size());
270      return array[start + index];
271    }
272
273    @Override
274    public boolean contains(@CheckForNull Object target) {
275      // Overridden to prevent a ton of boxing
276      return (target instanceof Byte) && Bytes.indexOf(array, (Byte) target, start, end) != -1;
277    }
278
279    @Override
280    public int indexOf(@CheckForNull Object target) {
281      // Overridden to prevent a ton of boxing
282      if (target instanceof Byte) {
283        int i = Bytes.indexOf(array, (Byte) target, start, end);
284        if (i >= 0) {
285          return i - start;
286        }
287      }
288      return -1;
289    }
290
291    @Override
292    public int lastIndexOf(@CheckForNull Object target) {
293      // Overridden to prevent a ton of boxing
294      if (target instanceof Byte) {
295        int i = Bytes.lastIndexOf(array, (Byte) target, start, end);
296        if (i >= 0) {
297          return i - start;
298        }
299      }
300      return -1;
301    }
302
303    @Override
304    public Byte set(int index, Byte element) {
305      checkElementIndex(index, size());
306      byte oldValue = array[start + index];
307      // checkNotNull for GWT (do not optimize)
308      array[start + index] = checkNotNull(element);
309      return oldValue;
310    }
311
312    @Override
313    public List<Byte> subList(int fromIndex, int toIndex) {
314      int size = size();
315      checkPositionIndexes(fromIndex, toIndex, size);
316      if (fromIndex == toIndex) {
317        return Collections.emptyList();
318      }
319      return new ByteArrayAsList(array, start + fromIndex, start + toIndex);
320    }
321
322    @Override
323    public boolean equals(@CheckForNull Object object) {
324      if (object == this) {
325        return true;
326      }
327      if (object instanceof ByteArrayAsList) {
328        ByteArrayAsList that = (ByteArrayAsList) object;
329        int size = size();
330        if (that.size() != size) {
331          return false;
332        }
333        for (int i = 0; i < size; i++) {
334          if (array[start + i] != that.array[that.start + i]) {
335            return false;
336          }
337        }
338        return true;
339      }
340      return super.equals(object);
341    }
342
343    @Override
344    public int hashCode() {
345      int result = 1;
346      for (int i = start; i < end; i++) {
347        result = 31 * result + Bytes.hashCode(array[i]);
348      }
349      return result;
350    }
351
352    @Override
353    public String toString() {
354      StringBuilder builder = new StringBuilder(size() * 5);
355      builder.append('[').append(array[start]);
356      for (int i = start + 1; i < end; i++) {
357        builder.append(", ").append(array[i]);
358      }
359      return builder.append(']').toString();
360    }
361
362    byte[] toByteArray() {
363      return Arrays.copyOfRange(array, start, end);
364    }
365
366    private static final long serialVersionUID = 0;
367  }
368
369  /**
370   * Reverses the elements of {@code array}. This is equivalent to {@code
371   * Collections.reverse(Bytes.asList(array))}, but is likely to be more efficient.
372   *
373   * @since 23.1
374   */
375  public static void reverse(byte[] array) {
376    checkNotNull(array);
377    reverse(array, 0, array.length);
378  }
379
380  /**
381   * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
382   * exclusive. This is equivalent to {@code
383   * Collections.reverse(Bytes.asList(array).subList(fromIndex, toIndex))}, but is likely to be more
384   * efficient.
385   *
386   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
387   *     {@code toIndex > fromIndex}
388   * @since 23.1
389   */
390  public static void reverse(byte[] array, int fromIndex, int toIndex) {
391    checkNotNull(array);
392    checkPositionIndexes(fromIndex, toIndex, array.length);
393    for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) {
394      byte tmp = array[i];
395      array[i] = array[j];
396      array[j] = tmp;
397    }
398  }
399}