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