Home | History | Annotate | Download | only in primitives
      1 /*
      2  * Copyright (C) 2009 Google Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.google.common.primitives;
     18 
     19 import java.util.Comparator;
     20 
     21 import static com.google.common.base.Preconditions.checkArgument;
     22 import static com.google.common.base.Preconditions.checkNotNull;
     23 
     24 /**
     25  * Static utility methods pertaining to {@code byte} primitives that interpret
     26  * values as <i>unsigned</i> (that is, any negative value {@code b} is treated
     27  * as the positive value {@code 256 + b}). The corresponding methods that treat
     28  * the values as signed are found in {@link SignedBytes}, and the methods for
     29  * which signedness is not an issue are in {@link Bytes}.
     30  *
     31  * @author Kevin Bourrillion
     32  * @since 2009.09.15 <b>tentative</b>
     33  */
     34 public final class UnsignedBytes {
     35   private UnsignedBytes() {}
     36 
     37   /**
     38    * Returns the {@code byte} value that, when treated as unsigned, is equal to
     39    * {@code value}, if possible.
     40    *
     41    * @param value a value between 0 and 255 inclusive
     42    * @return the {@code byte} value that, when treated as unsigned, equals
     43    *     {@code value}
     44    * @throws IllegalArgumentException if {@code value} is negative or greater
     45    *     than 255
     46    */
     47   public static byte checkedCast(long value) {
     48     checkArgument(value >> 8 == 0, "out of range: %s", value);
     49     return (byte) value;
     50   }
     51 
     52   /**
     53    * Returns the {@code byte} value that, when treated as unsigned, is nearest
     54    * in value to {@code value}.
     55    *
     56    * @param value any {@code long} value
     57    * @return {@code (byte) 255} if {@code value >= 255}, {@code (byte) 0} if
     58    *     {@code value <= 0}, and {@code value} cast to {@code byte} otherwise
     59    */
     60   public static byte saturatedCast(long value) {
     61     if (value > 255) {
     62       return (byte) 255; // -1
     63     }
     64     if (value < 0) {
     65       return (byte) 0;
     66     }
     67     return (byte) value;
     68   }
     69 
     70   /**
     71    * Compares the two specified {@code byte} values, treating them as unsigned
     72    * values between 0 and 255 inclusive. For example, {@code (byte) -127} is
     73    * considered greater than {@code (byte) 127} because it is seen as having
     74    * the value of positive {@code 129}.
     75    *
     76    * @param a the first {@code byte} to compare
     77    * @param b the second {@code byte} to compare
     78    * @return a negative value if {@code a} is less than {@code b}; a positive
     79    *     value if {@code a} is greater than {@code b}; or zero if they are equal
     80    */
     81   public static int compare(byte a, byte b) {
     82     return (a & 0xFF) - (b & 0xFF);
     83   }
     84 
     85   /**
     86    * Returns the least value present in {@code array}.
     87    *
     88    * @param array a <i>nonempty</i> array of {@code byte} values
     89    * @return the value present in {@code array} that is less than or equal to
     90    *     every other value in the array
     91    * @throws IllegalArgumentException if {@code array} is empty
     92    */
     93   public static byte min(byte... array) {
     94     checkArgument(array.length > 0);
     95     int min = array[0] & 0xFF;
     96     for (int i = 1; i < array.length; i++) {
     97       int next = array[i] & 0xFF;
     98       if (next < min) {
     99         min = next;
    100       }
    101     }
    102     return (byte) min;
    103   }
    104 
    105   /**
    106    * Returns the greatest value present in {@code array}.
    107    *
    108    * @param array a <i>nonempty</i> array of {@code byte} values
    109    * @return the value present in {@code array} that is greater than or equal
    110    *     to every other value in the array
    111    * @throws IllegalArgumentException if {@code array} is empty
    112    */
    113   public static byte max(byte... array) {
    114     checkArgument(array.length > 0);
    115     int max = array[0] & 0xFF;
    116     for (int i = 1; i < array.length; i++) {
    117       int next = array[i] & 0xFF;
    118       if (next > max) {
    119         max = next;
    120       }
    121     }
    122     return (byte) max;
    123   }
    124 
    125   /**
    126    * Returns a string containing the supplied {@code byte} values separated by
    127    * {@code separator}. For example, {@code join(":", (byte) 1, (byte) 2,
    128    * (byte) 255)} returns the string {@code "1:2:255"}.
    129    *
    130    * @param separator the text that should appear between consecutive values in
    131    *     the resulting string (but not at the start or end)
    132    * @param array an array of {@code byte} values, possibly empty
    133    */
    134   public static String join(String separator, byte... array) {
    135     checkNotNull(separator);
    136     if (array.length == 0) {
    137       return "";
    138     }
    139 
    140     // For pre-sizing a builder, just get the right order of magnitude
    141     StringBuilder builder = new StringBuilder(array.length * 5);
    142     builder.append(array[0] & 0xFF);
    143     for (int i = 1; i < array.length; i++) {
    144       builder.append(separator).append(array[i] & 0xFF);
    145     }
    146     return builder.toString();
    147   }
    148 
    149   /**
    150    * Returns a comparator that compares two {@code byte} arrays
    151    * lexicographically. That is, it compares, using {@link
    152    * #compare(byte, byte)}), the first pair of values that follow any common
    153    * prefix, or when one array is a prefix of the other, treats the shorter
    154    * array as the lesser. For example, {@code [] < [0x01] < [0x01, 0x7F] <
    155    * [0x01, 0x80] < [0x02]}. Values are treated as unsigned.
    156    *
    157    * <p>The returned comparator is inconsistent with {@link
    158    * Object#equals(Object)} (since arrays support only identity equality), but
    159    * it is consistent with {@link java.util.Arrays#equals(byte[], byte[])}.
    160    *
    161    * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
    162    *     Lexicographical order</a> article at Wikipedia
    163    * @since 2010.01.04 <b>tentative</b>
    164    */
    165   public static Comparator<byte[]> lexicographicalComparator() {
    166     return LexicographicalComparator.INSTANCE;
    167   }
    168 
    169   private enum LexicographicalComparator implements Comparator<byte[]> {
    170     INSTANCE;
    171 
    172     public int compare(byte[] left, byte[] right) {
    173       int minLength = Math.min(left.length, right.length);
    174       for (int i = 0; i < minLength; i++) {
    175         int result = UnsignedBytes.compare(left[i], right[i]);
    176         if (result != 0) {
    177           return result;
    178         }
    179       }
    180       return left.length - right.length;
    181     }
    182   }
    183 }
    184