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