001/*
002 * Copyright (C) 2009 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.primitives;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019
020import com.google.common.annotations.GwtCompatible;
021import java.util.Comparator;
022
023/**
024 * Static utility methods pertaining to {@code byte} primitives that interpret values as signed. The
025 * corresponding methods that treat the values as unsigned are found in {@link UnsignedBytes}, and
026 * the methods for which signedness is not an issue are in {@link Bytes}.
027 *
028 * <p>See the Guava User Guide article on
029 * <a href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>.
030 *
031 * @author Kevin Bourrillion
032 * @since 1.0
033 */
034// TODO(kevinb): how to prevent warning on UnsignedBytes when building GWT
035// javadoc?
036@GwtCompatible
037public final class SignedBytes {
038  private SignedBytes() {}
039
040  /**
041   * The largest power of two that can be represented as a signed {@code byte}.
042   *
043   * @since 10.0
044   */
045  public static final byte MAX_POWER_OF_TWO = 1 << 6;
046
047  /**
048   * Returns the {@code byte} value that is equal to {@code value}, if possible.
049   *
050   * @param value any value in the range of the {@code byte} type
051   * @return the {@code byte} value that equals {@code value}
052   * @throws IllegalArgumentException if {@code value} is greater than {@link Byte#MAX_VALUE} or
053   *     less than {@link Byte#MIN_VALUE}
054   */
055  public static byte checkedCast(long value) {
056    byte result = (byte) value;
057    if (result != value) {
058      // don't use checkArgument here, to avoid boxing
059      throw new IllegalArgumentException("Out of range: " + value);
060    }
061    return result;
062  }
063
064  /**
065   * Returns the {@code byte} nearest in value to {@code value}.
066   *
067   * @param value any {@code long} value
068   * @return the same value cast to {@code byte} if it is in the range of the {@code byte} type,
069   *     {@link Byte#MAX_VALUE} if it is too large, or {@link Byte#MIN_VALUE} if it is too small
070   */
071  public static byte saturatedCast(long value) {
072    if (value > Byte.MAX_VALUE) {
073      return Byte.MAX_VALUE;
074    }
075    if (value < Byte.MIN_VALUE) {
076      return Byte.MIN_VALUE;
077    }
078    return (byte) value;
079  }
080
081  /**
082   * Compares the two specified {@code byte} values. The sign of the value returned is the same as
083   * that of {@code ((Byte) a).compareTo(b)}.
084   *
085   * <p><b>Note:</b> this method behaves identically to the JDK 7 method {@link Byte#compare}.
086   *
087   * @param a the first {@code byte} to compare
088   * @param b the second {@code byte} to compare
089   * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is
090   *     greater than {@code b}; or zero if they are equal
091   */
092  // TODO(kevinb): if Ints.compare etc. are ever removed, *maybe* remove this
093  // one too, which would leave compare methods only on the Unsigned* classes.
094  public static int compare(byte a, byte b) {
095    return a - b; // safe due to restricted range
096  }
097
098  /**
099   * Returns the least value present in {@code array}.
100   *
101   * @param array a <i>nonempty</i> array of {@code byte} values
102   * @return the value present in {@code array} that is less than or equal to every other value in
103   *     the array
104   * @throws IllegalArgumentException if {@code array} is empty
105   */
106  public static byte min(byte... array) {
107    checkArgument(array.length > 0);
108    byte min = array[0];
109    for (int i = 1; i < array.length; i++) {
110      if (array[i] < min) {
111        min = array[i];
112      }
113    }
114    return min;
115  }
116
117  /**
118   * Returns the greatest 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 greater than or equal to every other value
122   *     in the array
123   * @throws IllegalArgumentException if {@code array} is empty
124   */
125  public static byte max(byte... array) {
126    checkArgument(array.length > 0);
127    byte max = array[0];
128    for (int i = 1; i < array.length; i++) {
129      if (array[i] > max) {
130        max = array[i];
131      }
132    }
133    return max;
134  }
135
136  /**
137   * Returns a string containing the supplied {@code byte} values separated by {@code separator}.
138   * For example, {@code join(":", 0x01, 0x02, -0x01)} returns the string {@code "1:2:-1"}.
139   *
140   * @param separator the text that should appear between consecutive values in the resulting string
141   *     (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 <a
161   * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it
162   * compares, using {@link #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 array as the lesser. For
164   * example, {@code [] < [0x01] < [0x01, 0x80] < [0x01, 0x7F] < [0x02]}. Values are treated as
165   * signed.
166   *
167   * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
168   * support only identity equality), but it is consistent with
169   * {@link java.util.Arrays#equals(byte[], byte[])}.
170   *
171   * @since 2.0
172   */
173  public static Comparator<byte[]> lexicographicalComparator() {
174    return LexicographicalComparator.INSTANCE;
175  }
176
177  private enum LexicographicalComparator implements Comparator<byte[]> {
178    INSTANCE;
179
180    @Override
181    public int compare(byte[] left, byte[] right) {
182      int minLength = Math.min(left.length, right.length);
183      for (int i = 0; i < minLength; i++) {
184        int result = SignedBytes.compare(left[i], right[i]);
185        if (result != 0) {
186          return result;
187        }
188      }
189      return left.length - right.length;
190    }
191
192    @Override
193    public String toString() {
194      return "SignedBytes.lexicographicalComparator()";
195    }
196  }
197}