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
026import javax.annotation.CheckReturnValue;
027
028/**
029 * Static utility methods pertaining to {@code byte} primitives that
030 * interpret values as signed. The corresponding methods that treat the values
031 * as unsigned are found in {@link UnsignedBytes}, and the methods for which
032 * signedness is not an issue are in {@link Bytes}.
033 *
034 * <p>See the Guava User Guide article on <a href=
035 * "https://github.com/google/guava/wiki/PrimitivesExplained">
036 * primitive utilities</a>.
037 *
038 * @author Kevin Bourrillion
039 * @since 1.0
040 */
041// TODO(kevinb): how to prevent warning on UnsignedBytes when building GWT
042// javadoc?
043@CheckReturnValue
044@GwtCompatible
045public final class SignedBytes {
046  private SignedBytes() {}
047
048  /**
049   * The largest power of two that can be represented as a signed {@code byte}.
050   *
051   * @since 10.0
052   */
053  public static final byte MAX_POWER_OF_TWO = 1 << 6;
054
055  /**
056   * Returns the {@code byte} value that is equal to {@code value}, if possible.
057   *
058   * @param value any value in the range of the {@code byte} type
059   * @return the {@code byte} value that equals {@code value}
060   * @throws IllegalArgumentException if {@code value} is greater than {@link
061   *     Byte#MAX_VALUE} or less than {@link Byte#MIN_VALUE}
062   */
063  public static byte checkedCast(long value) {
064    byte result = (byte) value;
065    if (result != value) {
066      // don't use checkArgument here, to avoid boxing
067      throw new IllegalArgumentException("Out of range: " + value);
068    }
069    return result;
070  }
071
072  /**
073   * Returns the {@code byte} nearest in value to {@code value}.
074   *
075   * @param value any {@code long} value
076   * @return the same value cast to {@code byte} if it is in the range of the
077   *     {@code byte} type, {@link Byte#MAX_VALUE} if it is too large,
078   *     or {@link Byte#MIN_VALUE} if it is too small
079   */
080  public static byte saturatedCast(long value) {
081    if (value > Byte.MAX_VALUE) {
082      return Byte.MAX_VALUE;
083    }
084    if (value < Byte.MIN_VALUE) {
085      return Byte.MIN_VALUE;
086    }
087    return (byte) value;
088  }
089
090  /**
091   * Compares the two specified {@code byte} values. The sign of the value
092   * returned is the same as that of {@code ((Byte) a).compareTo(b)}.
093   *
094   * <p><b>Note:</b> this method behaves identically to the JDK 7 method {@link
095   * Byte#compare}.
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  // TODO(kevinb): if Ints.compare etc. are ever removed, *maybe* remove this
103  // one too, which would leave compare methods only on the Unsigned* classes.
104  public static int compare(byte a, byte b) {
105    return a - b; // safe due to restricted range
106  }
107
108  /**
109   * Returns the least value present in {@code array}.
110   *
111   * @param array a <i>nonempty</i> array of {@code byte} values
112   * @return the value present in {@code array} that is less than or equal to
113   *     every other value in the array
114   * @throws IllegalArgumentException if {@code array} is empty
115   */
116  public static byte min(byte... array) {
117    checkArgument(array.length > 0);
118    byte min = array[0];
119    for (int i = 1; i < array.length; i++) {
120      if (array[i] < min) {
121        min = array[i];
122      }
123    }
124    return min;
125  }
126
127  /**
128   * Returns the greatest value present in {@code array}.
129   *
130   * @param array a <i>nonempty</i> array of {@code byte} values
131   * @return the value present in {@code array} that is greater than or equal to
132   *     every other value in the array
133   * @throws IllegalArgumentException if {@code array} is empty
134   */
135  public static byte max(byte... array) {
136    checkArgument(array.length > 0);
137    byte max = array[0];
138    for (int i = 1; i < array.length; i++) {
139      if (array[i] > max) {
140        max = array[i];
141      }
142    }
143    return max;
144  }
145
146  /**
147   * Returns a string containing the supplied {@code byte} values separated
148   * by {@code separator}. For example, {@code join(":", 0x01, 0x02, -0x01)}
149   * returns the string {@code "1:2:-1"}.
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(array[0]);
164    for (int i = 1; i < array.length; i++) {
165      builder.append(separator).append(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, 0x80] <
176   * [0x01, 0x7F] < [0x02]}. Values are treated as signed.
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.0
185   */
186  public static Comparator<byte[]> lexicographicalComparator() {
187    return LexicographicalComparator.INSTANCE;
188  }
189
190  private enum LexicographicalComparator implements Comparator<byte[]> {
191    INSTANCE;
192
193    @Override
194    public int compare(byte[] left, byte[] right) {
195      int minLength = Math.min(left.length, right.length);
196      for (int i = 0; i < minLength; i++) {
197        int result = SignedBytes.compare(left[i], right[i]);
198        if (result != 0) {
199          return result;
200        }
201      }
202      return left.length - right.length;
203    }
204  }
205}