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