emul/mini/src/main/java/java/lang/Long.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 26 Jan 2013 08:47:05 +0100
changeset 592 5e13b1ac2886
parent 179 469199c2994a
child 675 7d3da112e2c1
permissions -rw-r--r--
In order to support fields of the same name in subclasses we are now prefixing them with name of the class that defines them. To provide convenient way to access them from generated bytecode and also directly from JavaScript, there is a getter/setter function for each field. It starts with _ followed by the field name. If called with a parameter, it sets the field, with a parameter it just returns it.
     1 /*
     2  * Copyright (c) 1994, 2009, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    25 
    26 package java.lang;
    27 
    28 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    29 
    30 /**
    31  * The {@code Long} class wraps a value of the primitive type {@code
    32  * long} in an object. An object of type {@code Long} contains a
    33  * single field whose type is {@code long}.
    34  *
    35  * <p> In addition, this class provides several methods for converting
    36  * a {@code long} to a {@code String} and a {@code String} to a {@code
    37  * long}, as well as other constants and methods useful when dealing
    38  * with a {@code long}.
    39  *
    40  * <p>Implementation note: The implementations of the "bit twiddling"
    41  * methods (such as {@link #highestOneBit(long) highestOneBit} and
    42  * {@link #numberOfTrailingZeros(long) numberOfTrailingZeros}) are
    43  * based on material from Henry S. Warren, Jr.'s <i>Hacker's
    44  * Delight</i>, (Addison Wesley, 2002).
    45  *
    46  * @author  Lee Boynton
    47  * @author  Arthur van Hoff
    48  * @author  Josh Bloch
    49  * @author  Joseph D. Darcy
    50  * @since   JDK1.0
    51  */
    52 public final class Long extends Number implements Comparable<Long> {
    53     /**
    54      * A constant holding the minimum value a {@code long} can
    55      * have, -2<sup>63</sup>.
    56      */
    57     public static final long MIN_VALUE = 0x8000000000000000L;
    58 
    59     /**
    60      * A constant holding the maximum value a {@code long} can
    61      * have, 2<sup>63</sup>-1.
    62      */
    63     public static final long MAX_VALUE = 0x7fffffffffffffffL;
    64 
    65     /**
    66      * The {@code Class} instance representing the primitive type
    67      * {@code long}.
    68      *
    69      * @since   JDK1.1
    70      */
    71     public static final Class<Long>     TYPE = (Class<Long>) Class.getPrimitiveClass("long");
    72 
    73     /**
    74      * Returns a string representation of the first argument in the
    75      * radix specified by the second argument.
    76      *
    77      * <p>If the radix is smaller than {@code Character.MIN_RADIX}
    78      * or larger than {@code Character.MAX_RADIX}, then the radix
    79      * {@code 10} is used instead.
    80      *
    81      * <p>If the first argument is negative, the first element of the
    82      * result is the ASCII minus sign {@code '-'}
    83      * (<code>'&#92;u002d'</code>). If the first argument is not
    84      * negative, no sign character appears in the result.
    85      *
    86      * <p>The remaining characters of the result represent the magnitude
    87      * of the first argument. If the magnitude is zero, it is
    88      * represented by a single zero character {@code '0'}
    89      * (<code>'&#92;u0030'</code>); otherwise, the first character of
    90      * the representation of the magnitude will not be the zero
    91      * character.  The following ASCII characters are used as digits:
    92      *
    93      * <blockquote>
    94      *   {@code 0123456789abcdefghijklmnopqrstuvwxyz}
    95      * </blockquote>
    96      *
    97      * These are <code>'&#92;u0030'</code> through
    98      * <code>'&#92;u0039'</code> and <code>'&#92;u0061'</code> through
    99      * <code>'&#92;u007a'</code>. If {@code radix} is
   100      * <var>N</var>, then the first <var>N</var> of these characters
   101      * are used as radix-<var>N</var> digits in the order shown. Thus,
   102      * the digits for hexadecimal (radix 16) are
   103      * {@code 0123456789abcdef}. If uppercase letters are
   104      * desired, the {@link java.lang.String#toUpperCase()} method may
   105      * be called on the result:
   106      *
   107      * <blockquote>
   108      *  {@code Long.toString(n, 16).toUpperCase()}
   109      * </blockquote>
   110      *
   111      * @param   i       a {@code long} to be converted to a string.
   112      * @param   radix   the radix to use in the string representation.
   113      * @return  a string representation of the argument in the specified radix.
   114      * @see     java.lang.Character#MAX_RADIX
   115      * @see     java.lang.Character#MIN_RADIX
   116      */
   117     public static String toString(long i, int radix) {
   118         if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
   119             radix = 10;
   120         if (radix == 10)
   121             return toString(i);
   122         char[] buf = new char[65];
   123         int charPos = 64;
   124         boolean negative = (i < 0);
   125 
   126         if (!negative) {
   127             i = -i;
   128         }
   129 
   130         while (i <= -radix) {
   131             buf[charPos--] = Integer.digits[(int)(-(i % radix))];
   132             i = i / radix;
   133         }
   134         buf[charPos] = Integer.digits[(int)(-i)];
   135 
   136         if (negative) {
   137             buf[--charPos] = '-';
   138         }
   139 
   140         return new String(buf, charPos, (65 - charPos));
   141     }
   142 
   143     /**
   144      * Returns a string representation of the {@code long}
   145      * argument as an unsigned integer in base&nbsp;16.
   146      *
   147      * <p>The unsigned {@code long} value is the argument plus
   148      * 2<sup>64</sup> if the argument is negative; otherwise, it is
   149      * equal to the argument.  This value is converted to a string of
   150      * ASCII digits in hexadecimal (base&nbsp;16) with no extra
   151      * leading {@code 0}s.  If the unsigned magnitude is zero, it
   152      * is represented by a single zero character {@code '0'}
   153      * (<code>'&#92;u0030'</code>); otherwise, the first character of
   154      * the representation of the unsigned magnitude will not be the
   155      * zero character. The following characters are used as
   156      * hexadecimal digits:
   157      *
   158      * <blockquote>
   159      *  {@code 0123456789abcdef}
   160      * </blockquote>
   161      *
   162      * These are the characters <code>'&#92;u0030'</code> through
   163      * <code>'&#92;u0039'</code> and  <code>'&#92;u0061'</code> through
   164      * <code>'&#92;u0066'</code>.  If uppercase letters are desired,
   165      * the {@link java.lang.String#toUpperCase()} method may be called
   166      * on the result:
   167      *
   168      * <blockquote>
   169      *  {@code Long.toHexString(n).toUpperCase()}
   170      * </blockquote>
   171      *
   172      * @param   i   a {@code long} to be converted to a string.
   173      * @return  the string representation of the unsigned {@code long}
   174      *          value represented by the argument in hexadecimal
   175      *          (base&nbsp;16).
   176      * @since   JDK 1.0.2
   177      */
   178     public static String toHexString(long i) {
   179         return toUnsignedString(i, 4);
   180     }
   181 
   182     /**
   183      * Returns a string representation of the {@code long}
   184      * argument as an unsigned integer in base&nbsp;8.
   185      *
   186      * <p>The unsigned {@code long} value is the argument plus
   187      * 2<sup>64</sup> if the argument is negative; otherwise, it is
   188      * equal to the argument.  This value is converted to a string of
   189      * ASCII digits in octal (base&nbsp;8) with no extra leading
   190      * {@code 0}s.
   191      *
   192      * <p>If the unsigned magnitude is zero, it is represented by a
   193      * single zero character {@code '0'}
   194      * (<code>'&#92;u0030'</code>); otherwise, the first character of
   195      * the representation of the unsigned magnitude will not be the
   196      * zero character. The following characters are used as octal
   197      * digits:
   198      *
   199      * <blockquote>
   200      *  {@code 01234567}
   201      * </blockquote>
   202      *
   203      * These are the characters <code>'&#92;u0030'</code> through
   204      * <code>'&#92;u0037'</code>.
   205      *
   206      * @param   i   a {@code long} to be converted to a string.
   207      * @return  the string representation of the unsigned {@code long}
   208      *          value represented by the argument in octal (base&nbsp;8).
   209      * @since   JDK 1.0.2
   210      */
   211     public static String toOctalString(long i) {
   212         return toUnsignedString(i, 3);
   213     }
   214 
   215     /**
   216      * Returns a string representation of the {@code long}
   217      * argument as an unsigned integer in base&nbsp;2.
   218      *
   219      * <p>The unsigned {@code long} value is the argument plus
   220      * 2<sup>64</sup> if the argument is negative; otherwise, it is
   221      * equal to the argument.  This value is converted to a string of
   222      * ASCII digits in binary (base&nbsp;2) with no extra leading
   223      * {@code 0}s.  If the unsigned magnitude is zero, it is
   224      * represented by a single zero character {@code '0'}
   225      * (<code>'&#92;u0030'</code>); otherwise, the first character of
   226      * the representation of the unsigned magnitude will not be the
   227      * zero character. The characters {@code '0'}
   228      * (<code>'&#92;u0030'</code>) and {@code '1'}
   229      * (<code>'&#92;u0031'</code>) are used as binary digits.
   230      *
   231      * @param   i   a {@code long} to be converted to a string.
   232      * @return  the string representation of the unsigned {@code long}
   233      *          value represented by the argument in binary (base&nbsp;2).
   234      * @since   JDK 1.0.2
   235      */
   236     public static String toBinaryString(long i) {
   237         return toUnsignedString(i, 1);
   238     }
   239 
   240     /**
   241      * Convert the integer to an unsigned number.
   242      */
   243     private static String toUnsignedString(long i, int shift) {
   244         char[] buf = new char[64];
   245         int charPos = 64;
   246         int radix = 1 << shift;
   247         long mask = radix - 1;
   248         do {
   249             buf[--charPos] = Integer.digits[(int)(i & mask)];
   250             i >>>= shift;
   251         } while (i != 0);
   252         return new String(buf, charPos, (64 - charPos));
   253     }
   254 
   255     /**
   256      * Returns a {@code String} object representing the specified
   257      * {@code long}.  The argument is converted to signed decimal
   258      * representation and returned as a string, exactly as if the
   259      * argument and the radix 10 were given as arguments to the {@link
   260      * #toString(long, int)} method.
   261      *
   262      * @param   i   a {@code long} to be converted.
   263      * @return  a string representation of the argument in base&nbsp;10.
   264      */
   265     @JavaScriptBody(args = "i", body = "return i.toString();")
   266     public static String toString(long i) {
   267         if (i == Long.MIN_VALUE)
   268             return "-9223372036854775808";
   269         int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
   270         char[] buf = new char[size];
   271         getChars(i, size, buf);
   272         return new String(buf, 0, size);
   273     }
   274 
   275     /**
   276      * Places characters representing the integer i into the
   277      * character array buf. The characters are placed into
   278      * the buffer backwards starting with the least significant
   279      * digit at the specified index (exclusive), and working
   280      * backwards from there.
   281      *
   282      * Will fail if i == Long.MIN_VALUE
   283      */
   284     static void getChars(long i, int index, char[] buf) {
   285         long q;
   286         int r;
   287         int charPos = index;
   288         char sign = 0;
   289 
   290         if (i < 0) {
   291             sign = '-';
   292             i = -i;
   293         }
   294 
   295         // Get 2 digits/iteration using longs until quotient fits into an int
   296         while (i > Integer.MAX_VALUE) {
   297             q = i / 100;
   298             // really: r = i - (q * 100);
   299             r = (int)(i - ((q << 6) + (q << 5) + (q << 2)));
   300             i = q;
   301             buf[--charPos] = Integer.DigitOnes[r];
   302             buf[--charPos] = Integer.DigitTens[r];
   303         }
   304 
   305         // Get 2 digits/iteration using ints
   306         int q2;
   307         int i2 = (int)i;
   308         while (i2 >= 65536) {
   309             q2 = i2 / 100;
   310             // really: r = i2 - (q * 100);
   311             r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));
   312             i2 = q2;
   313             buf[--charPos] = Integer.DigitOnes[r];
   314             buf[--charPos] = Integer.DigitTens[r];
   315         }
   316 
   317         // Fall thru to fast mode for smaller numbers
   318         // assert(i2 <= 65536, i2);
   319         for (;;) {
   320             q2 = (i2 * 52429) >>> (16+3);
   321             r = i2 - ((q2 << 3) + (q2 << 1));  // r = i2-(q2*10) ...
   322             buf[--charPos] = Integer.digits[r];
   323             i2 = q2;
   324             if (i2 == 0) break;
   325         }
   326         if (sign != 0) {
   327             buf[--charPos] = sign;
   328         }
   329     }
   330 
   331     // Requires positive x
   332     static int stringSize(long x) {
   333         long p = 10;
   334         for (int i=1; i<19; i++) {
   335             if (x < p)
   336                 return i;
   337             p = 10*p;
   338         }
   339         return 19;
   340     }
   341 
   342     /**
   343      * Parses the string argument as a signed {@code long} in the
   344      * radix specified by the second argument. The characters in the
   345      * string must all be digits of the specified radix (as determined
   346      * by whether {@link java.lang.Character#digit(char, int)} returns
   347      * a nonnegative value), except that the first character may be an
   348      * ASCII minus sign {@code '-'} (<code>'&#92;u002D'</code>) to
   349      * indicate a negative value or an ASCII plus sign {@code '+'}
   350      * (<code>'&#92;u002B'</code>) to indicate a positive value. The
   351      * resulting {@code long} value is returned.
   352      *
   353      * <p>Note that neither the character {@code L}
   354      * (<code>'&#92;u004C'</code>) nor {@code l}
   355      * (<code>'&#92;u006C'</code>) is permitted to appear at the end
   356      * of the string as a type indicator, as would be permitted in
   357      * Java programming language source code - except that either
   358      * {@code L} or {@code l} may appear as a digit for a
   359      * radix greater than 22.
   360      *
   361      * <p>An exception of type {@code NumberFormatException} is
   362      * thrown if any of the following situations occurs:
   363      * <ul>
   364      *
   365      * <li>The first argument is {@code null} or is a string of
   366      * length zero.
   367      *
   368      * <li>The {@code radix} is either smaller than {@link
   369      * java.lang.Character#MIN_RADIX} or larger than {@link
   370      * java.lang.Character#MAX_RADIX}.
   371      *
   372      * <li>Any character of the string is not a digit of the specified
   373      * radix, except that the first character may be a minus sign
   374      * {@code '-'} (<code>'&#92;u002d'</code>) or plus sign {@code
   375      * '+'} (<code>'&#92;u002B'</code>) provided that the string is
   376      * longer than length 1.
   377      *
   378      * <li>The value represented by the string is not a value of type
   379      *      {@code long}.
   380      * </ul>
   381      *
   382      * <p>Examples:
   383      * <blockquote><pre>
   384      * parseLong("0", 10) returns 0L
   385      * parseLong("473", 10) returns 473L
   386      * parseLong("+42", 10) returns 42L
   387      * parseLong("-0", 10) returns 0L
   388      * parseLong("-FF", 16) returns -255L
   389      * parseLong("1100110", 2) returns 102L
   390      * parseLong("99", 8) throws a NumberFormatException
   391      * parseLong("Hazelnut", 10) throws a NumberFormatException
   392      * parseLong("Hazelnut", 36) returns 1356099454469L
   393      * </pre></blockquote>
   394      *
   395      * @param      s       the {@code String} containing the
   396      *                     {@code long} representation to be parsed.
   397      * @param      radix   the radix to be used while parsing {@code s}.
   398      * @return     the {@code long} represented by the string argument in
   399      *             the specified radix.
   400      * @throws     NumberFormatException  if the string does not contain a
   401      *             parsable {@code long}.
   402      */
   403     public static long parseLong(String s, int radix)
   404               throws NumberFormatException
   405     {
   406         if (s == null) {
   407             throw new NumberFormatException("null");
   408         }
   409 
   410         if (radix < Character.MIN_RADIX) {
   411             throw new NumberFormatException("radix " + radix +
   412                                             " less than Character.MIN_RADIX");
   413         }
   414         if (radix > Character.MAX_RADIX) {
   415             throw new NumberFormatException("radix " + radix +
   416                                             " greater than Character.MAX_RADIX");
   417         }
   418 
   419         long result = 0;
   420         boolean negative = false;
   421         int i = 0, len = s.length();
   422         long limit = -Long.MAX_VALUE;
   423         long multmin;
   424         int digit;
   425 
   426         if (len > 0) {
   427             char firstChar = s.charAt(0);
   428             if (firstChar < '0') { // Possible leading "+" or "-"
   429                 if (firstChar == '-') {
   430                     negative = true;
   431                     limit = Long.MIN_VALUE;
   432                 } else if (firstChar != '+')
   433                     throw NumberFormatException.forInputString(s);
   434 
   435                 if (len == 1) // Cannot have lone "+" or "-"
   436                     throw NumberFormatException.forInputString(s);
   437                 i++;
   438             }
   439             multmin = limit / radix;
   440             while (i < len) {
   441                 // Accumulating negatively avoids surprises near MAX_VALUE
   442                 digit = Character.digit(s.charAt(i++),radix);
   443                 if (digit < 0) {
   444                     throw NumberFormatException.forInputString(s);
   445                 }
   446                 if (result < multmin) {
   447                     throw NumberFormatException.forInputString(s);
   448                 }
   449                 result *= radix;
   450                 if (result < limit + digit) {
   451                     throw NumberFormatException.forInputString(s);
   452                 }
   453                 result -= digit;
   454             }
   455         } else {
   456             throw NumberFormatException.forInputString(s);
   457         }
   458         return negative ? result : -result;
   459     }
   460 
   461     /**
   462      * Parses the string argument as a signed decimal {@code long}.
   463      * The characters in the string must all be decimal digits, except
   464      * that the first character may be an ASCII minus sign {@code '-'}
   465      * (<code>&#92;u002D'</code>) to indicate a negative value or an
   466      * ASCII plus sign {@code '+'} (<code>'&#92;u002B'</code>) to
   467      * indicate a positive value. The resulting {@code long} value is
   468      * returned, exactly as if the argument and the radix {@code 10}
   469      * were given as arguments to the {@link
   470      * #parseLong(java.lang.String, int)} method.
   471      *
   472      * <p>Note that neither the character {@code L}
   473      * (<code>'&#92;u004C'</code>) nor {@code l}
   474      * (<code>'&#92;u006C'</code>) is permitted to appear at the end
   475      * of the string as a type indicator, as would be permitted in
   476      * Java programming language source code.
   477      *
   478      * @param      s   a {@code String} containing the {@code long}
   479      *             representation to be parsed
   480      * @return     the {@code long} represented by the argument in
   481      *             decimal.
   482      * @throws     NumberFormatException  if the string does not contain a
   483      *             parsable {@code long}.
   484      */
   485     public static long parseLong(String s) throws NumberFormatException {
   486         return parseLong(s, 10);
   487     }
   488 
   489     /**
   490      * Returns a {@code Long} object holding the value
   491      * extracted from the specified {@code String} when parsed
   492      * with the radix given by the second argument.  The first
   493      * argument is interpreted as representing a signed
   494      * {@code long} in the radix specified by the second
   495      * argument, exactly as if the arguments were given to the {@link
   496      * #parseLong(java.lang.String, int)} method. The result is a
   497      * {@code Long} object that represents the {@code long}
   498      * value specified by the string.
   499      *
   500      * <p>In other words, this method returns a {@code Long} object equal
   501      * to the value of:
   502      *
   503      * <blockquote>
   504      *  {@code new Long(Long.parseLong(s, radix))}
   505      * </blockquote>
   506      *
   507      * @param      s       the string to be parsed
   508      * @param      radix   the radix to be used in interpreting {@code s}
   509      * @return     a {@code Long} object holding the value
   510      *             represented by the string argument in the specified
   511      *             radix.
   512      * @throws     NumberFormatException  If the {@code String} does not
   513      *             contain a parsable {@code long}.
   514      */
   515     public static Long valueOf(String s, int radix) throws NumberFormatException {
   516         return Long.valueOf(parseLong(s, radix));
   517     }
   518 
   519     /**
   520      * Returns a {@code Long} object holding the value
   521      * of the specified {@code String}. The argument is
   522      * interpreted as representing a signed decimal {@code long},
   523      * exactly as if the argument were given to the {@link
   524      * #parseLong(java.lang.String)} method. The result is a
   525      * {@code Long} object that represents the integer value
   526      * specified by the string.
   527      *
   528      * <p>In other words, this method returns a {@code Long} object
   529      * equal to the value of:
   530      *
   531      * <blockquote>
   532      *  {@code new Long(Long.parseLong(s))}
   533      * </blockquote>
   534      *
   535      * @param      s   the string to be parsed.
   536      * @return     a {@code Long} object holding the value
   537      *             represented by the string argument.
   538      * @throws     NumberFormatException  If the string cannot be parsed
   539      *             as a {@code long}.
   540      */
   541     public static Long valueOf(String s) throws NumberFormatException
   542     {
   543         return Long.valueOf(parseLong(s, 10));
   544     }
   545 
   546     private static class LongCache {
   547         private LongCache(){}
   548 
   549         static final Long cache[] = new Long[-(-128) + 127 + 1];
   550 
   551         static {
   552             for(int i = 0; i < cache.length; i++)
   553                 cache[i] = new Long(i - 128);
   554         }
   555     }
   556 
   557     /**
   558      * Returns a {@code Long} instance representing the specified
   559      * {@code long} value.
   560      * If a new {@code Long} instance is not required, this method
   561      * should generally be used in preference to the constructor
   562      * {@link #Long(long)}, as this method is likely to yield
   563      * significantly better space and time performance by caching
   564      * frequently requested values.
   565      *
   566      * Note that unlike the {@linkplain Integer#valueOf(int)
   567      * corresponding method} in the {@code Integer} class, this method
   568      * is <em>not</em> required to cache values within a particular
   569      * range.
   570      *
   571      * @param  l a long value.
   572      * @return a {@code Long} instance representing {@code l}.
   573      * @since  1.5
   574      */
   575     public static Long valueOf(long l) {
   576         final int offset = 128;
   577         if (l >= -128 && l <= 127) { // will cache
   578             return LongCache.cache[(int)l + offset];
   579         }
   580         return new Long(l);
   581     }
   582 
   583     /**
   584      * Decodes a {@code String} into a {@code Long}.
   585      * Accepts decimal, hexadecimal, and octal numbers given by the
   586      * following grammar:
   587      *
   588      * <blockquote>
   589      * <dl>
   590      * <dt><i>DecodableString:</i>
   591      * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
   592      * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
   593      * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
   594      * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
   595      * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
   596      * <p>
   597      * <dt><i>Sign:</i>
   598      * <dd>{@code -}
   599      * <dd>{@code +}
   600      * </dl>
   601      * </blockquote>
   602      *
   603      * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
   604      * are as defined in section 3.10.1 of
   605      * <cite>The Java&trade; Language Specification</cite>,
   606      * except that underscores are not accepted between digits.
   607      *
   608      * <p>The sequence of characters following an optional
   609      * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
   610      * "{@code #}", or leading zero) is parsed as by the {@code
   611      * Long.parseLong} method with the indicated radix (10, 16, or 8).
   612      * This sequence of characters must represent a positive value or
   613      * a {@link NumberFormatException} will be thrown.  The result is
   614      * negated if first character of the specified {@code String} is
   615      * the minus sign.  No whitespace characters are permitted in the
   616      * {@code String}.
   617      *
   618      * @param     nm the {@code String} to decode.
   619      * @return    a {@code Long} object holding the {@code long}
   620      *            value represented by {@code nm}
   621      * @throws    NumberFormatException  if the {@code String} does not
   622      *            contain a parsable {@code long}.
   623      * @see java.lang.Long#parseLong(String, int)
   624      * @since 1.2
   625      */
   626     public static Long decode(String nm) throws NumberFormatException {
   627         int radix = 10;
   628         int index = 0;
   629         boolean negative = false;
   630         Long result;
   631 
   632         if (nm.length() == 0)
   633             throw new NumberFormatException("Zero length string");
   634         char firstChar = nm.charAt(0);
   635         // Handle sign, if present
   636         if (firstChar == '-') {
   637             negative = true;
   638             index++;
   639         } else if (firstChar == '+')
   640             index++;
   641 
   642         // Handle radix specifier, if present
   643         if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
   644             index += 2;
   645             radix = 16;
   646         }
   647         else if (nm.startsWith("#", index)) {
   648             index ++;
   649             radix = 16;
   650         }
   651         else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
   652             index ++;
   653             radix = 8;
   654         }
   655 
   656         if (nm.startsWith("-", index) || nm.startsWith("+", index))
   657             throw new NumberFormatException("Sign character in wrong position");
   658 
   659         try {
   660             result = Long.valueOf(nm.substring(index), radix);
   661             result = negative ? Long.valueOf(-result.longValue()) : result;
   662         } catch (NumberFormatException e) {
   663             // If number is Long.MIN_VALUE, we'll end up here. The next line
   664             // handles this case, and causes any genuine format error to be
   665             // rethrown.
   666             String constant = negative ? ("-" + nm.substring(index))
   667                                        : nm.substring(index);
   668             result = Long.valueOf(constant, radix);
   669         }
   670         return result;
   671     }
   672 
   673     /**
   674      * The value of the {@code Long}.
   675      *
   676      * @serial
   677      */
   678     private final long value;
   679 
   680     /**
   681      * Constructs a newly allocated {@code Long} object that
   682      * represents the specified {@code long} argument.
   683      *
   684      * @param   value   the value to be represented by the
   685      *          {@code Long} object.
   686      */
   687     public Long(long value) {
   688         this.value = value;
   689     }
   690 
   691     /**
   692      * Constructs a newly allocated {@code Long} object that
   693      * represents the {@code long} value indicated by the
   694      * {@code String} parameter. The string is converted to a
   695      * {@code long} value in exactly the manner used by the
   696      * {@code parseLong} method for radix 10.
   697      *
   698      * @param      s   the {@code String} to be converted to a
   699      *             {@code Long}.
   700      * @throws     NumberFormatException  if the {@code String} does not
   701      *             contain a parsable {@code long}.
   702      * @see        java.lang.Long#parseLong(java.lang.String, int)
   703      */
   704     public Long(String s) throws NumberFormatException {
   705         this.value = parseLong(s, 10);
   706     }
   707 
   708     /**
   709      * Returns the value of this {@code Long} as a
   710      * {@code byte}.
   711      */
   712     public byte byteValue() {
   713         return (byte)value;
   714     }
   715 
   716     /**
   717      * Returns the value of this {@code Long} as a
   718      * {@code short}.
   719      */
   720     public short shortValue() {
   721         return (short)value;
   722     }
   723 
   724     /**
   725      * Returns the value of this {@code Long} as an
   726      * {@code int}.
   727      */
   728     public int intValue() {
   729         return (int)value;
   730     }
   731 
   732     /**
   733      * Returns the value of this {@code Long} as a
   734      * {@code long} value.
   735      */
   736     public long longValue() {
   737         return (long)value;
   738     }
   739 
   740     /**
   741      * Returns the value of this {@code Long} as a
   742      * {@code float}.
   743      */
   744     public float floatValue() {
   745         return (float)value;
   746     }
   747 
   748     /**
   749      * Returns the value of this {@code Long} as a
   750      * {@code double}.
   751      */
   752     public double doubleValue() {
   753         return (double)value;
   754     }
   755 
   756     /**
   757      * Returns a {@code String} object representing this
   758      * {@code Long}'s value.  The value is converted to signed
   759      * decimal representation and returned as a string, exactly as if
   760      * the {@code long} value were given as an argument to the
   761      * {@link java.lang.Long#toString(long)} method.
   762      *
   763      * @return  a string representation of the value of this object in
   764      *          base&nbsp;10.
   765      */
   766     public String toString() {
   767         return toString(value);
   768     }
   769 
   770     /**
   771      * Returns a hash code for this {@code Long}. The result is
   772      * the exclusive OR of the two halves of the primitive
   773      * {@code long} value held by this {@code Long}
   774      * object. That is, the hashcode is the value of the expression:
   775      *
   776      * <blockquote>
   777      *  {@code (int)(this.longValue()^(this.longValue()>>>32))}
   778      * </blockquote>
   779      *
   780      * @return  a hash code value for this object.
   781      */
   782     public int hashCode() {
   783         return (int)(value ^ (value >>> 32));
   784     }
   785 
   786     /**
   787      * Compares this object to the specified object.  The result is
   788      * {@code true} if and only if the argument is not
   789      * {@code null} and is a {@code Long} object that
   790      * contains the same {@code long} value as this object.
   791      *
   792      * @param   obj   the object to compare with.
   793      * @return  {@code true} if the objects are the same;
   794      *          {@code false} otherwise.
   795      */
   796     public boolean equals(Object obj) {
   797         if (obj instanceof Long) {
   798             return value == ((Long)obj).longValue();
   799         }
   800         return false;
   801     }
   802 
   803     /**
   804      * Determines the {@code long} value of the system property
   805      * with the specified name.
   806      *
   807      * <p>The first argument is treated as the name of a system property.
   808      * System properties are accessible through the {@link
   809      * java.lang.System#getProperty(java.lang.String)} method. The
   810      * string value of this property is then interpreted as a
   811      * {@code long} value and a {@code Long} object
   812      * representing this value is returned.  Details of possible
   813      * numeric formats can be found with the definition of
   814      * {@code getProperty}.
   815      *
   816      * <p>If there is no property with the specified name, if the
   817      * specified name is empty or {@code null}, or if the
   818      * property does not have the correct numeric format, then
   819      * {@code null} is returned.
   820      *
   821      * <p>In other words, this method returns a {@code Long} object equal to
   822      * the value of:
   823      *
   824      * <blockquote>
   825      *  {@code getLong(nm, null)}
   826      * </blockquote>
   827      *
   828      * @param   nm   property name.
   829      * @return  the {@code Long} value of the property.
   830      * @see     java.lang.System#getProperty(java.lang.String)
   831      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
   832      */
   833     public static Long getLong(String nm) {
   834         return getLong(nm, null);
   835     }
   836 
   837     /**
   838      * Determines the {@code long} value of the system property
   839      * with the specified name.
   840      *
   841      * <p>The first argument is treated as the name of a system property.
   842      * System properties are accessible through the {@link
   843      * java.lang.System#getProperty(java.lang.String)} method. The
   844      * string value of this property is then interpreted as a
   845      * {@code long} value and a {@code Long} object
   846      * representing this value is returned.  Details of possible
   847      * numeric formats can be found with the definition of
   848      * {@code getProperty}.
   849      *
   850      * <p>The second argument is the default value. A {@code Long} object
   851      * that represents the value of the second argument is returned if there
   852      * is no property of the specified name, if the property does not have
   853      * the correct numeric format, or if the specified name is empty or null.
   854      *
   855      * <p>In other words, this method returns a {@code Long} object equal
   856      * to the value of:
   857      *
   858      * <blockquote>
   859      *  {@code getLong(nm, new Long(val))}
   860      * </blockquote>
   861      *
   862      * but in practice it may be implemented in a manner such as:
   863      *
   864      * <blockquote><pre>
   865      * Long result = getLong(nm, null);
   866      * return (result == null) ? new Long(val) : result;
   867      * </pre></blockquote>
   868      *
   869      * to avoid the unnecessary allocation of a {@code Long} object when
   870      * the default value is not needed.
   871      *
   872      * @param   nm    property name.
   873      * @param   val   default value.
   874      * @return  the {@code Long} value of the property.
   875      * @see     java.lang.System#getProperty(java.lang.String)
   876      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
   877      */
   878     public static Long getLong(String nm, long val) {
   879         Long result = Long.getLong(nm, null);
   880         return (result == null) ? Long.valueOf(val) : result;
   881     }
   882 
   883     /**
   884      * Returns the {@code long} value of the system property with
   885      * the specified name.  The first argument is treated as the name
   886      * of a system property.  System properties are accessible through
   887      * the {@link java.lang.System#getProperty(java.lang.String)}
   888      * method. The string value of this property is then interpreted
   889      * as a {@code long} value, as per the
   890      * {@code Long.decode} method, and a {@code Long} object
   891      * representing this value is returned.
   892      *
   893      * <ul>
   894      * <li>If the property value begins with the two ASCII characters
   895      * {@code 0x} or the ASCII character {@code #}, not followed by
   896      * a minus sign, then the rest of it is parsed as a hexadecimal integer
   897      * exactly as for the method {@link #valueOf(java.lang.String, int)}
   898      * with radix 16.
   899      * <li>If the property value begins with the ASCII character
   900      * {@code 0} followed by another character, it is parsed as
   901      * an octal integer exactly as by the method {@link
   902      * #valueOf(java.lang.String, int)} with radix 8.
   903      * <li>Otherwise the property value is parsed as a decimal
   904      * integer exactly as by the method
   905      * {@link #valueOf(java.lang.String, int)} with radix 10.
   906      * </ul>
   907      *
   908      * <p>Note that, in every case, neither {@code L}
   909      * (<code>'&#92;u004C'</code>) nor {@code l}
   910      * (<code>'&#92;u006C'</code>) is permitted to appear at the end
   911      * of the property value as a type indicator, as would be
   912      * permitted in Java programming language source code.
   913      *
   914      * <p>The second argument is the default value. The default value is
   915      * returned if there is no property of the specified name, if the
   916      * property does not have the correct numeric format, or if the
   917      * specified name is empty or {@code null}.
   918      *
   919      * @param   nm   property name.
   920      * @param   val   default value.
   921      * @return  the {@code Long} value of the property.
   922      * @see     java.lang.System#getProperty(java.lang.String)
   923      * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
   924      * @see java.lang.Long#decode
   925      */
   926     public static Long getLong(String nm, Long val) {
   927         String v = null;
   928         try {
   929             v = AbstractStringBuilder.getProperty(nm);
   930         } catch (IllegalArgumentException e) {
   931         } catch (NullPointerException e) {
   932         }
   933         if (v != null) {
   934             try {
   935                 return Long.decode(v);
   936             } catch (NumberFormatException e) {
   937             }
   938         }
   939         return val;
   940     }
   941 
   942     /**
   943      * Compares two {@code Long} objects numerically.
   944      *
   945      * @param   anotherLong   the {@code Long} to be compared.
   946      * @return  the value {@code 0} if this {@code Long} is
   947      *          equal to the argument {@code Long}; a value less than
   948      *          {@code 0} if this {@code Long} is numerically less
   949      *          than the argument {@code Long}; and a value greater
   950      *          than {@code 0} if this {@code Long} is numerically
   951      *           greater than the argument {@code Long} (signed
   952      *           comparison).
   953      * @since   1.2
   954      */
   955     public int compareTo(Long anotherLong) {
   956         return compare(this.value, anotherLong.value);
   957     }
   958 
   959     /**
   960      * Compares two {@code long} values numerically.
   961      * The value returned is identical to what would be returned by:
   962      * <pre>
   963      *    Long.valueOf(x).compareTo(Long.valueOf(y))
   964      * </pre>
   965      *
   966      * @param  x the first {@code long} to compare
   967      * @param  y the second {@code long} to compare
   968      * @return the value {@code 0} if {@code x == y};
   969      *         a value less than {@code 0} if {@code x < y}; and
   970      *         a value greater than {@code 0} if {@code x > y}
   971      * @since 1.7
   972      */
   973     public static int compare(long x, long y) {
   974         return (x < y) ? -1 : ((x == y) ? 0 : 1);
   975     }
   976 
   977 
   978     // Bit Twiddling
   979 
   980     /**
   981      * The number of bits used to represent a {@code long} value in two's
   982      * complement binary form.
   983      *
   984      * @since 1.5
   985      */
   986     public static final int SIZE = 64;
   987 
   988     /**
   989      * Returns a {@code long} value with at most a single one-bit, in the
   990      * position of the highest-order ("leftmost") one-bit in the specified
   991      * {@code long} value.  Returns zero if the specified value has no
   992      * one-bits in its two's complement binary representation, that is, if it
   993      * is equal to zero.
   994      *
   995      * @return a {@code long} value with a single one-bit, in the position
   996      *     of the highest-order one-bit in the specified value, or zero if
   997      *     the specified value is itself equal to zero.
   998      * @since 1.5
   999      */
  1000     public static long highestOneBit(long i) {
  1001         // HD, Figure 3-1
  1002         i |= (i >>  1);
  1003         i |= (i >>  2);
  1004         i |= (i >>  4);
  1005         i |= (i >>  8);
  1006         i |= (i >> 16);
  1007         i |= (i >> 32);
  1008         return i - (i >>> 1);
  1009     }
  1010 
  1011     /**
  1012      * Returns a {@code long} value with at most a single one-bit, in the
  1013      * position of the lowest-order ("rightmost") one-bit in the specified
  1014      * {@code long} value.  Returns zero if the specified value has no
  1015      * one-bits in its two's complement binary representation, that is, if it
  1016      * is equal to zero.
  1017      *
  1018      * @return a {@code long} value with a single one-bit, in the position
  1019      *     of the lowest-order one-bit in the specified value, or zero if
  1020      *     the specified value is itself equal to zero.
  1021      * @since 1.5
  1022      */
  1023     public static long lowestOneBit(long i) {
  1024         // HD, Section 2-1
  1025         return i & -i;
  1026     }
  1027 
  1028     /**
  1029      * Returns the number of zero bits preceding the highest-order
  1030      * ("leftmost") one-bit in the two's complement binary representation
  1031      * of the specified {@code long} value.  Returns 64 if the
  1032      * specified value has no one-bits in its two's complement representation,
  1033      * in other words if it is equal to zero.
  1034      *
  1035      * <p>Note that this method is closely related to the logarithm base 2.
  1036      * For all positive {@code long} values x:
  1037      * <ul>
  1038      * <li>floor(log<sub>2</sub>(x)) = {@code 63 - numberOfLeadingZeros(x)}
  1039      * <li>ceil(log<sub>2</sub>(x)) = {@code 64 - numberOfLeadingZeros(x - 1)}
  1040      * </ul>
  1041      *
  1042      * @return the number of zero bits preceding the highest-order
  1043      *     ("leftmost") one-bit in the two's complement binary representation
  1044      *     of the specified {@code long} value, or 64 if the value
  1045      *     is equal to zero.
  1046      * @since 1.5
  1047      */
  1048     public static int numberOfLeadingZeros(long i) {
  1049         // HD, Figure 5-6
  1050          if (i == 0)
  1051             return 64;
  1052         int n = 1;
  1053         int x = (int)(i >>> 32);
  1054         if (x == 0) { n += 32; x = (int)i; }
  1055         if (x >>> 16 == 0) { n += 16; x <<= 16; }
  1056         if (x >>> 24 == 0) { n +=  8; x <<=  8; }
  1057         if (x >>> 28 == 0) { n +=  4; x <<=  4; }
  1058         if (x >>> 30 == 0) { n +=  2; x <<=  2; }
  1059         n -= x >>> 31;
  1060         return n;
  1061     }
  1062 
  1063     /**
  1064      * Returns the number of zero bits following the lowest-order ("rightmost")
  1065      * one-bit in the two's complement binary representation of the specified
  1066      * {@code long} value.  Returns 64 if the specified value has no
  1067      * one-bits in its two's complement representation, in other words if it is
  1068      * equal to zero.
  1069      *
  1070      * @return the number of zero bits following the lowest-order ("rightmost")
  1071      *     one-bit in the two's complement binary representation of the
  1072      *     specified {@code long} value, or 64 if the value is equal
  1073      *     to zero.
  1074      * @since 1.5
  1075      */
  1076     public static int numberOfTrailingZeros(long i) {
  1077         // HD, Figure 5-14
  1078         int x, y;
  1079         if (i == 0) return 64;
  1080         int n = 63;
  1081         y = (int)i; if (y != 0) { n = n -32; x = y; } else x = (int)(i>>>32);
  1082         y = x <<16; if (y != 0) { n = n -16; x = y; }
  1083         y = x << 8; if (y != 0) { n = n - 8; x = y; }
  1084         y = x << 4; if (y != 0) { n = n - 4; x = y; }
  1085         y = x << 2; if (y != 0) { n = n - 2; x = y; }
  1086         return n - ((x << 1) >>> 31);
  1087     }
  1088 
  1089     /**
  1090      * Returns the number of one-bits in the two's complement binary
  1091      * representation of the specified {@code long} value.  This function is
  1092      * sometimes referred to as the <i>population count</i>.
  1093      *
  1094      * @return the number of one-bits in the two's complement binary
  1095      *     representation of the specified {@code long} value.
  1096      * @since 1.5
  1097      */
  1098      public static int bitCount(long i) {
  1099         // HD, Figure 5-14
  1100         i = i - ((i >>> 1) & 0x5555555555555555L);
  1101         i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L);
  1102         i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL;
  1103         i = i + (i >>> 8);
  1104         i = i + (i >>> 16);
  1105         i = i + (i >>> 32);
  1106         return (int)i & 0x7f;
  1107      }
  1108 
  1109     /**
  1110      * Returns the value obtained by rotating the two's complement binary
  1111      * representation of the specified {@code long} value left by the
  1112      * specified number of bits.  (Bits shifted out of the left hand, or
  1113      * high-order, side reenter on the right, or low-order.)
  1114      *
  1115      * <p>Note that left rotation with a negative distance is equivalent to
  1116      * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
  1117      * distance)}.  Note also that rotation by any multiple of 64 is a
  1118      * no-op, so all but the last six bits of the rotation distance can be
  1119      * ignored, even if the distance is negative: {@code rotateLeft(val,
  1120      * distance) == rotateLeft(val, distance & 0x3F)}.
  1121      *
  1122      * @return the value obtained by rotating the two's complement binary
  1123      *     representation of the specified {@code long} value left by the
  1124      *     specified number of bits.
  1125      * @since 1.5
  1126      */
  1127     public static long rotateLeft(long i, int distance) {
  1128         return (i << distance) | (i >>> -distance);
  1129     }
  1130 
  1131     /**
  1132      * Returns the value obtained by rotating the two's complement binary
  1133      * representation of the specified {@code long} value right by the
  1134      * specified number of bits.  (Bits shifted out of the right hand, or
  1135      * low-order, side reenter on the left, or high-order.)
  1136      *
  1137      * <p>Note that right rotation with a negative distance is equivalent to
  1138      * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
  1139      * distance)}.  Note also that rotation by any multiple of 64 is a
  1140      * no-op, so all but the last six bits of the rotation distance can be
  1141      * ignored, even if the distance is negative: {@code rotateRight(val,
  1142      * distance) == rotateRight(val, distance & 0x3F)}.
  1143      *
  1144      * @return the value obtained by rotating the two's complement binary
  1145      *     representation of the specified {@code long} value right by the
  1146      *     specified number of bits.
  1147      * @since 1.5
  1148      */
  1149     public static long rotateRight(long i, int distance) {
  1150         return (i >>> distance) | (i << -distance);
  1151     }
  1152 
  1153     /**
  1154      * Returns the value obtained by reversing the order of the bits in the
  1155      * two's complement binary representation of the specified {@code long}
  1156      * value.
  1157      *
  1158      * @return the value obtained by reversing order of the bits in the
  1159      *     specified {@code long} value.
  1160      * @since 1.5
  1161      */
  1162     public static long reverse(long i) {
  1163         // HD, Figure 7-1
  1164         i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L;
  1165         i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L;
  1166         i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL;
  1167         i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
  1168         i = (i << 48) | ((i & 0xffff0000L) << 16) |
  1169             ((i >>> 16) & 0xffff0000L) | (i >>> 48);
  1170         return i;
  1171     }
  1172 
  1173     /**
  1174      * Returns the signum function of the specified {@code long} value.  (The
  1175      * return value is -1 if the specified value is negative; 0 if the
  1176      * specified value is zero; and 1 if the specified value is positive.)
  1177      *
  1178      * @return the signum function of the specified {@code long} value.
  1179      * @since 1.5
  1180      */
  1181     public static int signum(long i) {
  1182         // HD, Section 2-7
  1183         return (int) ((i >> 63) | (-i >>> 63));
  1184     }
  1185 
  1186     /**
  1187      * Returns the value obtained by reversing the order of the bytes in the
  1188      * two's complement representation of the specified {@code long} value.
  1189      *
  1190      * @return the value obtained by reversing the bytes in the specified
  1191      *     {@code long} value.
  1192      * @since 1.5
  1193      */
  1194     public static long reverseBytes(long i) {
  1195         i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
  1196         return (i << 48) | ((i & 0xffff0000L) << 16) |
  1197             ((i >>> 16) & 0xffff0000L) | (i >>> 48);
  1198     }
  1199 
  1200     /** use serialVersionUID from JDK 1.0.2 for interoperability */
  1201     private static final long serialVersionUID = 4290774380558885855L;
  1202 }