001/*
002 * Copyright (C) 2009 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.checkNotNull;
019import static com.google.common.base.Preconditions.checkPositionIndexes;
020import static java.util.Objects.requireNonNull;
021
022import com.google.common.annotations.GwtIncompatible;
023import com.google.common.annotations.J2ktIncompatible;
024import com.google.common.annotations.VisibleForTesting;
025import com.google.errorprone.annotations.CanIgnoreReturnValue;
026import java.lang.reflect.Field;
027import java.nio.ByteOrder;
028import java.security.AccessController;
029import java.security.PrivilegedActionException;
030import java.security.PrivilegedExceptionAction;
031import java.util.Arrays;
032import java.util.Comparator;
033import sun.misc.Unsafe;
034
035/**
036 * Static utility methods pertaining to {@code byte} primitives that interpret values as
037 * <i>unsigned</i> (that is, any negative value {@code b} is treated as the positive value {@code
038 * 256 + b}). The corresponding methods that treat the values as signed are found in {@link
039 * SignedBytes}, and the methods for which signedness is not an issue are in {@link Bytes}.
040 *
041 * <p>See the Guava User Guide article on <a
042 * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>.
043 *
044 * @author Kevin Bourrillion
045 * @author Martin Buchholz
046 * @author Hiroshi Yamauchi
047 * @author Louis Wasserman
048 * @since 1.0
049 */
050@J2ktIncompatible
051@GwtIncompatible
052@ElementTypesAreNonnullByDefault
053public final class UnsignedBytes {
054  private UnsignedBytes() {}
055
056  /**
057   * The largest power of two that can be represented as an unsigned {@code byte}.
058   *
059   * @since 10.0
060   */
061  public static final byte MAX_POWER_OF_TWO = (byte) 0x80;
062
063  /**
064   * The largest value that fits into an unsigned byte.
065   *
066   * @since 13.0
067   */
068  public static final byte MAX_VALUE = (byte) 0xFF;
069
070  private static final int UNSIGNED_MASK = 0xFF;
071
072  /**
073   * Returns the value of the given byte as an integer, when treated as unsigned. That is, returns
074   * {@code value + 256} if {@code value} is negative; {@code value} itself otherwise.
075   *
076   * <p><b>Java 8+ users:</b> use {@link Byte#toUnsignedInt(byte)} instead.
077   *
078   * @since 6.0
079   */
080  public static int toInt(byte value) {
081    return value & UNSIGNED_MASK;
082  }
083
084  /**
085   * Returns the {@code byte} value that, when treated as unsigned, is equal to {@code value}, if
086   * possible.
087   *
088   * @param value a value between 0 and 255 inclusive
089   * @return the {@code byte} value that, when treated as unsigned, equals {@code value}
090   * @throws IllegalArgumentException if {@code value} is negative or greater than 255
091   */
092  @CanIgnoreReturnValue
093  public static byte checkedCast(long value) {
094    checkArgument(value >> Byte.SIZE == 0, "out of range: %s", value);
095    return (byte) value;
096  }
097
098  /**
099   * Returns the {@code byte} value that, when treated as unsigned, is nearest in value to {@code
100   * value}.
101   *
102   * @param value any {@code long} value
103   * @return {@code (byte) 255} if {@code value >= 255}, {@code (byte) 0} if {@code value <= 0}, and
104   *     {@code value} cast to {@code byte} otherwise
105   */
106  public static byte saturatedCast(long value) {
107    if (value > toInt(MAX_VALUE)) {
108      return MAX_VALUE; // -1
109    }
110    if (value < 0) {
111      return (byte) 0;
112    }
113    return (byte) value;
114  }
115
116  /**
117   * Compares the two specified {@code byte} values, treating them as unsigned values between 0 and
118   * 255 inclusive. For example, {@code (byte) -127} is considered greater than {@code (byte) 127}
119   * because it is seen as having the value of positive {@code 129}.
120   *
121   * @param a the first {@code byte} to compare
122   * @param b the second {@code byte} to compare
123   * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is
124   *     greater than {@code b}; or zero if they are equal
125   */
126  public static int compare(byte a, byte b) {
127    return toInt(a) - toInt(b);
128  }
129
130  /**
131   * Returns the least value present in {@code array}, treating values as unsigned.
132   *
133   * @param array a <i>nonempty</i> array of {@code byte} values
134   * @return the value present in {@code array} that is less than or equal to every other value in
135   *     the array according to {@link #compare}
136   * @throws IllegalArgumentException if {@code array} is empty
137   */
138  public static byte min(byte... array) {
139    checkArgument(array.length > 0);
140    int min = toInt(array[0]);
141    for (int i = 1; i < array.length; i++) {
142      int next = toInt(array[i]);
143      if (next < min) {
144        min = next;
145      }
146    }
147    return (byte) min;
148  }
149
150  /**
151   * Returns the greatest value present in {@code array}, treating values as unsigned.
152   *
153   * @param array a <i>nonempty</i> array of {@code byte} values
154   * @return the value present in {@code array} that is greater than or equal to every other value
155   *     in the array according to {@link #compare}
156   * @throws IllegalArgumentException if {@code array} is empty
157   */
158  public static byte max(byte... array) {
159    checkArgument(array.length > 0);
160    int max = toInt(array[0]);
161    for (int i = 1; i < array.length; i++) {
162      int next = toInt(array[i]);
163      if (next > max) {
164        max = next;
165      }
166    }
167    return (byte) max;
168  }
169
170  /**
171   * Returns a string representation of x, where x is treated as unsigned.
172   *
173   * @since 13.0
174   */
175  public static String toString(byte x) {
176    return toString(x, 10);
177  }
178
179  /**
180   * Returns a string representation of {@code x} for the given radix, where {@code x} is treated as
181   * unsigned.
182   *
183   * @param x the value to convert to a string.
184   * @param radix the radix to use while working with {@code x}
185   * @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX}
186   *     and {@link Character#MAX_RADIX}.
187   * @since 13.0
188   */
189  public static String toString(byte x, int radix) {
190    checkArgument(
191        radix >= Character.MIN_RADIX && radix <= Character.MAX_RADIX,
192        "radix (%s) must be between Character.MIN_RADIX and Character.MAX_RADIX",
193        radix);
194    // Benchmarks indicate this is probably not worth optimizing.
195    return Integer.toString(toInt(x), radix);
196  }
197
198  /**
199   * Returns the unsigned {@code byte} value represented by the given decimal string.
200   *
201   * @throws NumberFormatException if the string does not contain a valid unsigned {@code byte}
202   *     value
203   * @throws NullPointerException if {@code string} is null (in contrast to {@link
204   *     Byte#parseByte(String)})
205   * @since 13.0
206   */
207  @CanIgnoreReturnValue
208  public static byte parseUnsignedByte(String string) {
209    return parseUnsignedByte(string, 10);
210  }
211
212  /**
213   * Returns the unsigned {@code byte} value represented by a string with the given radix.
214   *
215   * @param string the string containing the unsigned {@code byte} representation to be parsed.
216   * @param radix the radix to use while parsing {@code string}
217   * @throws NumberFormatException if the string does not contain a valid unsigned {@code byte} with
218   *     the given radix, or if {@code radix} is not between {@link Character#MIN_RADIX} and {@link
219   *     Character#MAX_RADIX}.
220   * @throws NullPointerException if {@code string} is null (in contrast to {@link
221   *     Byte#parseByte(String)})
222   * @since 13.0
223   */
224  @CanIgnoreReturnValue
225  public static byte parseUnsignedByte(String string, int radix) {
226    int parse = Integer.parseInt(checkNotNull(string), radix);
227    // We need to throw a NumberFormatException, so we have to duplicate checkedCast. =(
228    if (parse >> Byte.SIZE == 0) {
229      return (byte) parse;
230    } else {
231      throw new NumberFormatException("out of range: " + parse);
232    }
233  }
234
235  /**
236   * Returns a string containing the supplied {@code byte} values separated by {@code separator}.
237   * For example, {@code join(":", (byte) 1, (byte) 2, (byte) 255)} returns the string {@code
238   * "1:2:255"}.
239   *
240   * @param separator the text that should appear between consecutive values in the resulting string
241   *     (but not at the start or end)
242   * @param array an array of {@code byte} values, possibly empty
243   */
244  public static String join(String separator, byte... array) {
245    checkNotNull(separator);
246    if (array.length == 0) {
247      return "";
248    }
249
250    // For pre-sizing a builder, just get the right order of magnitude
251    StringBuilder builder = new StringBuilder(array.length * (3 + separator.length()));
252    builder.append(toInt(array[0]));
253    for (int i = 1; i < array.length; i++) {
254      builder.append(separator).append(toString(array[i]));
255    }
256    return builder.toString();
257  }
258
259  /**
260   * Returns a comparator that compares two {@code byte} arrays <a
261   * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it
262   * compares, using {@link #compare(byte, byte)}), the first pair of values that follow any common
263   * prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For
264   * example, {@code [] < [0x01] < [0x01, 0x7F] < [0x01, 0x80] < [0x02]}. Values are treated as
265   * unsigned.
266   *
267   * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
268   * support only identity equality), but it is consistent with {@link
269   * java.util.Arrays#equals(byte[], byte[])}.
270   *
271   * @since 2.0
272   */
273  public static Comparator<byte[]> lexicographicalComparator() {
274    return LexicographicalComparatorHolder.BEST_COMPARATOR;
275  }
276
277  @VisibleForTesting
278  static Comparator<byte[]> lexicographicalComparatorJavaImpl() {
279    return LexicographicalComparatorHolder.PureJavaComparator.INSTANCE;
280  }
281
282  /**
283   * Provides a lexicographical comparator implementation; either a Java implementation or a faster
284   * implementation based on {@link Unsafe}.
285   *
286   * <p>Uses reflection to gracefully fall back to the Java implementation if {@code Unsafe} isn't
287   * available.
288   */
289  @VisibleForTesting
290  static class LexicographicalComparatorHolder {
291    static final String UNSAFE_COMPARATOR_NAME =
292        LexicographicalComparatorHolder.class.getName() + "$UnsafeComparator";
293
294    static final Comparator<byte[]> BEST_COMPARATOR = getBestComparator();
295
296    @SuppressWarnings({"SunApi", "removal"}) // b/345822163
297    @VisibleForTesting
298    enum UnsafeComparator implements Comparator<byte[]> {
299      INSTANCE;
300
301      static final boolean BIG_ENDIAN = ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN);
302
303      /*
304       * The following static final fields exist for performance reasons.
305       *
306       * In UnsignedBytesBenchmark, accessing the following objects via static final fields is the
307       * fastest (more than twice as fast as the Java implementation, vs ~1.5x with non-final static
308       * fields, on x86_32) under the Hotspot server compiler. The reason is obviously that the
309       * non-final fields need to be reloaded inside the loop.
310       *
311       * And, no, defining (final or not) local variables out of the loop still isn't as good
312       * because the null check on the theUnsafe object remains inside the loop and
313       * BYTE_ARRAY_BASE_OFFSET doesn't get constant-folded.
314       *
315       * The compiler can treat static final fields as compile-time constants and can constant-fold
316       * them while (final or not) local variables are run time values.
317       */
318
319      static final Unsafe theUnsafe = getUnsafe();
320
321      /** The offset to the first element in a byte array. */
322      static final int BYTE_ARRAY_BASE_OFFSET = theUnsafe.arrayBaseOffset(byte[].class);
323
324      static {
325        // fall back to the safer pure java implementation unless we're in
326        // a 64-bit JVM with an 8-byte aligned field offset.
327        if (!("64".equals(System.getProperty("sun.arch.data.model"))
328            && (BYTE_ARRAY_BASE_OFFSET % 8) == 0
329            // sanity check - this should never fail
330            && theUnsafe.arrayIndexScale(byte[].class) == 1)) {
331          throw new Error(); // force fallback to PureJavaComparator
332        }
333      }
334
335      /**
336       * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. Replace with a simple
337       * call to Unsafe.getUnsafe when integrating into a jdk.
338       *
339       * @return a sun.misc.Unsafe
340       */
341      private static Unsafe getUnsafe() {
342        try {
343          return Unsafe.getUnsafe();
344        } catch (SecurityException e) {
345          // that's okay; try reflection instead
346        }
347        try {
348          return AccessController.doPrivileged(
349              new PrivilegedExceptionAction<Unsafe>() {
350                @Override
351                public Unsafe run() throws Exception {
352                  Class<Unsafe> k = Unsafe.class;
353                  for (Field f : k.getDeclaredFields()) {
354                    f.setAccessible(true);
355                    Object x = f.get(null);
356                    if (k.isInstance(x)) {
357                      return k.cast(x);
358                    }
359                  }
360                  throw new NoSuchFieldError("the Unsafe");
361                }
362              });
363        } catch (PrivilegedActionException e) {
364          throw new RuntimeException("Could not initialize intrinsics", e.getCause());
365        }
366      }
367
368      @Override
369      // Long.compareUnsigned is available under Android, which is what we really care about.
370      @SuppressWarnings("Java7ApiChecker")
371      public int compare(byte[] left, byte[] right) {
372        int stride = 8;
373        int minLength = Math.min(left.length, right.length);
374        int strideLimit = minLength & ~(stride - 1);
375        int i;
376
377        /*
378         * Compare 8 bytes at a time. Benchmarking on x86 shows a stride of 8 bytes is no slower
379         * than 4 bytes even on 32-bit. On the other hand, it is substantially faster on 64-bit.
380         */
381        for (i = 0; i < strideLimit; i += stride) {
382          long lw = theUnsafe.getLong(left, BYTE_ARRAY_BASE_OFFSET + (long) i);
383          long rw = theUnsafe.getLong(right, BYTE_ARRAY_BASE_OFFSET + (long) i);
384          if (lw != rw) {
385            if (BIG_ENDIAN) {
386              return Long.compareUnsigned(lw, rw);
387            }
388
389            /*
390             * We want to compare only the first index where left[index] != right[index]. This
391             * corresponds to the least significant nonzero byte in lw ^ rw, since lw and rw are
392             * little-endian. Long.numberOfTrailingZeros(diff) tells us the least significant
393             * nonzero bit, and zeroing out the first three bits of L.nTZ gives us the shift to get
394             * that least significant nonzero byte.
395             */
396            int n = Long.numberOfTrailingZeros(lw ^ rw) & ~0x7;
397            return ((int) ((lw >>> n) & UNSIGNED_MASK)) - ((int) ((rw >>> n) & UNSIGNED_MASK));
398          }
399        }
400
401        // The epilogue to cover the last (minLength % stride) elements.
402        for (; i < minLength; i++) {
403          int result = UnsignedBytes.compare(left[i], right[i]);
404          if (result != 0) {
405            return result;
406          }
407        }
408        return left.length - right.length;
409      }
410
411      @Override
412      public String toString() {
413        return "UnsignedBytes.lexicographicalComparator() (sun.misc.Unsafe version)";
414      }
415    }
416
417    enum PureJavaComparator implements Comparator<byte[]> {
418      INSTANCE;
419
420      @Override
421      public int compare(byte[] left, byte[] right) {
422        int minLength = Math.min(left.length, right.length);
423        for (int i = 0; i < minLength; i++) {
424          int result = UnsignedBytes.compare(left[i], right[i]);
425          if (result != 0) {
426            return result;
427          }
428        }
429        return left.length - right.length;
430      }
431
432      @Override
433      public String toString() {
434        return "UnsignedBytes.lexicographicalComparator() (pure Java version)";
435      }
436    }
437
438    /**
439     * Returns the Unsafe-using Comparator, or falls back to the pure-Java implementation if unable
440     * to do so.
441     */
442    static Comparator<byte[]> getBestComparator() {
443      try {
444        Class<?> theClass = Class.forName(UNSAFE_COMPARATOR_NAME);
445
446        // requireNonNull is safe because the class is an enum.
447        Object[] constants = requireNonNull(theClass.getEnumConstants());
448
449        // yes, UnsafeComparator does implement Comparator<byte[]>
450        @SuppressWarnings("unchecked")
451        Comparator<byte[]> comparator = (Comparator<byte[]>) constants[0];
452        return comparator;
453      } catch (Throwable t) { // ensure we really catch *everything*
454        return lexicographicalComparatorJavaImpl();
455      }
456    }
457  }
458
459  private static byte flip(byte b) {
460    return (byte) (b ^ 0x80);
461  }
462
463  /**
464   * Sorts the array, treating its elements as unsigned bytes.
465   *
466   * @since 23.1
467   */
468  public static void sort(byte[] array) {
469    checkNotNull(array);
470    sort(array, 0, array.length);
471  }
472
473  /**
474   * Sorts the array between {@code fromIndex} inclusive and {@code toIndex} exclusive, treating its
475   * elements as unsigned bytes.
476   *
477   * @since 23.1
478   */
479  public static void sort(byte[] array, int fromIndex, int toIndex) {
480    checkNotNull(array);
481    checkPositionIndexes(fromIndex, toIndex, array.length);
482    for (int i = fromIndex; i < toIndex; i++) {
483      array[i] = flip(array[i]);
484    }
485    Arrays.sort(array, fromIndex, toIndex);
486    for (int i = fromIndex; i < toIndex; i++) {
487      array[i] = flip(array[i]);
488    }
489  }
490
491  /**
492   * Sorts the elements of {@code array} in descending order, interpreting them as unsigned 8-bit
493   * integers.
494   *
495   * @since 23.1
496   */
497  public static void sortDescending(byte[] array) {
498    checkNotNull(array);
499    sortDescending(array, 0, array.length);
500  }
501
502  /**
503   * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
504   * exclusive in descending order, interpreting them as unsigned 8-bit integers.
505   *
506   * @since 23.1
507   */
508  public static void sortDescending(byte[] array, int fromIndex, int toIndex) {
509    checkNotNull(array);
510    checkPositionIndexes(fromIndex, toIndex, array.length);
511    for (int i = fromIndex; i < toIndex; i++) {
512      array[i] ^= Byte.MAX_VALUE;
513    }
514    Arrays.sort(array, fromIndex, toIndex);
515    for (int i = fromIndex; i < toIndex; i++) {
516      array[i] ^= Byte.MAX_VALUE;
517    }
518  }
519}