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 flip(a) <= flip(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 public int compare(long[] left, long[] right) {
163 int minLength = Math.min(left.length, right.length);
164 for (int i = 0; i < minLength; i++) {
165 if (left[i] != right[i]) {
166 return UnsignedLongs.compare(left[i], right[i]);
167 }
168 }
169 return left.length - right.length;
170 }
171 }
172
173 /**
174 * Returns dividend / divisor, where the dividend and divisor are treated as unsigned 64-bit
175 * quantities.
176 *
177 * @param dividend the dividend (numerator)
178 * @param divisor the divisor (denominator)
179 * @throws ArithmeticException if divisor is 0
180 */
181 public static long divide(long dividend, long divisor) {
182 if (divisor < 0) { // i.e., divisor >= 2^63:
183 if (compare(dividend, divisor) < 0) {
184 return 0; // dividend < divisor
185 } else {
186 return 1; // dividend >= divisor
187 }
188 }
189
190 // Optimization - use signed division if dividend < 2^63
191 if (dividend >= 0) {
192 return dividend / divisor;
193 }
194
195 /*
196 * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is
197 * guaranteed to be either exact or one less than the correct value. This follows from fact
198 * that floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not
199 * quite trivial.
200 */
201 long quotient = ((dividend >>> 1) / divisor) << 1;
202 long rem = dividend - quotient * divisor;
203 return quotient + (compare(rem, divisor) >= 0 ? 1 : 0);
204 }
205
206 /**
207 * Returns dividend % divisor, where the dividend and divisor are treated as unsigned 64-bit
208 * quantities.
209 *
210 * @param dividend the dividend (numerator)
211 * @param divisor the divisor (denominator)
212 * @throws ArithmeticException if divisor is 0
213 * @since 11.0
214 */
215 public static long remainder(long dividend, long divisor) {
216 if (divisor < 0) { // i.e., divisor >= 2^63:
217 if (compare(dividend, divisor) < 0) {
218 return dividend; // dividend < divisor
219 } else {
220 return dividend - divisor; // dividend >= divisor
221 }
222 }
223
224 // Optimization - use signed modulus if dividend < 2^63
225 if (dividend >= 0) {
226 return dividend % divisor;
227 }
228
229 /*
230 * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is
231 * guaranteed to be either exact or one less than the correct value. This follows from fact
232 * that floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not
233 * quite trivial.
234 */
235 long quotient = ((dividend >>> 1) / divisor) << 1;
236 long rem = dividend - quotient * divisor;
237 return rem - (compare(rem, divisor) >= 0 ? divisor : 0);
238 }
239
240 /**
241 * Returns the unsigned {@code long} value represented by the given decimal string.
242 *
243 * @throws NumberFormatException if the string does not contain a valid unsigned {@code long}
244 * value
245 */
246 public static long parseUnsignedLong(String s) {
247 return parseUnsignedLong(s, 10);
248 }
249
250 /**
251 * Returns the unsigned {@code long} value represented by the given string.
252 *
253 * Accepts a decimal, hexadecimal, or octal number given by specifying the following prefix:
254 *
255 * <ul>
256 * <li>{@code 0x}<i>HexDigits</i>
257 * <li>{@code 0X}<i>HexDigits</i>
258 * <li>{@code #}<i>HexDigits</i>
259 * <li>{@code 0}<i>OctalDigits</i>
260 * </ul>
261 *
262 * @throws NumberFormatException if the string does not contain a valid unsigned {@code long}
263 * value
264 * @since 13.0
265 */
266 public static long decode(String stringValue) {
267 ParseRequest request = ParseRequest.fromString(stringValue);
268
269 try {
270 return parseUnsignedLong(request.rawValue, request.radix);
271 } catch (NumberFormatException e) {
272 NumberFormatException decodeException =
273 new NumberFormatException("Error parsing value: " + stringValue);
274 decodeException.initCause(e);
275 throw decodeException;
276 }
277 }
278
279 /**
280 * Returns the unsigned {@code long} value represented by a string with the given radix.
281 *
282 * @param s the string containing the unsigned {@code long} representation to be parsed.
283 * @param radix the radix to use while parsing {@code s}
284 * @throws NumberFormatException if the string does not contain a valid unsigned {@code long}
285 * with the given radix, or if {@code radix} is not between {@link Character#MIN_RADIX}
286 * and {@link Character#MAX_RADIX}.
287 */
288 public static long parseUnsignedLong(String s, int radix) {
289 checkNotNull(s);
290 if (s.length() == 0) {
291 throw new NumberFormatException("empty string");
292 }
293 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
294 throw new NumberFormatException("illegal radix: " + radix);
295 }
296
297 int max_safe_pos = maxSafeDigits[radix] - 1;
298 long value = 0;
299 for (int pos = 0; pos < s.length(); pos++) {
300 int digit = Character.digit(s.charAt(pos), radix);
301 if (digit == -1) {
302 throw new NumberFormatException(s);
303 }
304 if (pos > max_safe_pos && overflowInParse(value, digit, radix)) {
305 throw new NumberFormatException("Too large for unsigned long: " + s);
306 }
307 value = (value * radix) + digit;
308 }
309
310 return value;
311 }
312
313 /**
314 * Returns true if (current * radix) + digit is a number too large to be represented by an
315 * unsigned long. This is useful for detecting overflow while parsing a string representation of
316 * a number. Does not verify whether supplied radix is valid, passing an invalid radix will give
317 * undefined results or an ArrayIndexOutOfBoundsException.
318 */
319 private static boolean overflowInParse(long current, int digit, int radix) {
320 if (current >= 0) {
321 if (current < maxValueDivs[radix]) {
322 return false;
323 }
324 if (current > maxValueDivs[radix]) {
325 return true;
326 }
327 // current == maxValueDivs[radix]
328 return (digit > maxValueMods[radix]);
329 }
330
331 // current < 0: high bit is set
332 return true;
333 }
334
335 /**
336 * Returns a string representation of x, where x is treated as unsigned.
337 */
338 public static String toString(long x) {
339 return toString(x, 10);
340 }
341
342 /**
343 * Returns a string representation of {@code x} for the given radix, where {@code x} is treated
344 * as unsigned.
345 *
346 * @param x the value to convert to a string.
347 * @param radix the radix to use while working with {@code x}
348 * @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX}
349 * and {@link Character#MAX_RADIX}.
350 */
351 public static String toString(long x, int radix) {
352 checkArgument(radix >= Character.MIN_RADIX && radix <= Character.MAX_RADIX,
353 "radix (%s) must be between Character.MIN_RADIX and Character.MAX_RADIX", radix);
354 if (x == 0) {
355 // Simply return "0"
356 return "0";
357 } else {
358 char[] buf = new char[64];
359 int i = buf.length;
360 if (x < 0) {
361 // Separate off the last digit using unsigned division. That will leave
362 // a number that is nonnegative as a signed integer.
363 long quotient = divide(x, radix);
364 long rem = x - quotient * radix;
365 buf[--i] = Character.forDigit((int) rem, radix);
366 x = quotient;
367 }
368 // Simple modulo/division approach
369 while (x > 0) {
370 buf[--i] = Character.forDigit((int) (x % radix), radix);
371 x /= radix;
372 }
373 // Generate string
374 return new String(buf, i, buf.length - i);
375 }
376 }
377
378 // calculated as 0xffffffffffffffff / radix
379 private static final long[] maxValueDivs = new long[Character.MAX_RADIX + 1];
380 private static final int[] maxValueMods = new int[Character.MAX_RADIX + 1];
381 private static final int[] maxSafeDigits = new int[Character.MAX_RADIX + 1];
382 static {
383 BigInteger overflow = new BigInteger("10000000000000000", 16);
384 for (int i = Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) {
385 maxValueDivs[i] = divide(MAX_VALUE, i);
386 maxValueMods[i] = (int) remainder(MAX_VALUE, i);
387 maxSafeDigits[i] = overflow.toString(i).length() - 1;
388 }
389 }
390 }