    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        @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 the given string.
    253       *
    254       * Accepts a decimal, hexadecimal, or octal number given by specifying the following prefix:
    255       *
    256       * <ul>
    257       * <li>{@code 0x}<i>HexDigits</i>
    258       * <li>{@code 0X}<i>HexDigits</i>
    259       * <li>{@code #}<i>HexDigits</i>
    260       * <li>{@code 0}<i>OctalDigits</i>
    261       * </ul>
    262       *
    263       * @throws NumberFormatException if the string does not contain a valid unsigned {@code long}
    264       *         value
    265       * @since 13.0
    266       */
    267      public static long decode(String stringValue) {
    268        ParseRequest request = ParseRequest.fromString(stringValue);
    269
    270        try {
    271          return parseUnsignedLong(request.rawValue, request.radix);
    272        } catch (NumberFormatException e) {
    273          NumberFormatException decodeException =
    274              new NumberFormatException("Error parsing value: " + stringValue);
    275          decodeException.initCause(e);
    276          throw decodeException;
    277        }
    278      }
    279
    280      /**
    281       * Returns the unsigned {@code long} value represented by a string with the given radix.
    282       *
    283       * @param s the string containing the unsigned {@code long} representation to be parsed.
    284       * @param radix the radix to use while parsing {@code s}
    285       * @throws NumberFormatException if the string does not contain a valid unsigned {@code long}
    286       *         with the given radix, or if {@code radix} is not between {@link Character#MIN_RADIX}
    287       *         and {@link Character#MAX_RADIX}.
    288       */
    289      public static long parseUnsignedLong(String s, int radix) {
    290        checkNotNull(s);
    291        if (s.length() == 0) {
    292          throw new NumberFormatException("empty string");
    293        }
    294        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
    295          throw new NumberFormatException("illegal radix: " + radix);
    296        }
    297
    298        int max_safe_pos = maxSafeDigits[radix] - 1;
    299        long value = 0;
    300        for (int pos = 0; pos < s.length(); pos++) {
    301          int digit = Character.digit(s.charAt(pos), radix);
    302          if (digit == -1) {
    303            throw new NumberFormatException(s);
    304          }
    305          if (pos > max_safe_pos && overflowInParse(value, digit, radix)) {
    306            throw new NumberFormatException("Too large for unsigned long: " + s);
    307          }
    308          value = (value * radix) + digit;
    309        }
    310
    311        return value;
    312      }
    313
    314      /**
    315       * Returns true if (current * radix) + digit is a number too large to be represented by an
    316       * unsigned long. This is useful for detecting overflow while parsing a string representation of
    317       * a number. Does not verify whether supplied radix is valid, passing an invalid radix will give
    318       * undefined results or an ArrayIndexOutOfBoundsException.
    319       */
    320      private static boolean overflowInParse(long current, int digit, int radix) {
    321        if (current >= 0) {
    322          if (current < maxValueDivs[radix]) {
    323            return false;
    324          }
    325          if (current > maxValueDivs[radix]) {
    326            return true;
    327          }
    328          // current == maxValueDivs[radix]
    329          return (digit > maxValueMods[radix]);
    330        }
    331
    332        // current < 0: high bit is set
    333        return true;
    334      }
    335
    336      /**
    337       * Returns a string representation of x, where x is treated as unsigned.
    338       */
    339      public static String toString(long x) {
    340        return toString(x, 10);
    341      }
    342
    343      /**
    344       * Returns a string representation of {@code x} for the given radix, where {@code x} is treated
    345       * as unsigned.
    346       *
    347       * @param x the value to convert to a string.
    348       * @param radix the radix to use while working with {@code x}
    349       * @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX}
    350       *         and {@link Character#MAX_RADIX}.
    351       */
    352      public static String toString(long x, int radix) {
    353        checkArgument(radix >= Character.MIN_RADIX && radix <= Character.MAX_RADIX,
    354            "radix (%s) must be between Character.MIN_RADIX and Character.MAX_RADIX", radix);
    355        if (x == 0) {
    356          // Simply return "0"
    357          return "0";
    358        } else {
    359          char[] buf = new char[64];
    360          int i = buf.length;
    361          if (x < 0) {
    362            // Separate off the last digit using unsigned division. That will leave
    363            // a number that is nonnegative as a signed integer.
    364            long quotient = divide(x, radix);
    365            long rem = x - quotient * radix;
    366            buf[--i] = Character.forDigit((int) rem, radix);
    367            x = quotient;
    368          }
    369          // Simple modulo/division approach
    370          while (x > 0) {
    371            buf[--i] = Character.forDigit((int) (x % radix), radix);
    372            x /= radix;
    373          }
    374          // Generate string
    375          return new String(buf, i, buf.length - i);
    376        }
    377      }
    378
    379      // calculated as 0xffffffffffffffff / radix
    380      private static final long[] maxValueDivs = new long[Character.MAX_RADIX + 1];
    381      private static final int[] maxValueMods = new int[Character.MAX_RADIX + 1];
    382      private static final int[] maxSafeDigits = new int[Character.MAX_RADIX + 1];
    383      static {
    384        BigInteger overflow = new BigInteger("10000000000000000", 16);
    385        for (int i = Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) {
    386          maxValueDivs[i] = divide(MAX_VALUE, i);
    387          maxValueMods[i] = (int) remainder(MAX_VALUE, i);
    388          maxSafeDigits[i] = overflow.toString(i).length() - 1;
    389        }
    390      }
    391    }