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