1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17
18package java.lang;
19
20/**
21 * The wrapper for the primitive type {@code long}.
22 * <p>
23 * Implementation note: The "bit twiddling" methods in this class use techniques
24 * described in <a href="http://www.hackersdelight.org/">Henry S. Warren,
25 * Jr.'s Hacker's Delight, (Addison Wesley, 2002)</a> and <a href=
26 * "http://graphics.stanford.edu/~seander/bithacks.html">Sean Anderson's
27 * Bit Twiddling Hacks.</a>
28 *
29 * @see java.lang.Integer
30 * @since 1.0
31 */
32@FindBugsSuppressWarnings("DM_NUMBER_CTOR")
33public final class Long extends Number implements Comparable<Long> {
34
35    private static final long serialVersionUID = 4290774380558885855L;
36
37    /**
38     * The value which the receiver represents.
39     */
40    private final long value;
41
42    /**
43     * Constant for the maximum {@code long} value, 2<sup>63</sup>-1.
44     */
45    public static final long MAX_VALUE = 0x7FFFFFFFFFFFFFFFL;
46
47    /**
48     * Constant for the minimum {@code long} value, -2<sup>63</sup>.
49     */
50    public static final long MIN_VALUE = 0x8000000000000000L;
51
52    /**
53     * The {@link Class} object that represents the primitive type {@code long}.
54     */
55    @SuppressWarnings("unchecked")
56    public static final Class<Long> TYPE
57            = (Class<Long>) long[].class.getComponentType();
58    // Note: Long.TYPE can't be set to "long.class", since *that* is
59    // defined to be "java.lang.Long.TYPE";
60
61    /**
62     * Constant for the number of bits needed to represent a {@code long} in
63     * two's complement form.
64     *
65     * @since 1.5
66     */
67    public static final int SIZE = 64;
68
69    /**
70     * Constructs a new {@code Long} with the specified primitive long value.
71     *
72     * @param value
73     *            the primitive long value to store in the new instance.
74     */
75    public Long(long value) {
76        this.value = value;
77    }
78
79    /**
80     * Constructs a new {@code Long} from the specified string.
81     *
82     * @param string
83     *            the string representation of a long value.
84     * @throws NumberFormatException
85     *             if {@code string} cannot be parsed as a long value.
86     * @see #parseLong(String)
87     */
88    public Long(String string) throws NumberFormatException {
89        this(parseLong(string));
90    }
91
92    @Override
93    public byte byteValue() {
94        return (byte) value;
95    }
96
97    /**
98     * Compares this object to the specified long object to determine their
99     * relative order.
100     *
101     * @param object
102     *            the long object to compare this object to.
103     * @return a negative value if the value of this long is less than the value
104     *         of {@code object}; 0 if the value of this long and the value of
105     *         {@code object} are equal; a positive value if the value of this
106     *         long is greater than the value of {@code object}.
107     * @see java.lang.Comparable
108     * @since 1.2
109     */
110    public int compareTo(Long object) {
111        return compare(value, object.value);
112    }
113
114    /**
115     * Compares two {@code long} values.
116     * @return 0 if lhs = rhs, less than 0 if lhs &lt; rhs, and greater than 0 if lhs &gt; rhs.
117     * @since 1.7
118     * @hide 1.7
119     */
120    public static int compare(long lhs, long rhs) {
121        return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1);
122    }
123
124    private static NumberFormatException invalidLong(String s) {
125        throw new NumberFormatException("Invalid long: \"" + s + "\"");
126    }
127
128    /**
129     * Parses the specified string and returns a {@code Long} instance if the
130     * string can be decoded into a long value. The string may be an optional
131     * minus sign "-" followed by a hexadecimal ("0x..." or "#..."), octal
132     * ("0..."), or decimal ("...") representation of a long.
133     *
134     * @param string
135     *            a string representation of a long value.
136     * @return a {@code Long} containing the value represented by {@code string}.
137     * @throws NumberFormatException
138     *             if {@code string} cannot be parsed as a long value.
139     */
140    public static Long decode(String string) throws NumberFormatException {
141        int length = string.length(), i = 0;
142        if (length == 0) {
143            throw invalidLong(string);
144        }
145        char firstDigit = string.charAt(i);
146        boolean negative = firstDigit == '-';
147        if (negative) {
148            if (length == 1) {
149                throw invalidLong(string);
150            }
151            firstDigit = string.charAt(++i);
152        }
153
154        int base = 10;
155        if (firstDigit == '0') {
156            if (++i == length) {
157                return valueOf(0L);
158            }
159            if ((firstDigit = string.charAt(i)) == 'x' || firstDigit == 'X') {
160                if (i == length) {
161                    throw invalidLong(string);
162                }
163                i++;
164                base = 16;
165            } else {
166                base = 8;
167            }
168        } else if (firstDigit == '#') {
169            if (i == length) {
170                throw invalidLong(string);
171            }
172            i++;
173            base = 16;
174        }
175
176        long result = parse(string, i, base, negative);
177        return valueOf(result);
178    }
179
180    @Override
181    public double doubleValue() {
182        return value;
183    }
184
185    /**
186     * Compares this instance with the specified object and indicates if they
187     * are equal. In order to be equal, {@code o} must be an instance of
188     * {@code Long} and have the same long value as this object.
189     *
190     * @param o
191     *            the object to compare this long with.
192     * @return {@code true} if the specified object is equal to this
193     *         {@code Long}; {@code false} otherwise.
194     */
195    @Override
196    public boolean equals(Object o) {
197        return (o instanceof Long) && (((Long) o).value == value);
198    }
199
200    @Override
201    public float floatValue() {
202        return value;
203    }
204
205    /**
206     * Returns the {@code Long} value of the system property identified by
207     * {@code string}. Returns {@code null} if {@code string} is {@code null}
208     * or empty, if the property can not be found or if its value can not be
209     * parsed as a long.
210     *
211     * @param string
212     *            the name of the requested system property.
213     * @return the requested property's value as a {@code Long} or {@code null}.
214     */
215    public static Long getLong(String string) {
216        if (string == null || string.length() == 0) {
217            return null;
218        }
219        String prop = System.getProperty(string);
220        if (prop == null) {
221            return null;
222        }
223        try {
224            return decode(prop);
225        } catch (NumberFormatException ex) {
226            return null;
227        }
228    }
229
230    /**
231     * Returns the {@code Long} value of the system property identified by
232     * {@code string}. Returns the specified default value if {@code string} is
233     * {@code null} or empty, if the property can not be found or if its value
234     * can not be parsed as a long.
235     *
236     * @param string
237     *            the name of the requested system property.
238     * @param defaultValue
239     *            the default value that is returned if there is no long system
240     *            property with the requested name.
241     * @return the requested property's value as a {@code Long} or the default
242     *         value.
243     */
244    public static Long getLong(String string, long defaultValue) {
245        if (string == null || string.length() == 0) {
246            return valueOf(defaultValue);
247        }
248        String prop = System.getProperty(string);
249        if (prop == null) {
250            return valueOf(defaultValue);
251        }
252        try {
253            return decode(prop);
254        } catch (NumberFormatException ex) {
255            return valueOf(defaultValue);
256        }
257    }
258
259    /**
260     * Returns the {@code Long} value of the system property identified by
261     * {@code string}. Returns the specified default value if {@code string} is
262     * {@code null} or empty, if the property can not be found or if its value
263     * can not be parsed as a long.
264     *
265     * @param string
266     *            the name of the requested system property.
267     * @param defaultValue
268     *            the default value that is returned if there is no long system
269     *            property with the requested name.
270     * @return the requested property's value as a {@code Long} or the default
271     *         value.
272     */
273    public static Long getLong(String string, Long defaultValue) {
274        if (string == null || string.length() == 0) {
275            return defaultValue;
276        }
277        String prop = System.getProperty(string);
278        if (prop == null) {
279            return defaultValue;
280        }
281        try {
282            return decode(prop);
283        } catch (NumberFormatException ex) {
284            return defaultValue;
285        }
286    }
287
288    @Override
289    public int hashCode() {
290        return (int) (value ^ (value >>> 32));
291    }
292
293    @Override
294    public int intValue() {
295        return (int) value;
296    }
297
298    /**
299     * Gets the primitive value of this long.
300     *
301     * @return this object's primitive value.
302     */
303    @Override
304    public long longValue() {
305        return value;
306    }
307
308    /**
309     * Parses the specified string as a signed decimal long value. The ASCII
310     * character \u002d ('-') is recognized as the minus sign.
311     *
312     * @param string
313     *            the string representation of a long value.
314     * @return the primitive long value represented by {@code string}.
315     * @throws NumberFormatException
316     *             if {@code string} cannot be parsed as a long value.
317     */
318    public static long parseLong(String string) throws NumberFormatException {
319        return parseLong(string, 10);
320    }
321
322    /**
323     * Parses the specified string as a signed long value using the specified
324     * radix. The ASCII character \u002d ('-') is recognized as the minus sign.
325     *
326     * @param string
327     *            the string representation of a long value.
328     * @param radix
329     *            the radix to use when parsing.
330     * @return the primitive long value represented by {@code string} using
331     *         {@code radix}.
332     * @throws NumberFormatException
333     *             if {@code string} cannot be parsed as a long value, or
334     *             {@code radix < Character.MIN_RADIX ||
335     *             radix > Character.MAX_RADIX}.
336     */
337    public static long parseLong(String string, int radix) throws NumberFormatException {
338        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
339            throw new NumberFormatException("Invalid radix: " + radix);
340        }
341        if (string == null) {
342            throw invalidLong(string);
343        }
344        int length = string.length(), i = 0;
345        if (length == 0) {
346            throw invalidLong(string);
347        }
348        boolean negative = string.charAt(i) == '-';
349        if (negative && ++i == length) {
350            throw invalidLong(string);
351        }
352
353        return parse(string, i, radix, negative);
354    }
355
356    private static long parse(String string, int offset, int radix, boolean negative) {
357        long max = Long.MIN_VALUE / radix;
358        long result = 0, length = string.length();
359        while (offset < length) {
360            int digit = Character.digit(string.charAt(offset++), radix);
361            if (digit == -1) {
362                throw invalidLong(string);
363            }
364            if (max > result) {
365                throw invalidLong(string);
366            }
367            long next = result * radix - digit;
368            if (next > result) {
369                throw invalidLong(string);
370            }
371            result = next;
372        }
373        if (!negative) {
374            result = -result;
375            if (result < 0) {
376                throw invalidLong(string);
377            }
378        }
379        return result;
380    }
381
382    @Override
383    public short shortValue() {
384        return (short) value;
385    }
386
387    /**
388     * Converts the specified long value into its binary string representation.
389     * The returned string is a concatenation of '0' and '1' characters.
390     *
391     * @param v
392     *            the long value to convert.
393     * @return the binary string representation of {@code v}.
394     */
395    public static String toBinaryString(long v) {
396        return IntegralToString.longToBinaryString(v);
397    }
398
399    /**
400     * Converts the specified long value into its hexadecimal string
401     * representation. The returned string is a concatenation of characters from
402     * '0' to '9' and 'a' to 'f'.
403     *
404     * @param v
405     *            the long value to convert.
406     * @return the hexadecimal string representation of {@code l}.
407     */
408    public static String toHexString(long v) {
409        return IntegralToString.longToHexString(v);
410    }
411
412    /**
413     * Converts the specified long value into its octal string representation.
414     * The returned string is a concatenation of characters from '0' to '7'.
415     *
416     * @param v
417     *            the long value to convert.
418     * @return the octal string representation of {@code l}.
419     */
420    public static String toOctalString(long v) {
421        return IntegralToString.longToOctalString(v);
422    }
423
424    @Override
425    public String toString() {
426        return Long.toString(value);
427    }
428
429    /**
430     * Converts the specified long value into its decimal string representation.
431     * The returned string is a concatenation of a minus sign if the number is
432     * negative and characters from '0' to '9'.
433     *
434     * @param n
435     *            the long to convert.
436     * @return the decimal string representation of {@code l}.
437     */
438    public static String toString(long n) {
439        return IntegralToString.longToString(n);
440    }
441
442    /**
443     * Converts the specified signed long value into a string representation based on
444     * the specified radix. The returned string is a concatenation of a minus
445     * sign if the number is negative and characters from '0' to '9' and 'a' to
446     * 'z', depending on the radix. If {@code radix} is not in the interval
447     * defined by {@code Character.MIN_RADIX} and {@code Character.MAX_RADIX}
448     * then 10 is used as the base for the conversion.
449     *
450     * <p>This method treats its argument as signed. If you want to convert an
451     * unsigned value to one of the common non-decimal bases, you may find
452     * {@link #toBinaryString}, {@code #toHexString}, or {@link #toOctalString}
453     * more convenient.
454     *
455     * @param v
456     *            the signed long to convert.
457     * @param radix
458     *            the base to use for the conversion.
459     * @return the string representation of {@code v}.
460     */
461    public static String toString(long v, int radix) {
462        return IntegralToString.longToString(v, radix);
463    }
464
465    /**
466     * Parses the specified string as a signed decimal long value.
467     *
468     * @param string
469     *            the string representation of a long value.
470     * @return a {@code Long} instance containing the long value represented by
471     *         {@code string}.
472     * @throws NumberFormatException
473     *             if {@code string} cannot be parsed as a long value.
474     * @see #parseLong(String)
475     */
476    public static Long valueOf(String string) throws NumberFormatException {
477        return valueOf(parseLong(string));
478    }
479
480    /**
481     * Parses the specified string as a signed long value using the specified
482     * radix.
483     *
484     * @param string
485     *            the string representation of a long value.
486     * @param radix
487     *            the radix to use when parsing.
488     * @return a {@code Long} instance containing the long value represented by
489     *         {@code string} using {@code radix}.
490     * @throws NumberFormatException
491     *             if {@code string} cannot be parsed as a long value, or
492     *             {@code radix < Character.MIN_RADIX ||
493     *             radix > Character.MAX_RADIX}.
494     * @see #parseLong(String, int)
495     */
496    public static Long valueOf(String string, int radix) throws NumberFormatException {
497        return valueOf(parseLong(string, radix));
498    }
499
500    /**
501     * Determines the highest (leftmost) bit of the specified long value that is
502     * 1 and returns the bit mask value for that bit. This is also referred to
503     * as the Most Significant 1 Bit. Returns zero if the specified long is
504     * zero.
505     *
506     * @param v
507     *            the long to examine.
508     * @return the bit mask indicating the highest 1 bit in {@code v}.
509     * @since 1.5
510     */
511    public static long highestOneBit(long v) {
512        // Hacker's Delight, Figure 3-1
513        v |= (v >> 1);
514        v |= (v >> 2);
515        v |= (v >> 4);
516        v |= (v >> 8);
517        v |= (v >> 16);
518        v |= (v >> 32);
519        return v - (v >>> 1);
520    }
521
522    /**
523     * Determines the lowest (rightmost) bit of the specified long value that is
524     * 1 and returns the bit mask value for that bit. This is also referred to
525     * as the Least Significant 1 Bit. Returns zero if the specified long is
526     * zero.
527     *
528     * @param v
529     *            the long to examine.
530     * @return the bit mask indicating the lowest 1 bit in {@code v}.
531     * @since 1.5
532     */
533    public static long lowestOneBit(long v) {
534        return v & -v;
535    }
536
537    /**
538     * Determines the number of leading zeros in the specified long value prior
539     * to the {@link #highestOneBit(long) highest one bit}.
540     *
541     * @param v
542     *            the long to examine.
543     * @return the number of leading zeros in {@code v}.
544     * @since 1.5
545     */
546    public static int numberOfLeadingZeros(long v) {
547        // After Hacker's Delight, Figure 5-6
548        if (v < 0) {
549            return 0;
550        }
551        if (v == 0) {
552            return 64;
553        }
554        // On a 64-bit VM, the two previous tests should probably be replaced by
555        // if (v <= 0) return ((int) (~v >> 57)) & 64;
556
557        int n = 1;
558        int i = (int) (v >>> 32);
559        if (i == 0) {
560            n +=  32;
561            i = (int) v;
562        }
563        if (i >>> 16 == 0) {
564            n +=  16;
565            i <<= 16;
566        }
567        if (i >>> 24 == 0) {
568            n +=  8;
569            i <<= 8;
570        }
571        if (i >>> 28 == 0) {
572            n +=  4;
573            i <<= 4;
574        }
575        if (i >>> 30 == 0) {
576            n +=  2;
577            i <<= 2;
578        }
579        return n - (i >>> 31);
580    }
581
582    /**
583     * Determines the number of trailing zeros in the specified long value after
584     * the {@link #lowestOneBit(long) lowest one bit}.
585     *
586     * @param v
587     *            the long to examine.
588     * @return the number of trailing zeros in {@code v}.
589     * @since 1.5
590     */
591    public static int numberOfTrailingZeros(long v) {
592        int low = (int) v;
593        return low !=0 ? Integer.numberOfTrailingZeros(low)
594                       : 32 + Integer.numberOfTrailingZeros((int) (v >>> 32));
595    }
596
597    /**
598     * Counts the number of 1 bits in the specified long value; this is also
599     * referred to as population count.
600     *
601     * @param v
602     *            the long to examine.
603     * @return the number of 1 bits in {@code v}.
604     * @since 1.5
605     */
606    public static int bitCount(long v) {
607        // Combines techniques from several sources
608        v -=  (v >>> 1) & 0x5555555555555555L;
609        v = (v & 0x3333333333333333L) + ((v >>> 2) & 0x3333333333333333L);
610        int i =  ((int)(v >>> 32)) + (int) v;
611        i = (i & 0x0F0F0F0F) + ((i >>> 4) & 0x0F0F0F0F);
612        i += i >>> 8;
613        i += i >>> 16;
614        return i  & 0x0000007F;
615    }
616
617    /*
618     * On a modern 64-bit processor with a fast hardware multiply, this is
619     * much faster (assuming you're running a 64-bit VM):
620     *
621     * // http://chessprogramming.wikispaces.com/Population+Count
622     * int bitCount (long x) {
623     *     x -=  (x >>> 1) & 0x5555555555555555L;
624     *     x = (x & 0x3333333333333333L) + ((x >>> 2) & 0x3333333333333333L);
625     *     x = (x + (x >>> 4)) & 0x0f0f0f0f0f0f0f0fL;
626     *     x = (x * 0x0101010101010101L) >>> 56;
627     *     return (int) x;
628     * }
629     *
630     * Really modern processors (e.g., Nehalem, K-10) have hardware popcount
631     * instructions.
632     */
633
634    /**
635     * Rotates the bits of the specified long value to the left by the specified
636     * number of bits.
637     *
638     * @param v
639     *            the long value to rotate left.
640     * @param distance
641     *            the number of bits to rotate.
642     * @return the rotated value.
643     * @since 1.5
644     */
645    public static long rotateLeft(long v, int distance) {
646        // Shift distances are mod 64 (JLS3 15.19), so we needn't mask -distance
647        return (v << distance) | (v >>> -distance);
648    }
649
650    /**
651     * Rotates the bits of the specified long value to the right by the
652     * specified number of bits.
653     *
654     * @param v
655     *            the long value to rotate right.
656     * @param distance
657     *            the number of bits to rotate.
658     * @return the rotated value.
659     * @since 1.5
660     */
661    public static long rotateRight(long v, int distance) {
662        // Shift distances are mod 64 (JLS3 15.19), so we needn't mask -distance
663        return (v >>> distance) | (v << -distance);
664    }
665
666    /**
667     * Reverses the order of the bytes of the specified long value.
668     *
669     * @param v
670     *            the long value for which to reverse the byte order.
671     * @return the reversed value.
672     * @since 1.5
673     */
674    public static long reverseBytes(long v) {
675        // Hacker's Delight 7-1, with minor tweak from Veldmeijer
676        // http://graphics.stanford.edu/~seander/bithacks.html
677        v = ((v >>> 8) & 0x00FF00FF00FF00FFL) | ((v & 0x00FF00FF00FF00FFL) << 8);
678        v = ((v >>>16) & 0x0000FFFF0000FFFFL) | ((v & 0x0000FFFF0000FFFFL) <<16);
679        return ((v >>>32)                   ) | ((v                      ) <<32);
680    }
681
682    /**
683     * Reverses the order of the bits of the specified long value.
684     *
685     * @param v
686     *            the long value for which to reverse the bit order.
687     * @return the reversed value.
688     * @since 1.5
689     */
690    public static long reverse(long v) {
691        // Hacker's Delight 7-1, with minor tweak from Veldmeijer
692        // http://graphics.stanford.edu/~seander/bithacks.html
693        v = ((v >>> 1) & 0x5555555555555555L) | ((v & 0x5555555555555555L) << 1);
694        v = ((v >>> 2) & 0x3333333333333333L) | ((v & 0x3333333333333333L) << 2);
695        v = ((v >>> 4) & 0x0F0F0F0F0F0F0F0FL) | ((v & 0x0F0F0F0F0F0F0F0FL) << 4);
696        v = ((v >>> 8) & 0x00FF00FF00FF00FFL) | ((v & 0x00FF00FF00FF00FFL) << 8);
697        v = ((v >>>16) & 0x0000FFFF0000FFFFL) | ((v & 0x0000FFFF0000FFFFL) <<16);
698        return ((v >>>32)                   ) | ((v                      ) <<32);
699    }
700
701    /**
702     * Returns the value of the {@code signum} function for the specified long
703     * value.
704     *
705     * @param v
706     *            the long value to check.
707     * @return -1 if {@code v} is negative, 1 if {@code v} is positive, 0 if
708     *         {@code v} is zero.
709     * @since 1.5
710     */
711    public static int signum(long v) {
712        return v < 0 ? -1 : (v == 0 ? 0 : 1);
713    }
714
715    /**
716     * Returns a {@code Long} instance for the specified long value.
717     * <p>
718     * If it is not necessary to get a new {@code Long} instance, it is
719     * recommended to use this method instead of the constructor, since it
720     * maintains a cache of instances which may result in better performance.
721     *
722     * @param v
723     *            the long value to store in the instance.
724     * @return a {@code Long} instance containing {@code v}.
725     * @since 1.5
726     */
727    public static Long valueOf(long v) {
728        return  v >= 128 || v < -128 ? new Long(v) : SMALL_VALUES[((int) v) + 128];
729    }
730
731    /**
732     * A cache of instances used by {@link Long#valueOf(long)} and auto-boxing.
733     */
734    private static final Long[] SMALL_VALUES = new Long[256];
735
736    static {
737        for (int i = -128; i < 128; i++) {
738            SMALL_VALUES[i + 128] = new Long(i);
739        }
740    }
741}
742