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.GwtCompatible;
023
024import java.util.Comparator;
025
026/**
027 * Static utility methods pertaining to {@code byte} primitives that
028 * interpret values as signed. The corresponding methods that treat the values
029 * as unsigned are found in {@link UnsignedBytes}, and the methods for which
030 * signedness is not an issue are in {@link Bytes}.
031 * 
032 * <p>See the Guava User Guide article on <a href=
033 * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
034 * primitive utilities</a>.
035 *
036 * @author Kevin Bourrillion
037 * @since 1.0
038 */
039// TODO(kevinb): how to prevent warning on UnsignedBytes when building GWT
040// javadoc?
041@GwtCompatible
042public final class SignedBytes {
043  private SignedBytes() {}
044
045  /**
046   * The largest power of two that can be represented as a signed {@code byte}. 
047   *
048   * @since 10.0
049   */
050  public static final byte MAX_POWER_OF_TWO = 1 << 6;
051  
052  /**
053   * Returns the {@code byte} value that is equal to {@code value}, if possible.
054   *
055   * @param value any value in the range of the {@code byte} type
056   * @return the {@code byte} value that equals {@code value}
057   * @throws IllegalArgumentException if {@code value} is greater than {@link
058   *     Byte#MAX_VALUE} or less than {@link Byte#MIN_VALUE}
059   */
060  public static byte checkedCast(long value) {
061    byte result = (byte) value;
062    checkArgument(result == value, "Out of range: %s", value);
063    return result;
064  }
065
066  /**
067   * Returns the {@code byte} nearest in value to {@code value}.
068   *
069   * @param value any {@code long} value
070   * @return the same value cast to {@code byte} if it is in the range of the
071   *     {@code byte} type, {@link Byte#MAX_VALUE} if it is too large,
072   *     or {@link Byte#MIN_VALUE} if it is too small
073   */
074  public static byte saturatedCast(long value) {
075    if (value > Byte.MAX_VALUE) {
076      return Byte.MAX_VALUE;
077    }
078    if (value < Byte.MIN_VALUE) {
079      return Byte.MIN_VALUE;
080    }
081    return (byte) value;
082  }
083
084  /**
085   * Compares the two specified {@code byte} values. The sign of the value
086   * returned is the same as that of {@code ((Byte) a).compareTo(b)}.
087   *
088   * @param a the first {@code byte} to compare
089   * @param b the second {@code byte} to compare
090   * @return a negative value if {@code a} is less than {@code b}; a positive
091   *     value if {@code a} is greater than {@code b}; or zero if they are equal
092   */
093  public static int compare(byte a, byte b) {
094    return a - b; // safe due to restricted range
095  }
096
097  /**
098   * Returns the least value present in {@code array}.
099   *
100   * @param array a <i>nonempty</i> array of {@code byte} values
101   * @return the value present in {@code array} that is less than or equal to
102   *     every other value in the array
103   * @throws IllegalArgumentException if {@code array} is empty
104   */
105  public static byte min(byte... array) {
106    checkArgument(array.length > 0);
107    byte min = array[0];
108    for (int i = 1; i < array.length; i++) {
109      if (array[i] < min) {
110        min = array[i];
111      }
112    }
113    return min;
114  }
115
116  /**
117   * Returns the greatest value present in {@code array}.
118   *
119   * @param array a <i>nonempty</i> array of {@code byte} values
120   * @return the value present in {@code array} that is greater than or equal to
121   *     every other value in the array
122   * @throws IllegalArgumentException if {@code array} is empty
123   */
124  public static byte max(byte... array) {
125    checkArgument(array.length > 0);
126    byte max = array[0];
127    for (int i = 1; i < array.length; i++) {
128      if (array[i] > max) {
129        max = array[i];
130      }
131    }
132    return max;
133  }
134
135  /**
136   * Returns a string containing the supplied {@code byte} values separated
137   * by {@code separator}. For example, {@code join(":", 0x01, 0x02, -0x01)}
138   * returns the string {@code "1:2:-1"}.
139   *
140   * @param separator the text that should appear between consecutive values in
141   *     the resulting string (but not at the start or end)
142   * @param array an array of {@code byte} values, possibly empty
143   */
144  public static String join(String separator, byte... array) {
145    checkNotNull(separator);
146    if (array.length == 0) {
147      return "";
148    }
149
150    // For pre-sizing a builder, just get the right order of magnitude
151    StringBuilder builder = new StringBuilder(array.length * 5);
152    builder.append(array[0]);
153    for (int i = 1; i < array.length; i++) {
154      builder.append(separator).append(array[i]);
155    }
156    return builder.toString();
157  }
158
159  /**
160   * Returns a comparator that compares two {@code byte} arrays
161   * lexicographically. That is, it compares, using {@link
162   * #compare(byte, byte)}), the first pair of values that follow any common
163   * prefix, or when one array is a prefix of the other, treats the shorter
164   * array as the lesser. For example, {@code [] < [0x01] < [0x01, 0x80] <
165   * [0x01, 0x7F] < [0x02]}. Values are treated as signed.
166   *
167   * <p>The returned comparator is inconsistent with {@link
168   * Object#equals(Object)} (since arrays support only identity equality), but
169   * it is consistent with {@link java.util.Arrays#equals(byte[], byte[])}.
170   *
171   * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
172   *     Lexicographical order article at Wikipedia</a>
173   * @since 2.0
174   */
175  public static Comparator<byte[]> lexicographicalComparator() {
176    return LexicographicalComparator.INSTANCE;
177  }
178
179  private enum LexicographicalComparator implements Comparator<byte[]> {
180    INSTANCE;
181
182    @Override
183    public int compare(byte[] left, byte[] right) {
184      int minLength = Math.min(left.length, right.length);
185      for (int i = 0; i < minLength; i++) {
186        int result = SignedBytes.compare(left[i], right[i]);
187        if (result != 0) {
188          return result;
189        }
190      }
191      return left.length - right.length;
192    }
193  }
194}