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