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.math.BigInteger; 024import java.util.Arrays; 025import java.util.Comparator; 026 027/** 028 * Static utility methods pertaining to {@code long} 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^64 + x}). The methods for which signedness is not an issue are in {@link Longs}, 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 a {@code long} to a 034 * {@code String} and a {@code String} to a {@code long} that treat the {@code long} 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 long} values. When possible, it is recommended that the {@link UnsignedLong} wrapper class 039 * 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 * @author Brian Milch 047 * @author Colin Evans 048 * @since 10.0 049 */ 050@GwtCompatible 051public final class UnsignedLongs { 052 private UnsignedLongs() {} 053 054 public static final long MAX_VALUE = -1L; // Equivalent to 2^64 - 1 055 056 /** 057 * A (self-inverse) bijection which converts the ordering on unsigned longs to the ordering on 058 * longs, that is, {@code a <= b} as unsigned longs if and only if {@code flip(a) <= flip(b)} as 059 * signed longs. 060 */ 061 private static long flip(long a) { 062 return a ^ Long.MIN_VALUE; 063 } 064 065 /** 066 * Compares the two specified {@code long} values, treating them as unsigned values between {@code 067 * 0} and {@code 2^64 - 1} inclusive. 068 * 069 * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated; use the 070 * equivalent {@link Long#compareUnsigned(long, long)} method instead. 071 * 072 * @param a the first unsigned {@code long} to compare 073 * @param b the second unsigned {@code long} to compare 074 * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is 075 * greater than {@code b}; or zero if they are equal 076 */ 077 @SuppressWarnings("InlineMeInliner") // Integer.compare unavailable under GWT+J2CL 078 public static int compare(long a, long b) { 079 return Longs.compare(flip(a), flip(b)); 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 long} 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 public static long min(long... array) { 091 checkArgument(array.length > 0); 092 long min = flip(array[0]); 093 for (int i = 1; i < array.length; i++) { 094 long next = flip(array[i]); 095 if (next < min) { 096 min = next; 097 } 098 } 099 return flip(min); 100 } 101 102 /** 103 * Returns the greatest value present in {@code array}, treating values as unsigned. 104 * 105 * @param array a <i>nonempty</i> array of unsigned {@code long} values 106 * @return the value present in {@code array} that is greater than or equal to every other value 107 * in the array according to {@link #compare} 108 * @throws IllegalArgumentException if {@code array} is empty 109 */ 110 public static long max(long... array) { 111 checkArgument(array.length > 0); 112 long max = flip(array[0]); 113 for (int i = 1; i < array.length; i++) { 114 long next = flip(array[i]); 115 if (next > max) { 116 max = next; 117 } 118 } 119 return flip(max); 120 } 121 122 /** 123 * Returns a string containing the supplied unsigned {@code long} values separated by {@code 124 * separator}. For example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}. 125 * 126 * @param separator the text that should appear between consecutive values in the resulting string 127 * (but not at the start or end) 128 * @param array an array of unsigned {@code long} values, possibly empty 129 */ 130 public static String join(String separator, long... array) { 131 checkNotNull(separator); 132 if (array.length == 0) { 133 return ""; 134 } 135 136 // For pre-sizing a builder, just get the right order of magnitude 137 StringBuilder builder = new StringBuilder(array.length * 5); 138 builder.append(toString(array[0])); 139 for (int i = 1; i < array.length; i++) { 140 builder.append(separator).append(toString(array[i])); 141 } 142 return builder.toString(); 143 } 144 145 /** 146 * Returns a comparator that compares two arrays of unsigned {@code long} values <a 147 * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it 148 * compares, using {@link #compare(long, long)}), the first pair of values that follow any common 149 * prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For 150 * example, {@code [] < [1L] < [1L, 2L] < [2L] < [1L << 63]}. 151 * 152 * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays 153 * support only identity equality), but it is consistent with {@link Arrays#equals(long[], 154 * long[])}. 155 * 156 * <p><b>Java 9+ users:</b> Use {@link Arrays#compareUnsigned(long[], long[]) 157 * Arrays::compareUnsigned}. 158 */ 159 public static Comparator<long[]> lexicographicalComparator() { 160 return LexicographicalComparator.INSTANCE; 161 } 162 163 enum LexicographicalComparator implements Comparator<long[]> { 164 INSTANCE; 165 166 @Override 167 public int compare(long[] left, long[] right) { 168 int minLength = Math.min(left.length, right.length); 169 for (int i = 0; i < minLength; i++) { 170 if (left[i] != right[i]) { 171 return UnsignedLongs.compare(left[i], right[i]); 172 } 173 } 174 return left.length - right.length; 175 } 176 177 @Override 178 public String toString() { 179 return "UnsignedLongs.lexicographicalComparator()"; 180 } 181 } 182 183 /** 184 * Sorts the array, treating its elements as unsigned 64-bit integers. 185 * 186 * @since 23.1 187 */ 188 public static void sort(long[] array) { 189 checkNotNull(array); 190 sort(array, 0, array.length); 191 } 192 193 /** 194 * Sorts the array between {@code fromIndex} inclusive and {@code toIndex} exclusive, treating its 195 * elements as unsigned 64-bit integers. 196 * 197 * @since 23.1 198 */ 199 public static void sort(long[] array, int fromIndex, int toIndex) { 200 checkNotNull(array); 201 checkPositionIndexes(fromIndex, toIndex, array.length); 202 for (int i = fromIndex; i < toIndex; i++) { 203 array[i] = flip(array[i]); 204 } 205 Arrays.sort(array, fromIndex, toIndex); 206 for (int i = fromIndex; i < toIndex; i++) { 207 array[i] = flip(array[i]); 208 } 209 } 210 211 /** 212 * Sorts the elements of {@code array} in descending order, interpreting them as unsigned 64-bit 213 * integers. 214 * 215 * @since 23.1 216 */ 217 public static void sortDescending(long[] array) { 218 checkNotNull(array); 219 sortDescending(array, 0, array.length); 220 } 221 222 /** 223 * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} 224 * exclusive in descending order, interpreting them as unsigned 64-bit integers. 225 * 226 * @since 23.1 227 */ 228 public static void sortDescending(long[] array, int fromIndex, int toIndex) { 229 checkNotNull(array); 230 checkPositionIndexes(fromIndex, toIndex, array.length); 231 for (int i = fromIndex; i < toIndex; i++) { 232 array[i] ^= Long.MAX_VALUE; 233 } 234 Arrays.sort(array, fromIndex, toIndex); 235 for (int i = fromIndex; i < toIndex; i++) { 236 array[i] ^= Long.MAX_VALUE; 237 } 238 } 239 240 /** 241 * Returns dividend / divisor, where the dividend and divisor are treated as unsigned 64-bit 242 * quantities. 243 * 244 * <p><b>Java 8+ users:</b> use {@link Long#divideUnsigned(long, long)} instead. 245 * 246 * @param dividend the dividend (numerator) 247 * @param divisor the divisor (denominator) 248 * @throws ArithmeticException if divisor is 0 249 */ 250 public static long divide(long dividend, long divisor) { 251 if (divisor < 0) { // i.e., divisor >= 2^63: 252 if (compare(dividend, divisor) < 0) { 253 return 0; // dividend < divisor 254 } else { 255 return 1; // dividend >= divisor 256 } 257 } 258 259 // Optimization - use signed division if dividend < 2^63 260 if (dividend >= 0) { 261 return dividend / divisor; 262 } 263 264 /* 265 * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is 266 * guaranteed to be either exact or one less than the correct value. This follows from fact that 267 * floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not quite 268 * trivial. 269 */ 270 long quotient = ((dividend >>> 1) / divisor) << 1; 271 long rem = dividend - quotient * divisor; 272 return quotient + (compare(rem, divisor) >= 0 ? 1 : 0); 273 } 274 275 /** 276 * Returns dividend % divisor, where the dividend and divisor are treated as unsigned 64-bit 277 * quantities. 278 * 279 * <p><b>Java 8+ users:</b> use {@link Long#remainderUnsigned(long, long)} instead. 280 * 281 * @param dividend the dividend (numerator) 282 * @param divisor the divisor (denominator) 283 * @throws ArithmeticException if divisor is 0 284 * @since 11.0 285 */ 286 public static long remainder(long dividend, long divisor) { 287 if (divisor < 0) { // i.e., divisor >= 2^63: 288 if (compare(dividend, divisor) < 0) { 289 return dividend; // dividend < divisor 290 } else { 291 return dividend - divisor; // dividend >= divisor 292 } 293 } 294 295 // Optimization - use signed modulus if dividend < 2^63 296 if (dividend >= 0) { 297 return dividend % divisor; 298 } 299 300 /* 301 * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is 302 * guaranteed to be either exact or one less than the correct value. This follows from the fact 303 * that floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not 304 * quite trivial. 305 */ 306 long quotient = ((dividend >>> 1) / divisor) << 1; 307 long rem = dividend - quotient * divisor; 308 return rem - (compare(rem, divisor) >= 0 ? divisor : 0); 309 } 310 311 /** 312 * Returns the unsigned {@code long} value represented by the given decimal string. 313 * 314 * <p><b>Java 8+ users:</b> use {@link Long#parseUnsignedLong(String)} instead. 315 * 316 * @throws NumberFormatException if the string does not contain a valid unsigned {@code long} 317 * value 318 * @throws NullPointerException if {@code string} is null (in contrast to {@link 319 * Long#parseLong(String)}) 320 */ 321 @CanIgnoreReturnValue 322 public static long parseUnsignedLong(String string) { 323 return parseUnsignedLong(string, 10); 324 } 325 326 /** 327 * Returns the unsigned {@code long} value represented by a string with the given radix. 328 * 329 * <p><b>Java 8+ users:</b> use {@link Long#parseUnsignedLong(String, int)} instead. 330 * 331 * @param string the string containing the unsigned {@code long} representation to be parsed. 332 * @param radix the radix to use while parsing {@code string} 333 * @throws NumberFormatException if the string does not contain a valid unsigned {@code long} with 334 * the given radix, or if {@code radix} is not between {@link Character#MIN_RADIX} and {@link 335 * Character#MAX_RADIX}. 336 * @throws NullPointerException if {@code string} is null (in contrast to {@link 337 * Long#parseLong(String)}) 338 */ 339 @CanIgnoreReturnValue 340 public static long parseUnsignedLong(String string, int radix) { 341 checkNotNull(string); 342 if (string.length() == 0) { 343 throw new NumberFormatException("empty string"); 344 } 345 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { 346 throw new NumberFormatException("illegal radix: " + radix); 347 } 348 349 int maxSafePos = ParseOverflowDetection.maxSafeDigits[radix] - 1; 350 long value = 0; 351 for (int pos = 0; pos < string.length(); pos++) { 352 int digit = Character.digit(string.charAt(pos), radix); 353 if (digit == -1) { 354 throw new NumberFormatException(string); 355 } 356 if (pos > maxSafePos && ParseOverflowDetection.overflowInParse(value, digit, radix)) { 357 throw new NumberFormatException("Too large for unsigned long: " + string); 358 } 359 value = (value * radix) + digit; 360 } 361 362 return value; 363 } 364 365 /** 366 * Returns the unsigned {@code long} value represented by the given string. 367 * 368 * <p>Accepts a decimal, hexadecimal, or octal number given by specifying the following prefix: 369 * 370 * <ul> 371 * <li>{@code 0x}<i>HexDigits</i> 372 * <li>{@code 0X}<i>HexDigits</i> 373 * <li>{@code #}<i>HexDigits</i> 374 * <li>{@code 0}<i>OctalDigits</i> 375 * </ul> 376 * 377 * @throws NumberFormatException if the string does not contain a valid unsigned {@code long} 378 * value 379 * @since 13.0 380 */ 381 @CanIgnoreReturnValue 382 public static long decode(String stringValue) { 383 ParseRequest request = ParseRequest.fromString(stringValue); 384 385 try { 386 return parseUnsignedLong(request.rawValue, request.radix); 387 } catch (NumberFormatException e) { 388 NumberFormatException decodeException = 389 new NumberFormatException("Error parsing value: " + stringValue); 390 decodeException.initCause(e); 391 throw decodeException; 392 } 393 } 394 395 /* 396 * We move the static constants into this class so ProGuard can inline UnsignedLongs entirely 397 * unless the user is actually calling a parse method. 398 */ 399 private static final class ParseOverflowDetection { 400 private ParseOverflowDetection() {} 401 402 // calculated as 0xffffffffffffffff / radix 403 static final long[] maxValueDivs = new long[Character.MAX_RADIX + 1]; 404 static final int[] maxValueMods = new int[Character.MAX_RADIX + 1]; 405 static final int[] maxSafeDigits = new int[Character.MAX_RADIX + 1]; 406 407 static { 408 BigInteger overflow = new BigInteger("10000000000000000", 16); 409 for (int i = Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) { 410 maxValueDivs[i] = divide(MAX_VALUE, i); 411 maxValueMods[i] = (int) remainder(MAX_VALUE, i); 412 maxSafeDigits[i] = overflow.toString(i).length() - 1; 413 } 414 } 415 416 /** 417 * Returns true if (current * radix) + digit is a number too large to be represented by an 418 * unsigned long. This is useful for detecting overflow while parsing a string representation of 419 * a number. Does not verify whether supplied radix is valid, passing an invalid radix will give 420 * undefined results or an ArrayIndexOutOfBoundsException. 421 */ 422 static boolean overflowInParse(long current, int digit, int radix) { 423 if (current >= 0) { 424 if (current < maxValueDivs[radix]) { 425 return false; 426 } 427 if (current > maxValueDivs[radix]) { 428 return true; 429 } 430 // current == maxValueDivs[radix] 431 return (digit > maxValueMods[radix]); 432 } 433 434 // current < 0: high bit is set 435 return true; 436 } 437 } 438 439 /** 440 * Returns a string representation of x, where x is treated as unsigned. 441 * 442 * <p><b>Java 8+ users:</b> use {@link Long#toUnsignedString(long)} instead. 443 */ 444 public static String toString(long x) { 445 return toString(x, 10); 446 } 447 448 /** 449 * Returns a string representation of {@code x} for the given radix, where {@code x} is treated as 450 * unsigned. 451 * 452 * <p><b>Java 8+ users:</b> use {@link Long#toUnsignedString(long, int)} instead. 453 * 454 * @param x the value to convert to a string. 455 * @param radix the radix to use while working with {@code x} 456 * @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX} 457 * and {@link Character#MAX_RADIX}. 458 */ 459 public static String toString(long x, int radix) { 460 checkArgument( 461 radix >= Character.MIN_RADIX && radix <= Character.MAX_RADIX, 462 "radix (%s) must be between Character.MIN_RADIX and Character.MAX_RADIX", 463 radix); 464 if (x == 0) { 465 // Simply return "0" 466 return "0"; 467 } else if (x > 0) { 468 return Long.toString(x, radix); 469 } else { 470 char[] buf = new char[64]; 471 int i = buf.length; 472 if ((radix & (radix - 1)) == 0) { 473 // Radix is a power of two so we can avoid division. 474 int shift = Integer.numberOfTrailingZeros(radix); 475 int mask = radix - 1; 476 do { 477 buf[--i] = Character.forDigit(((int) x) & mask, radix); 478 x >>>= shift; 479 } while (x != 0); 480 } else { 481 // Separate off the last digit using unsigned division. That will leave 482 // a number that is nonnegative as a signed integer. 483 long quotient; 484 if ((radix & 1) == 0) { 485 // Fast path for the usual case where the radix is even. 486 quotient = (x >>> 1) / (radix >>> 1); 487 } else { 488 quotient = divide(x, radix); 489 } 490 long rem = x - quotient * radix; 491 buf[--i] = Character.forDigit((int) rem, radix); 492 x = quotient; 493 // Simple modulo/division approach 494 while (x > 0) { 495 buf[--i] = Character.forDigit((int) (x % radix), radix); 496 x /= radix; 497 } 498 } 499 // Generate string 500 return new String(buf, i, buf.length - i); 501 } 502 } 503}