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