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 015 package com.google.common.primitives; 016 017 import static com.google.common.base.Preconditions.checkArgument; 018 import static com.google.common.base.Preconditions.checkNotNull; 019 020 import com.google.common.annotations.Beta; 021 import com.google.common.annotations.GwtCompatible; 022 023 import java.math.BigInteger; 024 import java.util.Arrays; 025 import 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 030 * {@code 2^64 + x}). The methods for which signedness is not an issue are in {@link Longs}, as 031 * well as 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 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 href= 042 * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained#Unsigned_support"> 043 * unsigned primitive utilities</a>. 044 * 045 * @author Louis Wasserman 046 * @author Brian Milch 047 * @author Colin Evans 048 * @since 10.0 049 */ 050 @Beta 051 @GwtCompatible 052 public final class UnsignedLongs { 053 private UnsignedLongs() {} 054 055 public static final long MAX_VALUE = -1L; // Equivalent to 2^64 - 1 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 rotate(a) <= rotate(b)} 060 * as 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 068 * {@code 0} and {@code 2^64 - 1} inclusive. 069 * 070 * @param a the first unsigned {@code long} to compare 071 * @param b the second unsigned {@code long} to compare 072 * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is 073 * greater than {@code b}; or zero if they are equal 074 */ 075 public static int compare(long a, long b) { 076 return Longs.compare(flip(a), flip(b)); 077 } 078 079 /** 080 * Returns the least value present in {@code array}, treating values as unsigned. 081 * 082 * @param array a <i>nonempty</i> array of unsigned {@code long} values 083 * @return the value present in {@code array} that is less than or equal to every other value in 084 * the array according to {@link #compare} 085 * @throws IllegalArgumentException if {@code array} is empty 086 */ 087 public static long min(long... array) { 088 checkArgument(array.length > 0); 089 long min = flip(array[0]); 090 for (int i = 1; i < array.length; i++) { 091 long next = flip(array[i]); 092 if (next < min) { 093 min = next; 094 } 095 } 096 return flip(min); 097 } 098 099 /** 100 * Returns the greatest value present in {@code array}, treating values as unsigned. 101 * 102 * @param array a <i>nonempty</i> array of unsigned {@code long} values 103 * @return the value present in {@code array} that is greater than or equal to every other value 104 * in the array according to {@link #compare} 105 * @throws IllegalArgumentException if {@code array} is empty 106 */ 107 public static long max(long... array) { 108 checkArgument(array.length > 0); 109 long max = flip(array[0]); 110 for (int i = 1; i < array.length; i++) { 111 long next = flip(array[i]); 112 if (next > max) { 113 max = next; 114 } 115 } 116 return flip(max); 117 } 118 119 /** 120 * Returns a string containing the supplied unsigned {@code long} values separated by 121 * {@code separator}. For example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}. 122 * 123 * @param separator the text that should appear between consecutive values in the resulting 124 * string (but not at the start or end) 125 * @param array an array of unsigned {@code long} values, possibly empty 126 */ 127 public static String join(String separator, long... array) { 128 checkNotNull(separator); 129 if (array.length == 0) { 130 return ""; 131 } 132 133 // For pre-sizing a builder, just get the right order of magnitude 134 StringBuilder builder = new StringBuilder(array.length * 5); 135 builder.append(toString(array[0])); 136 for (int i = 1; i < array.length; i++) { 137 builder.append(separator).append(toString(array[i])); 138 } 139 return builder.toString(); 140 } 141 142 /** 143 * Returns a comparator that compares two arrays of unsigned {@code long} values 144 * lexicographically. That is, it compares, using {@link #compare(long, long)}), the first pair of 145 * values that follow any common prefix, or when one array is a prefix of the other, treats the 146 * shorter array as the lesser. For example, {@code [] < [1L] < [1L, 2L] < [2L] < [1L << 63]}. 147 * 148 * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays 149 * support only identity equality), but it is consistent with 150 * {@link Arrays#equals(long[], long[])}. 151 * 152 * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">Lexicographical order 153 * article at Wikipedia</a> 154 */ 155 public static Comparator<long[]> lexicographicalComparator() { 156 return LexicographicalComparator.INSTANCE; 157 } 158 159 enum LexicographicalComparator implements Comparator<long[]> { 160 INSTANCE; 161 162 @Override 163 public int compare(long[] left, long[] right) { 164 int minLength = Math.min(left.length, right.length); 165 for (int i = 0; i < minLength; i++) { 166 if (left[i] != right[i]) { 167 return UnsignedLongs.compare(left[i], right[i]); 168 } 169 } 170 return left.length - right.length; 171 } 172 } 173 174 /** 175 * Returns dividend / divisor, where the dividend and divisor are treated as unsigned 64-bit 176 * quantities. 177 * 178 * @param dividend the dividend (numerator) 179 * @param divisor the divisor (denominator) 180 * @throws ArithmeticException if divisor is 0 181 */ 182 public static long divide(long dividend, long divisor) { 183 if (divisor < 0) { // i.e., divisor >= 2^63: 184 if (compare(dividend, divisor) < 0) { 185 return 0; // dividend < divisor 186 } else { 187 return 1; // dividend >= divisor 188 } 189 } 190 191 // Optimization - use signed division if dividend < 2^63 192 if (dividend >= 0) { 193 return dividend / divisor; 194 } 195 196 /* 197 * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is 198 * guaranteed to be either exact or one less than the correct value. This follows from fact 199 * that floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not 200 * quite trivial. 201 */ 202 long quotient = ((dividend >>> 1) / divisor) << 1; 203 long rem = dividend - quotient * divisor; 204 return quotient + (compare(rem, divisor) >= 0 ? 1 : 0); 205 } 206 207 /** 208 * Returns dividend % divisor, where the dividend and divisor are treated as unsigned 64-bit 209 * quantities. 210 * 211 * @param dividend the dividend (numerator) 212 * @param divisor the divisor (denominator) 213 * @throws ArithmeticException if divisor is 0 214 * @since 11.0 215 */ 216 public static long remainder(long dividend, long divisor) { 217 if (divisor < 0) { // i.e., divisor >= 2^63: 218 if (compare(dividend, divisor) < 0) { 219 return dividend; // dividend < divisor 220 } else { 221 return dividend - divisor; // dividend >= divisor 222 } 223 } 224 225 // Optimization - use signed modulus if dividend < 2^63 226 if (dividend >= 0) { 227 return dividend % divisor; 228 } 229 230 /* 231 * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is 232 * guaranteed to be either exact or one less than the correct value. This follows from fact 233 * that floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not 234 * quite trivial. 235 */ 236 long quotient = ((dividend >>> 1) / divisor) << 1; 237 long rem = dividend - quotient * divisor; 238 return rem - (compare(rem, divisor) >= 0 ? divisor : 0); 239 } 240 241 /** 242 * Returns the unsigned {@code long} value represented by the given decimal string. 243 * 244 * @throws NumberFormatException if the string does not contain a valid unsigned {@code long} 245 * value 246 */ 247 public static long parseUnsignedLong(String s) { 248 return parseUnsignedLong(s, 10); 249 } 250 251 /** 252 * Returns the unsigned {@code long} value represented by a string with the given radix. 253 * 254 * @param s the string containing the unsigned {@code long} representation to be parsed. 255 * @param radix the radix to use while parsing {@code s} 256 * @throws NumberFormatException if the string does not contain a valid unsigned {@code long} 257 * with the given radix, or if {@code radix} is not between {@link Character#MIN_RADIX} 258 * and {@link Character#MAX_RADIX}. 259 */ 260 public static long parseUnsignedLong(String s, int radix) { 261 checkNotNull(s); 262 if (s.length() == 0) { 263 throw new NumberFormatException("empty string"); 264 } 265 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { 266 throw new NumberFormatException("illegal radix: " + radix); 267 } 268 269 int max_safe_pos = maxSafeDigits[radix] - 1; 270 long value = 0; 271 for (int pos = 0; pos < s.length(); pos++) { 272 int digit = Character.digit(s.charAt(pos), radix); 273 if (digit == -1) { 274 throw new NumberFormatException(s); 275 } 276 if (pos > max_safe_pos && overflowInParse(value, digit, radix)) { 277 throw new NumberFormatException("Too large for unsigned long: " + s); 278 } 279 value = (value * radix) + digit; 280 } 281 282 return value; 283 } 284 285 /** 286 * Returns true if (current * radix) + digit is a number too large to be represented by an 287 * unsigned long. This is useful for detecting overflow while parsing a string representation of 288 * a number. Does not verify whether supplied radix is valid, passing an invalid radix will give 289 * undefined results or an ArrayIndexOutOfBoundsException. 290 */ 291 private static boolean overflowInParse(long current, int digit, int radix) { 292 if (current >= 0) { 293 if (current < maxValueDivs[radix]) { 294 return false; 295 } 296 if (current > maxValueDivs[radix]) { 297 return true; 298 } 299 // current == maxValueDivs[radix] 300 return (digit > maxValueMods[radix]); 301 } 302 303 // current < 0: high bit is set 304 return true; 305 } 306 307 /** 308 * Returns a string representation of x, where x is treated as unsigned. 309 */ 310 public static String toString(long x) { 311 return toString(x, 10); 312 } 313 314 /** 315 * Returns a string representation of {@code x} for the given radix, where {@code x} is treated 316 * as unsigned. 317 * 318 * @param x the value to convert to a string. 319 * @param radix the radix to use while working with {@code x} 320 * @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX} 321 * and {@link Character#MAX_RADIX}. 322 */ 323 public static String toString(long x, int radix) { 324 checkArgument(radix >= Character.MIN_RADIX && radix <= Character.MAX_RADIX, 325 "radix (%s) must be between Character.MIN_RADIX and Character.MAX_RADIX", radix); 326 if (x == 0) { 327 // Simply return "0" 328 return "0"; 329 } else { 330 char[] buf = new char[64]; 331 int i = buf.length; 332 if (x < 0) { 333 // Separate off the last digit using unsigned division. That will leave 334 // a number that is nonnegative as a signed integer. 335 long quotient = divide(x, radix); 336 long rem = x - quotient * radix; 337 buf[--i] = Character.forDigit((int) rem, radix); 338 x = quotient; 339 } 340 // Simple modulo/division approach 341 while (x > 0) { 342 buf[--i] = Character.forDigit((int) (x % radix), radix); 343 x /= radix; 344 } 345 // Generate string 346 return new String(buf, i, buf.length - i); 347 } 348 } 349 350 // calculated as 0xffffffffffffffff / radix 351 private static final long[] maxValueDivs = new long[Character.MAX_RADIX + 1]; 352 private static final int[] maxValueMods = new int[Character.MAX_RADIX + 1]; 353 private static final int[] maxSafeDigits = new int[Character.MAX_RADIX + 1]; 354 static { 355 BigInteger overflow = new BigInteger("10000000000000000", 16); 356 for (int i = Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) { 357 maxValueDivs[i] = divide(MAX_VALUE, i); 358 maxValueMods[i] = (int) remainder(MAX_VALUE, i); 359 maxSafeDigits[i] = overflow.toString(i).length() - 1; 360 } 361 } 362 }