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