001/*
002 * Copyright (C) 2011 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.Beta;
021import com.google.common.annotations.GwtCompatible;
022import com.google.errorprone.annotations.CanIgnoreReturnValue;
023import java.util.Arrays;
024import java.util.Comparator;
025
026/**
027 * Static utility methods pertaining to {@code int} primitives that interpret values as
028 * <i>unsigned</i> (that is, any negative value {@code x} is treated as the positive value
029 * {@code 2^32 + x}). The methods for which signedness is not an issue are in {@link Ints}, as well
030 * as signed versions of methods for which signedness is an issue.
031 *
032 * <p>In addition, this class provides several static methods for converting an {@code int} to a
033 * {@code String} and a {@code String} to an {@code int} that treat the {@code int} as an unsigned
034 * number.
035 *
036 * <p>Users of these utilities must be <i>extremely careful</i> not to mix up signed and unsigned
037 * {@code int} values. When possible, it is recommended that the {@link UnsignedInteger} wrapper
038 * class be used, at a small efficiency penalty, to enforce the distinction in the type system.
039 *
040 * <p>See the Guava User Guide article on
041 * <a href="https://github.com/google/guava/wiki/PrimitivesExplained#unsigned-support">unsigned
042 * primitive utilities</a>.
043 *
044 * @author Louis Wasserman
045 * @since 11.0
046 */
047@Beta
048@GwtCompatible
049public final class UnsignedInts {
050  static final long INT_MASK = 0xffffffffL;
051
052  private UnsignedInts() {}
053
054  static int flip(int value) {
055    return value ^ Integer.MIN_VALUE;
056  }
057
058  /**
059   * Compares the two specified {@code int} values, treating them as unsigned values between
060   * {@code 0} and {@code 2^32 - 1} inclusive.
061   *
062   * @param a the first unsigned {@code int} to compare
063   * @param b the second unsigned {@code int} to compare
064   * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is
065   *     greater than {@code b}; or zero if they are equal
066   */
067  public static int compare(int a, int b) {
068    return Ints.compare(flip(a), flip(b));
069  }
070
071  /**
072   * Returns the value of the given {@code int} as a {@code long}, when treated as unsigned.
073   */
074  public static long toLong(int value) {
075    return value & INT_MASK;
076  }
077
078  /**
079   * Returns the {@code int} value that, when treated as unsigned, is equal to {@code value}, if
080   * possible.
081   *
082   * @param value a value between 0 and 2<sup>32</sup>-1 inclusive
083   * @return the {@code int} value that, when treated as unsigned, equals {@code value}
084   * @throws IllegalArgumentException if {@code value} is negative or greater than or equal to
085   *     2<sup>32</sup>
086   * @since 21.0
087   */
088  public static int checkedCast(long value) {
089    checkArgument((value >> Integer.SIZE) == 0, "out of range: %s", value);
090    return (int) value;
091  }
092
093  /**
094   * Returns the {@code int} value that, when treated as unsigned, is nearest in value to
095   * {@code value}.
096   *
097   * @param value any {@code long} value
098   * @return {@code 2^32 - 1} if {@code value >= 2^32}, {@code 0} if {@code value <= 0}, and
099   *     {@code value} cast to {@code int} otherwise
100   * @since 21.0
101   */
102  public static int saturatedCast(long value) {
103    if (value <= 0) {
104      return 0;
105    } else if (value >= (1L << 32)) {
106      return -1;
107    } else {
108      return (int) value;
109    }
110  }
111
112  /**
113   * Returns the least value present in {@code array}, treating values as unsigned.
114   *
115   * @param array a <i>nonempty</i> array of unsigned {@code int} values
116   * @return the value present in {@code array} that is less than or equal to every other value in
117   *     the array according to {@link #compare}
118   * @throws IllegalArgumentException if {@code array} is empty
119   */
120  public static int min(int... array) {
121    checkArgument(array.length > 0);
122    int min = flip(array[0]);
123    for (int i = 1; i < array.length; i++) {
124      int next = flip(array[i]);
125      if (next < min) {
126        min = next;
127      }
128    }
129    return flip(min);
130  }
131
132  /**
133   * Returns the greatest value present in {@code array}, treating values as unsigned.
134   *
135   * @param array a <i>nonempty</i> array of unsigned {@code int} values
136   * @return the value present in {@code array} that is greater than or equal to every other value
137   *     in the array according to {@link #compare}
138   * @throws IllegalArgumentException if {@code array} is empty
139   */
140  public static int max(int... array) {
141    checkArgument(array.length > 0);
142    int max = flip(array[0]);
143    for (int i = 1; i < array.length; i++) {
144      int next = flip(array[i]);
145      if (next > max) {
146        max = next;
147      }
148    }
149    return flip(max);
150  }
151
152  /**
153   * Returns a string containing the supplied unsigned {@code int} values separated by
154   * {@code separator}. For example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}.
155   *
156   * @param separator the text that should appear between consecutive values in the resulting string
157   *     (but not at the start or end)
158   * @param array an array of unsigned {@code int} values, possibly empty
159   */
160  public static String join(String separator, int... array) {
161    checkNotNull(separator);
162    if (array.length == 0) {
163      return "";
164    }
165
166    // For pre-sizing a builder, just get the right order of magnitude
167    StringBuilder builder = new StringBuilder(array.length * 5);
168    builder.append(toString(array[0]));
169    for (int i = 1; i < array.length; i++) {
170      builder.append(separator).append(toString(array[i]));
171    }
172    return builder.toString();
173  }
174
175  /**
176   * Returns a comparator that compares two arrays of unsigned {@code int} values <a
177   * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it
178   * compares, using {@link #compare(int, int)}), the first pair of values that follow any common
179   * prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For
180   * example, {@code [] < [1] < [1, 2] < [2] < [1 << 31]}.
181   *
182   * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
183   * support only identity equality), but it is consistent with {@link Arrays#equals(int[], int[])}.
184   */
185  public static Comparator<int[]> lexicographicalComparator() {
186    return LexicographicalComparator.INSTANCE;
187  }
188
189  enum LexicographicalComparator implements Comparator<int[]> {
190    INSTANCE;
191
192    @Override
193    public int compare(int[] left, int[] right) {
194      int minLength = Math.min(left.length, right.length);
195      for (int i = 0; i < minLength; i++) {
196        if (left[i] != right[i]) {
197          return UnsignedInts.compare(left[i], right[i]);
198        }
199      }
200      return left.length - right.length;
201    }
202
203    @Override
204    public String toString() {
205      return "UnsignedInts.lexicographicalComparator()";
206    }
207  }
208
209  /**
210   * Returns dividend / divisor, where the dividend and divisor are treated as unsigned 32-bit
211   * quantities.
212   *
213   * @param dividend the dividend (numerator)
214   * @param divisor the divisor (denominator)
215   * @throws ArithmeticException if divisor is 0
216   */
217  public static int divide(int dividend, int divisor) {
218    return (int) (toLong(dividend) / toLong(divisor));
219  }
220
221  /**
222   * Returns dividend % divisor, where the dividend and divisor are treated as unsigned 32-bit
223   * quantities.
224   *
225   * @param dividend the dividend (numerator)
226   * @param divisor the divisor (denominator)
227   * @throws ArithmeticException if divisor is 0
228   */
229  public static int remainder(int dividend, int divisor) {
230    return (int) (toLong(dividend) % toLong(divisor));
231  }
232
233  /**
234   * Returns the unsigned {@code int} value represented by the given string.
235   *
236   * Accepts a decimal, hexadecimal, or octal number given by specifying the following prefix:
237   *
238   * <ul>
239   * <li>{@code 0x}<i>HexDigits</i>
240   * <li>{@code 0X}<i>HexDigits</i>
241   * <li>{@code #}<i>HexDigits</i>
242   * <li>{@code 0}<i>OctalDigits</i>
243   * </ul>
244   *
245   * @throws NumberFormatException if the string does not contain a valid unsigned {@code int} value
246   * @since 13.0
247   */
248  @CanIgnoreReturnValue
249  public static int decode(String stringValue) {
250    ParseRequest request = ParseRequest.fromString(stringValue);
251
252    try {
253      return parseUnsignedInt(request.rawValue, request.radix);
254    } catch (NumberFormatException e) {
255      NumberFormatException decodeException =
256          new NumberFormatException("Error parsing value: " + stringValue);
257      decodeException.initCause(e);
258      throw decodeException;
259    }
260  }
261
262  /**
263   * Returns the unsigned {@code int} value represented by the given decimal string.
264   *
265   * @throws NumberFormatException if the string does not contain a valid unsigned {@code int} value
266   * @throws NullPointerException if {@code s} is null (in contrast to
267   *     {@link Integer#parseInt(String)})
268   */
269  @CanIgnoreReturnValue
270  public static int parseUnsignedInt(String s) {
271    return parseUnsignedInt(s, 10);
272  }
273
274  /**
275   * Returns the unsigned {@code int} value represented by a string with the given radix.
276   *
277   * @param string the string containing the unsigned integer representation to be parsed.
278   * @param radix the radix to use while parsing {@code s}; must be between
279   *     {@link Character#MIN_RADIX} and {@link Character#MAX_RADIX}.
280   * @throws NumberFormatException if the string does not contain a valid unsigned {@code int}, or
281   *     if supplied radix is invalid.
282   * @throws NullPointerException if {@code s} is null (in contrast to
283   *     {@link Integer#parseInt(String)})
284   */
285  @CanIgnoreReturnValue
286  public static int parseUnsignedInt(String string, int radix) {
287    checkNotNull(string);
288    long result = Long.parseLong(string, radix);
289    if ((result & INT_MASK) != result) {
290      throw new NumberFormatException(
291          "Input " + string + " in base " + radix + " is not in the range of an unsigned integer");
292    }
293    return (int) result;
294  }
295
296  /**
297   * Returns a string representation of x, where x is treated as unsigned.
298   */
299  public static String toString(int x) {
300    return toString(x, 10);
301  }
302
303  /**
304   * Returns a string representation of {@code x} for the given radix, where {@code x} is treated as
305   * unsigned.
306   *
307   * @param x the value to convert to a string.
308   * @param radix the radix to use while working with {@code x}
309   * @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX}
310   *     and {@link Character#MAX_RADIX}.
311   */
312  public static String toString(int x, int radix) {
313    long asLong = x & INT_MASK;
314    return Long.toString(asLong, radix);
315  }
316}