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 com.google.common.annotations.GwtCompatible;
     20 
     21 import java.util.Comparator;
     22 
     23 import static com.google.common.base.Preconditions.checkArgument;
     24 import static com.google.common.base.Preconditions.checkNotNull;
     25 
     26 /**
     27  * Static utility methods pertaining to {@code byte} primitives that
     28  * interpret values as signed. The corresponding methods that treat the values
     29  * as unsigned are found in {@link UnsignedBytes}, and the methods for which
     30  * signedness is not an issue are in {@link Bytes}.
     31  *
     32  * @author Kevin Bourrillion
     33  * @since 2009.09.15 <b>tentative</b>
     34  */
     35 @GwtCompatible
     36 public final class SignedBytes {
     37   private SignedBytes() {}
     38 
     39   /**
     40    * Returns the {@code byte} value that is equal to {@code value}, if possible.
     41    *
     42    * @param value any value in the range of the {@code byte} type
     43    * @return the {@code byte} value that equals {@code value}
     44    * @throws IllegalArgumentException if {@code value} is greater than {@link
     45    *     Byte#MAX_VALUE} or less than {@link Byte#MIN_VALUE}
     46    */
     47   public static byte checkedCast(long value) {
     48     byte result = (byte) value;
     49     checkArgument(result == value, "Out of range: %s", value);
     50     return result;
     51   }
     52 
     53   /**
     54    * Returns the {@code byte} nearest in value to {@code value}.
     55    *
     56    * @param value any {@code long} value
     57    * @return the same value cast to {@code byte} if it is in the range of the
     58    *     {@code byte} type, {@link Byte#MAX_VALUE} if it is too large,
     59    *     or {@link Byte#MIN_VALUE} if it is too small
     60    */
     61   public static byte saturatedCast(long value) {
     62     if (value > Byte.MAX_VALUE) {
     63       return Byte.MAX_VALUE;
     64     }
     65     if (value < Byte.MIN_VALUE) {
     66       return Byte.MIN_VALUE;
     67     }
     68     return (byte) value;
     69   }
     70 
     71   /**
     72    * Compares the two specified {@code byte} values. The sign of the value
     73    * returned is the same as that of {@code ((Byte) a).compareTo(b)}.
     74    *
     75    * @param a the first {@code byte} to compare
     76    * @param b the second {@code byte} to compare
     77    * @return a negative value if {@code a} is less than {@code b}; a positive
     78    *     value if {@code a} is greater than {@code b}; or zero if they are equal
     79    */
     80   public static int compare(byte a, byte b) {
     81     return a - b; // safe due to restricted range
     82   }
     83 
     84   /**
     85    * Returns the least value present in {@code array}.
     86    *
     87    * @param array a <i>nonempty</i> array of {@code byte} values
     88    * @return the value present in {@code array} that is less than or equal to
     89    *     every other value in the array
     90    * @throws IllegalArgumentException if {@code array} is empty
     91    */
     92   public static byte min(byte... array) {
     93     checkArgument(array.length > 0);
     94     byte min = array[0];
     95     for (int i = 1; i < array.length; i++) {
     96       if (array[i] < min) {
     97         min = array[i];
     98       }
     99     }
    100     return min;
    101   }
    102 
    103   /**
    104    * Returns the greatest value present in {@code array}.
    105    *
    106    * @param array a <i>nonempty</i> array of {@code byte} values
    107    * @return the value present in {@code array} that is greater than or equal to
    108    *     every other value in the array
    109    * @throws IllegalArgumentException if {@code array} is empty
    110    */
    111   public static byte max(byte... array) {
    112     checkArgument(array.length > 0);
    113     byte max = array[0];
    114     for (int i = 1; i < array.length; i++) {
    115       if (array[i] > max) {
    116         max = array[i];
    117       }
    118     }
    119     return max;
    120   }
    121 
    122   /**
    123    * Returns a string containing the supplied {@code byte} values separated
    124    * by {@code separator}. For example, {@code join(":", 0x01, 0x02, -0x01)}
    125    * returns the string {@code "1:2:-1"}.
    126    *
    127    * @param separator the text that should appear between consecutive values in
    128    *     the resulting string (but not at the start or end)
    129    * @param array an array of {@code byte} values, possibly empty
    130    */
    131   public static String join(String separator, byte... array) {
    132     checkNotNull(separator);
    133     if (array.length == 0) {
    134       return "";
    135     }
    136 
    137     // For pre-sizing a builder, just get the right order of magnitude
    138     StringBuilder builder = new StringBuilder(array.length * 5);
    139     builder.append(array[0]);
    140     for (int i = 1; i < array.length; i++) {
    141       builder.append(separator).append(array[i]);
    142     }
    143     return builder.toString();
    144   }
    145 
    146   /**
    147    * Returns a comparator that compares two {@code byte} arrays
    148    * lexicographically. That is, it compares, using {@link
    149    * #compare(byte, byte)}), the first pair of values that follow any common
    150    * prefix, or when one array is a prefix of the other, treats the shorter
    151    * array as the lesser. For example, {@code [] < [0x01] < [0x01, 0x80] <
    152    * [0x01, 0x7F] < [0x02]}. Values are treated as signed.
    153    *
    154    * <p>The returned comparator is inconsistent with {@link
    155    * Object#equals(Object)} (since arrays support only identity equality), but
    156    * it is consistent with {@link java.util.Arrays#equals(byte[], byte[])}.
    157    *
    158    * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
    159    *     Lexicographical order</a> article at Wikipedia
    160    * @since 2010.01.04 <b>tentative</b>
    161    */
    162   public static Comparator<byte[]> lexicographicalComparator() {
    163     return LexicographicalComparator.INSTANCE;
    164   }
    165 
    166   private enum LexicographicalComparator implements Comparator<byte[]> {
    167     INSTANCE;
    168 
    169     public int compare(byte[] left, byte[] right) {
    170       int minLength = Math.min(left.length, right.length);
    171       for (int i = 0; i < minLength; i++) {
    172         int result = SignedBytes.compare(left[i], right[i]);
    173         if (result != 0) {
    174           return result;
    175         }
    176       }
    177       return left.length - right.length;
    178     }
    179   }
    180 }
    181