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;
019import static com.google.common.base.Preconditions.checkPositionIndexes;
020
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 {@code
029 * 2^32 + x}). The methods for which signedness is not an issue are in {@link Ints}, as well as
030 * 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 <a
041 * 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@GwtCompatible
048public final class UnsignedInts {
049  static final long INT_MASK = 0xffffffffL;
050
051  private UnsignedInts() {}
052
053  static int flip(int value) {
054    return value ^ Integer.MIN_VALUE;
055  }
056
057  /**
058   * Compares the two specified {@code int} values, treating them as unsigned values between {@code
059   * 0} and {@code 2^32 - 1} inclusive.
060   *
061   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated; use the
062   * equivalent {@link Integer#compareUnsigned(int, int)} method instead.
063   *
064   * @param a the first unsigned {@code int} to compare
065   * @param b the second unsigned {@code int} to compare
066   * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is
067   *     greater than {@code b}; or zero if they are equal
068   */
069  @SuppressWarnings("InlineMeInliner") // Integer.compare unavailable under GWT+J2CL
070  public static int compare(int a, int b) {
071    return Ints.compare(flip(a), flip(b));
072  }
073
074  /**
075   * Returns the value of the given {@code int} as a {@code long}, when treated as unsigned.
076   *
077   * <p><b>Java 8+ users:</b> use {@link Integer#toUnsignedLong(int)} instead.
078   */
079  public static long toLong(int value) {
080    return value & INT_MASK;
081  }
082
083  /**
084   * Returns the {@code int} value that, when treated as unsigned, is equal to {@code value}, if
085   * possible.
086   *
087   * @param value a value between 0 and 2<sup>32</sup>-1 inclusive
088   * @return the {@code int} value that, when treated as unsigned, equals {@code value}
089   * @throws IllegalArgumentException if {@code value} is negative or greater than or equal to
090   *     2<sup>32</sup>
091   * @since 21.0
092   */
093  public static int checkedCast(long value) {
094    checkArgument((value >> Integer.SIZE) == 0, "out of range: %s", value);
095    return (int) value;
096  }
097
098  /**
099   * Returns the {@code int} value that, when treated as unsigned, is nearest in value to {@code
100   * value}.
101   *
102   * @param value any {@code long} value
103   * @return {@code 2^32 - 1} if {@code value >= 2^32}, {@code 0} if {@code value <= 0}, and {@code
104   *     value} cast to {@code int} otherwise
105   * @since 21.0
106   */
107  public static int saturatedCast(long value) {
108    if (value <= 0) {
109      return 0;
110    } else if (value >= (1L << 32)) {
111      return -1;
112    } else {
113      return (int) value;
114    }
115  }
116
117  /**
118   * Returns the least value present in {@code array}, treating values as unsigned.
119   *
120   * @param array a <i>nonempty</i> array of unsigned {@code int} values
121   * @return the value present in {@code array} that is less than or equal to every other value in
122   *     the array according to {@link #compare}
123   * @throws IllegalArgumentException if {@code array} is empty
124   */
125  public static int min(int... array) {
126    checkArgument(array.length > 0);
127    int min = flip(array[0]);
128    for (int i = 1; i < array.length; i++) {
129      int next = flip(array[i]);
130      if (next < min) {
131        min = next;
132      }
133    }
134    return flip(min);
135  }
136
137  /**
138   * Returns the greatest value present in {@code array}, treating values as unsigned.
139   *
140   * @param array a <i>nonempty</i> array of unsigned {@code int} values
141   * @return the value present in {@code array} that is greater than or equal to every other value
142   *     in the array according to {@link #compare}
143   * @throws IllegalArgumentException if {@code array} is empty
144   */
145  public static int max(int... array) {
146    checkArgument(array.length > 0);
147    int max = flip(array[0]);
148    for (int i = 1; i < array.length; i++) {
149      int next = flip(array[i]);
150      if (next > max) {
151        max = next;
152      }
153    }
154    return flip(max);
155  }
156
157  /**
158   * Returns a string containing the supplied unsigned {@code int} values separated by {@code
159   * separator}. For example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}.
160   *
161   * @param separator the text that should appear between consecutive values in the resulting string
162   *     (but not at the start or end)
163   * @param array an array of unsigned {@code int} values, possibly empty
164   */
165  public static String join(String separator, int... array) {
166    checkNotNull(separator);
167    if (array.length == 0) {
168      return "";
169    }
170
171    // For pre-sizing a builder, just get the right order of magnitude
172    StringBuilder builder = new StringBuilder(array.length * 5);
173    builder.append(toString(array[0]));
174    for (int i = 1; i < array.length; i++) {
175      builder.append(separator).append(toString(array[i]));
176    }
177    return builder.toString();
178  }
179
180  /**
181   * Returns a comparator that compares two arrays of unsigned {@code int} values <a
182   * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it
183   * compares, using {@link #compare(int, int)}), the first pair of values that follow any common
184   * prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For
185   * example, {@code [] < [1] < [1, 2] < [2] < [1 << 31]}.
186   *
187   * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
188   * support only identity equality), but it is consistent with {@link Arrays#equals(int[], int[])}.
189   *
190   * <p><b>Java 9+ users:</b> Use {@link Arrays#compareUnsigned(int[], int[])
191   * Arrays::compareUnsigned}.
192   */
193  public static Comparator<int[]> lexicographicalComparator() {
194    return LexicographicalComparator.INSTANCE;
195  }
196
197  enum LexicographicalComparator implements Comparator<int[]> {
198    INSTANCE;
199
200    @Override
201    // A call to bare "min" or "max" would resolve to our varargs method, not to any static import.
202    @SuppressWarnings("StaticImportPreferred")
203    public int compare(int[] left, int[] right) {
204      int minLength = Math.min(left.length, right.length);
205      for (int i = 0; i < minLength; i++) {
206        if (left[i] != right[i]) {
207          return UnsignedInts.compare(left[i], right[i]);
208        }
209      }
210      return left.length - right.length;
211    }
212
213    @Override
214    public String toString() {
215      return "UnsignedInts.lexicographicalComparator()";
216    }
217  }
218
219  /**
220   * Sorts the array, treating its elements as unsigned 32-bit integers.
221   *
222   * @since 23.1
223   */
224  public static void sort(int[] array) {
225    checkNotNull(array);
226    sort(array, 0, array.length);
227  }
228
229  /**
230   * Sorts the array between {@code fromIndex} inclusive and {@code toIndex} exclusive, treating its
231   * elements as unsigned 32-bit integers.
232   *
233   * @since 23.1
234   */
235  public static void sort(int[] array, int fromIndex, int toIndex) {
236    checkNotNull(array);
237    checkPositionIndexes(fromIndex, toIndex, array.length);
238    for (int i = fromIndex; i < toIndex; i++) {
239      array[i] = flip(array[i]);
240    }
241    Arrays.sort(array, fromIndex, toIndex);
242    for (int i = fromIndex; i < toIndex; i++) {
243      array[i] = flip(array[i]);
244    }
245  }
246
247  /**
248   * Sorts the elements of {@code array} in descending order, interpreting them as unsigned 32-bit
249   * integers.
250   *
251   * @since 23.1
252   */
253  public static void sortDescending(int[] array) {
254    checkNotNull(array);
255    sortDescending(array, 0, array.length);
256  }
257
258  /**
259   * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
260   * exclusive in descending order, interpreting them as unsigned 32-bit integers.
261   *
262   * @since 23.1
263   */
264  public static void sortDescending(int[] array, int fromIndex, int toIndex) {
265    checkNotNull(array);
266    checkPositionIndexes(fromIndex, toIndex, array.length);
267    for (int i = fromIndex; i < toIndex; i++) {
268      array[i] ^= Integer.MAX_VALUE;
269    }
270    Arrays.sort(array, fromIndex, toIndex);
271    for (int i = fromIndex; i < toIndex; i++) {
272      array[i] ^= Integer.MAX_VALUE;
273    }
274  }
275
276  /**
277   * Returns dividend / divisor, where the dividend and divisor are treated as unsigned 32-bit
278   * quantities.
279   *
280   * <p><b>Java 8+ users:</b> use {@link Integer#divideUnsigned(int, int)} instead.
281   *
282   * @param dividend the dividend (numerator)
283   * @param divisor the divisor (denominator)
284   * @throws ArithmeticException if divisor is 0
285   */
286  public static int divide(int dividend, int divisor) {
287    return (int) (toLong(dividend) / toLong(divisor));
288  }
289
290  /**
291   * Returns dividend % divisor, where the dividend and divisor are treated as unsigned 32-bit
292   * quantities.
293   *
294   * <p><b>Java 8+ users:</b> use {@link Integer#remainderUnsigned(int, int)} instead.
295   *
296   * @param dividend the dividend (numerator)
297   * @param divisor the divisor (denominator)
298   * @throws ArithmeticException if divisor is 0
299   */
300  public static int remainder(int dividend, int divisor) {
301    return (int) (toLong(dividend) % toLong(divisor));
302  }
303
304  /**
305   * Returns the unsigned {@code int} value represented by the given string.
306   *
307   * <p>Accepts a decimal, hexadecimal, or octal number given by specifying the following prefix:
308   *
309   * <ul>
310   *   <li>{@code 0x}<i>HexDigits</i>
311   *   <li>{@code 0X}<i>HexDigits</i>
312   *   <li>{@code #}<i>HexDigits</i>
313   *   <li>{@code 0}<i>OctalDigits</i>
314   * </ul>
315   *
316   * @throws NumberFormatException if the string does not contain a valid unsigned {@code int} value
317   * @since 13.0
318   */
319  @CanIgnoreReturnValue
320  public static int decode(String stringValue) {
321    ParseRequest request = ParseRequest.fromString(stringValue);
322
323    try {
324      return parseUnsignedInt(request.rawValue, request.radix);
325    } catch (NumberFormatException e) {
326      NumberFormatException decodeException =
327          new NumberFormatException("Error parsing value: " + stringValue);
328      decodeException.initCause(e);
329      throw decodeException;
330    }
331  }
332
333  /**
334   * Returns the unsigned {@code int} value represented by the given decimal string.
335   *
336   * <p><b>Java 8+ users:</b> use {@link Integer#parseUnsignedInt(String)} instead.
337   *
338   * @throws NumberFormatException if the string does not contain a valid unsigned {@code int} value
339   * @throws NullPointerException if {@code s} is null (in contrast to {@link
340   *     Integer#parseInt(String)})
341   */
342  @CanIgnoreReturnValue
343  public static int parseUnsignedInt(String s) {
344    return parseUnsignedInt(s, 10);
345  }
346
347  /**
348   * Returns the unsigned {@code int} value represented by a string with the given radix.
349   *
350   * <p><b>Java 8+ users:</b> use {@link Integer#parseUnsignedInt(String, int)} instead.
351   *
352   * @param string the string containing the unsigned integer representation to be parsed.
353   * @param radix the radix to use while parsing {@code s}; must be between {@link
354   *     Character#MIN_RADIX} and {@link Character#MAX_RADIX}.
355   * @throws NumberFormatException if the string does not contain a valid unsigned {@code int}, or
356   *     if supplied radix is invalid.
357   * @throws NullPointerException if {@code s} is null (in contrast to {@link
358   *     Integer#parseInt(String)})
359   */
360  @CanIgnoreReturnValue
361  public static int parseUnsignedInt(String string, int radix) {
362    checkNotNull(string);
363    long result = Long.parseLong(string, radix);
364    if ((result & INT_MASK) != result) {
365      throw new NumberFormatException(
366          "Input " + string + " in base " + radix + " is not in the range of an unsigned integer");
367    }
368    return (int) result;
369  }
370
371  /**
372   * Returns a string representation of x, where x is treated as unsigned.
373   *
374   * <p><b>Java 8+ users:</b> use {@link Integer#toUnsignedString(int)} instead.
375   */
376  public static String toString(int x) {
377    return toString(x, 10);
378  }
379
380  /**
381   * Returns a string representation of {@code x} for the given radix, where {@code x} is treated as
382   * unsigned.
383   *
384   * <p><b>Java 8+ users:</b> use {@link Integer#toUnsignedString(int, int)} instead.
385   *
386   * @param x the value to convert to a string.
387   * @param radix the radix to use while working with {@code x}
388   * @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX}
389   *     and {@link Character#MAX_RADIX}.
390   */
391  public static String toString(int x, int radix) {
392    long asLong = x & INT_MASK;
393    return Long.toString(asLong, radix);
394  }
395}