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    
017    package com.google.common.primitives;
018    
019    import static com.google.common.base.Preconditions.checkArgument;
020    import static com.google.common.base.Preconditions.checkNotNull;
021    
022    import com.google.common.annotations.VisibleForTesting;
023    
024    import sun.misc.Unsafe;
025    
026    import java.lang.reflect.Field;
027    import java.nio.ByteOrder;
028    import java.security.AccessController;
029    import java.security.PrivilegedAction;
030    import java.util.Comparator;
031    
032    /**
033     * Static utility methods pertaining to {@code byte} primitives that interpret
034     * values as <i>unsigned</i> (that is, any negative value {@code b} is treated
035     * as the positive value {@code 256 + b}). The corresponding methods that treat
036     * the values as signed are found in {@link SignedBytes}, and the methods for
037     * which signedness is not an issue are in {@link Bytes}.
038     *
039     * @author Kevin Bourrillion
040     * @author Martin Buchholz
041     * @author Hiroshi Yamauchi
042     * @since 1
043     */
044    public final class UnsignedBytes {
045      private UnsignedBytes() {}
046    
047      /**
048       * Returns the value of the given byte as an integer, when treated as
049       * unsigned. That is, returns {@code value + 256} if {@code value} is
050       * negative; {@code value} itself otherwise.
051       *
052       * @since 6
053       */
054      public static int toInt(byte value) {
055        return value & 0xFF;
056      }
057    
058      /**
059       * Returns the {@code byte} value that, when treated as unsigned, is equal to
060       * {@code value}, if possible.
061       *
062       * @param value a value between 0 and 255 inclusive
063       * @return the {@code byte} value that, when treated as unsigned, equals
064       *     {@code value}
065       * @throws IllegalArgumentException if {@code value} is negative or greater
066       *     than 255
067       */
068      public static byte checkedCast(long value) {
069        checkArgument(value >> 8 == 0, "out of range: %s", value);
070        return (byte) value;
071      }
072    
073      /**
074       * Returns the {@code byte} value that, when treated as unsigned, is nearest
075       * in value to {@code value}.
076       *
077       * @param value any {@code long} value
078       * @return {@code (byte) 255} if {@code value >= 255}, {@code (byte) 0} if
079       *     {@code value <= 0}, and {@code value} cast to {@code byte} otherwise
080       */
081      public static byte saturatedCast(long value) {
082        if (value > 255) {
083          return (byte) 255; // -1
084        }
085        if (value < 0) {
086          return (byte) 0;
087        }
088        return (byte) value;
089      }
090    
091      /**
092       * Compares the two specified {@code byte} values, treating them as unsigned
093       * values between 0 and 255 inclusive. For example, {@code (byte) -127} is
094       * considered greater than {@code (byte) 127} because it is seen as having
095       * the value of positive {@code 129}.
096       *
097       * @param a the first {@code byte} to compare
098       * @param b the second {@code byte} to compare
099       * @return a negative value if {@code a} is less than {@code b}; a positive
100       *     value if {@code a} is greater than {@code b}; or zero if they are equal
101       */
102      public static int compare(byte a, byte b) {
103        return toInt(a) - toInt(b);
104      }
105    
106      /**
107       * Returns the least value present in {@code array}.
108       *
109       * @param array a <i>nonempty</i> array of {@code byte} values
110       * @return the value present in {@code array} that is less than or equal to
111       *     every other value in the array
112       * @throws IllegalArgumentException if {@code array} is empty
113       */
114      public static byte min(byte... array) {
115        checkArgument(array.length > 0);
116        int min = toInt(array[0]);
117        for (int i = 1; i < array.length; i++) {
118          int next = toInt(array[i]);
119          if (next < min) {
120            min = next;
121          }
122        }
123        return (byte) min;
124      }
125    
126      /**
127       * Returns the greatest 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 greater than or equal
131       *     to every other value in the array
132       * @throws IllegalArgumentException if {@code array} is empty
133       */
134      public static byte max(byte... array) {
135        checkArgument(array.length > 0);
136        int max = toInt(array[0]);
137        for (int i = 1; i < array.length; i++) {
138          int next = toInt(array[i]);
139          if (next > max) {
140            max = next;
141          }
142        }
143        return (byte) max;
144      }
145    
146      /**
147       * Returns a string containing the supplied {@code byte} values separated by
148       * {@code separator}. For example, {@code join(":", (byte) 1, (byte) 2,
149       * (byte) 255)} returns the string {@code "1:2:255"}.
150       *
151       * @param separator the text that should appear between consecutive values in
152       *     the resulting string (but not at the start or end)
153       * @param array an array of {@code byte} values, possibly empty
154       */
155      public static String join(String separator, byte... array) {
156        checkNotNull(separator);
157        if (array.length == 0) {
158          return "";
159        }
160    
161        // For pre-sizing a builder, just get the right order of magnitude
162        StringBuilder builder = new StringBuilder(array.length * 5);
163        builder.append(toInt(array[0]));
164        for (int i = 1; i < array.length; i++) {
165          builder.append(separator).append(toInt(array[i]));
166        }
167        return builder.toString();
168      }
169    
170      /**
171       * Returns a comparator that compares two {@code byte} arrays
172       * lexicographically. That is, it compares, using {@link
173       * #compare(byte, byte)}), the first pair of values that follow any common
174       * prefix, or when one array is a prefix of the other, treats the shorter
175       * array as the lesser. For example, {@code [] < [0x01] < [0x01, 0x7F] <
176       * [0x01, 0x80] < [0x02]}. Values are treated as unsigned.
177       *
178       * <p>The returned comparator is inconsistent with {@link
179       * Object#equals(Object)} (since arrays support only identity equality), but
180       * it is consistent with {@link java.util.Arrays#equals(byte[], byte[])}.
181       *
182       * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
183       *     Lexicographical order article at Wikipedia</a>
184       * @since 2
185       */
186      public static Comparator<byte[]> lexicographicalComparator() {
187        return LexicographicalComparatorHolder.BEST_COMPARATOR;
188      }
189    
190      @VisibleForTesting
191      static Comparator<byte[]> lexicographicalComparatorJavaImpl() {
192        return LexicographicalComparatorHolder.PureJavaComparator.INSTANCE;
193      }
194    
195      /**
196       * Provides a lexicographical comparator implementation; either a Java
197       * implementation or a faster implementation based on {@link Unsafe}.
198       *
199       * <p>Uses reflection to gracefully fall back to the Java implementation if
200       * {@code Unsafe} isn't available.
201       */
202      @VisibleForTesting
203      static class LexicographicalComparatorHolder {
204        static final String UNSAFE_COMPARATOR_NAME =
205            LexicographicalComparatorHolder.class.getName() + "$UnsafeComparator";
206    
207        static final Comparator<byte[]> BEST_COMPARATOR = getBestComparator();
208    
209        @SuppressWarnings("unused") // only access this class via reflection!
210        enum UnsafeComparator implements Comparator<byte[]> {
211          INSTANCE;
212    
213          static final boolean littleEndian =
214              ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN);
215    
216          /*
217           * The following static final fields exist for performance reasons.
218           *
219           * In UnsignedBytesBenchmark, accessing the following objects via static
220           * final fields is the fastest (more than twice as fast as the Java
221           * implementation, vs ~1.5x with non-final static fields, on x86_32)
222           * under the Hotspot server compiler. The reason is obviously that the
223           * non-final fields need to be reloaded inside the loop.
224           *
225           * And, no, defining (final or not) local variables out of the loop still
226           * isn't as good because the null check on the theUnsafe object remains
227           * inside the loop and BYTE_ARRAY_BASE_OFFSET doesn't get
228           * constant-folded.
229           *
230           * The compiler can treat static final fields as compile-time constants
231           * and can constant-fold them while (final or not) local variables are
232           * run time values.
233           */
234    
235          static final Unsafe theUnsafe;
236    
237          /** The offset to the first element in a byte array. */
238          static final int BYTE_ARRAY_BASE_OFFSET;
239    
240          static {
241            theUnsafe = (Unsafe) AccessController.doPrivileged(
242                new PrivilegedAction<Object>() {
243                  @Override
244                  public Object run() {
245                    try {
246                      Field f = Unsafe.class.getDeclaredField("theUnsafe");
247                      f.setAccessible(true);
248                      return f.get(null);
249                    } catch (NoSuchFieldException e) {
250                      // It doesn't matter what we throw;
251                      // it's swallowed in getBestComparator().
252                      throw new Error();
253                    } catch (IllegalAccessException e) {
254                      throw new Error();
255                    }
256                  }
257                });
258    
259            BYTE_ARRAY_BASE_OFFSET = theUnsafe.arrayBaseOffset(byte[].class);
260    
261            // sanity check - this should never fail
262            if (theUnsafe.arrayIndexScale(byte[].class) != 1) {
263              throw new AssertionError();
264            }
265          }
266    
267          /**
268           * Returns true if x1 is less than x2, when both values are treated as
269           * unsigned.
270           */
271          // TODO(kevinb): Should be a common method in primitives.UnsignedLongs.
272          static boolean lessThanUnsigned(long x1, long x2) {
273            return (x1 + Long.MIN_VALUE) < (x2 + Long.MIN_VALUE);
274          }
275    
276          @Override public int compare(byte[] left, byte[] right) {
277            int minLength = Math.min(left.length, right.length);
278            int minWords = minLength / Longs.BYTES;
279    
280            /*
281             * Compare 8 bytes at a time. Benchmarking shows comparing 8 bytes at a
282             * time is no slower than comparing 4 bytes at a time even on 32-bit.
283             * On the other hand, it is substantially faster on 64-bit.
284             */
285            for (int i = 0; i < minWords * Longs.BYTES; i += Longs.BYTES) {
286              long lw = theUnsafe.getLong(left, BYTE_ARRAY_BASE_OFFSET + (long) i);
287              long rw = theUnsafe.getLong(right, BYTE_ARRAY_BASE_OFFSET + (long) i);
288              long diff = lw ^ rw;
289    
290              if (diff != 0) {
291                if (!littleEndian) {
292                  return lessThanUnsigned(lw, rw) ? -1 : 1;
293                }
294    
295                // Use binary search
296                int n = 0;
297                int y;
298                int x = (int) diff;
299                if (x == 0) {
300                  x = (int) (diff >>> 32);
301                  n = 32;
302                }
303    
304                y = x << 16;
305                if (y == 0) {
306                  n += 16;
307                } else {
308                  x = y;
309                }
310    
311                y = x << 8;
312                if (y == 0) {
313                  n +=  8;
314                }
315                return (int) (((lw >>> n) & 0xFFL) - ((rw >>> n) & 0xFFL));
316              }
317            }
318    
319            // The epilogue to cover the last (minLength % 8) elements.
320            for (int i = minWords * Longs.BYTES; i < minLength; i++) {
321              int result = UnsignedBytes.compare(left[i], right[i]);
322              if (result != 0) {
323                return result;
324              }
325            }
326            return left.length - right.length;
327          }
328        }
329    
330        enum PureJavaComparator implements Comparator<byte[]> {
331          INSTANCE;
332    
333          @Override public int compare(byte[] left, byte[] right) {
334            int minLength = Math.min(left.length, right.length);
335            for (int i = 0; i < minLength; i++) {
336              int result = UnsignedBytes.compare(left[i], right[i]);
337              if (result != 0) {
338                return result;
339              }
340            }
341            return left.length - right.length;
342          }
343        }
344    
345        /**
346         * Returns the Unsafe-using Comparator, or falls back to the pure-Java
347         * implementation if unable to do so.
348         */
349        static Comparator<byte[]> getBestComparator() {
350          try {
351            Class<?> theClass = Class.forName(UNSAFE_COMPARATOR_NAME);
352    
353            // yes, UnsafeComparator does implement Comparator<byte[]>
354            @SuppressWarnings("unchecked")
355            Comparator<byte[]> comparator =
356                (Comparator<byte[]>) theClass.getEnumConstants()[0];
357            return comparator;
358          } catch (Throwable t) { // ensure we really catch *everything*
359            return lexicographicalComparatorJavaImpl();
360          }
361        }
362      }
363    }