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     */
119    public static int compare(long lhs, long rhs) {
120        return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1);
121    }
122
123    private static NumberFormatException invalidLong(String s) {
124        throw new NumberFormatException("Invalid long: \"" + s + "\"");
125    }
126
127    /**
128     * Parses the specified string and returns a {@code Long} instance if the
129     * string can be decoded into a long value. The string may be an optional
130     * optional sign character ("-" or "+") followed by a hexadecimal ("0x..."
131     * or "#..."), octal ("0..."), or decimal ("...") representation of a long.
132     *
133     * @param string
134     *            a string representation of a long value.
135     * @return a {@code Long} containing the value represented by {@code string}.
136     * @throws NumberFormatException
137     *             if {@code string} cannot be parsed as a long value.
138     */
139    public static Long decode(String string) throws NumberFormatException {
140        int length = string.length();
141        if (length == 0) {
142            throw invalidLong(string);
143        }
144
145        int i = 0;
146        char firstDigit = string.charAt(i);
147        boolean negative = firstDigit == '-';
148        if (negative || firstDigit == '+') {
149            if (length == 1) {
150                throw invalidLong(string);
151            }
152            firstDigit = string.charAt(++i);
153        }
154
155        int base = 10;
156        if (firstDigit == '0') {
157            if (++i == length) {
158                return valueOf(0L);
159            }
160            if ((firstDigit = string.charAt(i)) == 'x' || firstDigit == 'X') {
161                if (i == length) {
162                    throw invalidLong(string);
163                }
164                i++;
165                base = 16;
166            } else {
167                base = 8;
168            }
169        } else if (firstDigit == '#') {
170            if (i == length) {
171                throw invalidLong(string);
172            }
173            i++;
174            base = 16;
175        }
176
177        long result = parse(string, i, base, negative);
178        return valueOf(result);
179    }
180
181    @Override
182    public double doubleValue() {
183        return value;
184    }
185
186    /**
187     * Compares this instance with the specified object and indicates if they
188     * are equal. In order to be equal, {@code o} must be an instance of
189     * {@code Long} and have the same long value as this object.
190     *
191     * @param o
192     *            the object to compare this long with.
193     * @return {@code true} if the specified object is equal to this
194     *         {@code Long}; {@code false} otherwise.
195     */
196    @Override
197    public boolean equals(Object o) {
198        return (o instanceof Long) && (((Long) o).value == value);
199    }
200
201    @Override
202    public float floatValue() {
203        return value;
204    }
205
206    /**
207     * Returns the {@code Long} value of the system property identified by
208     * {@code string}. Returns {@code null} if {@code string} is {@code null}
209     * or empty, if the property can not be found or if its value can not be
210     * parsed as a long.
211     *
212     * @param string
213     *            the name of the requested system property.
214     * @return the requested property's value as a {@code Long} or {@code null}.
215     */
216    public static Long getLong(String string) {
217        if (string == null || string.length() == 0) {
218            return null;
219        }
220        String prop = System.getProperty(string);
221        if (prop == null) {
222            return null;
223        }
224        try {
225            return decode(prop);
226        } catch (NumberFormatException ex) {
227            return null;
228        }
229    }
230
231    /**
232     * Returns the {@code Long} value of the system property identified by
233     * {@code string}. Returns the specified default value if {@code string} is
234     * {@code null} or empty, if the property can not be found or if its value
235     * can not be parsed as a long.
236     *
237     * @param string
238     *            the name of the requested system property.
239     * @param defaultValue
240     *            the default value that is returned if there is no long system
241     *            property with the requested name.
242     * @return the requested property's value as a {@code Long} or the default
243     *         value.
244     */
245    public static Long getLong(String string, long defaultValue) {
246        if (string == null || string.length() == 0) {
247            return valueOf(defaultValue);
248        }
249        String prop = System.getProperty(string);
250        if (prop == null) {
251            return valueOf(defaultValue);
252        }
253        try {
254            return decode(prop);
255        } catch (NumberFormatException ex) {
256            return valueOf(defaultValue);
257        }
258    }
259
260    /**
261     * Returns the {@code Long} value of the system property identified by
262     * {@code string}. Returns the specified default value if {@code string} is
263     * {@code null} or empty, if the property can not be found or if its value
264     * can not be parsed as a long.
265     *
266     * @param string
267     *            the name of the requested system property.
268     * @param defaultValue
269     *            the default value that is returned if there is no long system
270     *            property with the requested name.
271     * @return the requested property's value as a {@code Long} or the default
272     *         value.
273     */
274    public static Long getLong(String string, Long defaultValue) {
275        if (string == null || string.length() == 0) {
276            return defaultValue;
277        }
278        String prop = System.getProperty(string);
279        if (prop == null) {
280            return defaultValue;
281        }
282        try {
283            return decode(prop);
284        } catch (NumberFormatException ex) {
285            return defaultValue;
286        }
287    }
288
289    @Override
290    public int hashCode() {
291        return (int) (value ^ (value >>> 32));
292    }
293
294    @Override
295    public int intValue() {
296        return (int) value;
297    }
298
299    /**
300     * Gets the primitive value of this long.
301     *
302     * @return this object's primitive value.
303     */
304    @Override
305    public long longValue() {
306        return value;
307    }
308
309    /**
310     * Parses the specified string as a signed decimal long value. The ASCII
311     * characters \u002d ('-') and \u002b ('+') are recognized as the minus and
312     * plus signs.
313     *
314     * @param string
315     *            the string representation of a long value.
316     * @return the primitive long value represented by {@code string}.
317     * @throws NumberFormatException
318     *             if {@code string} cannot be parsed as a long value.
319     */
320    public static long parseLong(String string) throws NumberFormatException {
321        return parseLong(string, 10);
322    }
323
324    /**
325     * Parses the specified string as a signed long value using the specified
326     * radix. The ASCII characters \u002d ('-') and \u002b ('+') are recognized
327     * as the minus and plus signs.
328     *
329     * @param string
330     *            the string representation of a long value.
331     * @param radix
332     *            the radix to use when parsing.
333     * @return the primitive long value represented by {@code string} using
334     *         {@code radix}.
335     * @throws NumberFormatException
336     *             if {@code string} cannot be parsed as a long value, or
337     *             {@code radix < Character.MIN_RADIX ||
338     *             radix > Character.MAX_RADIX}.
339     */
340    public static long parseLong(String string, int radix) throws NumberFormatException {
341        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
342            throw new NumberFormatException("Invalid radix: " + radix);
343        }
344        if (string == null || string.isEmpty()) {
345            throw invalidLong(string);
346        }
347        char firstChar = string.charAt(0);
348        int firstDigitIndex = (firstChar == '-' || firstChar == '+') ? 1 : 0;
349        if (firstDigitIndex == string.length()) {
350            throw invalidLong(string);
351        }
352
353        return parse(string, firstDigitIndex, radix, firstChar == '-');
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;
359        int length = string.length();
360        while (offset < length) {
361            int digit = Character.digit(string.charAt(offset++), radix);
362            if (digit == -1) {
363                throw invalidLong(string);
364            }
365            if (max > result) {
366                throw invalidLong(string);
367            }
368            long next = result * radix - digit;
369            if (next > result) {
370                throw invalidLong(string);
371            }
372            result = next;
373        }
374        if (!negative) {
375            result = -result;
376            if (result < 0) {
377                throw invalidLong(string);
378            }
379        }
380        return result;
381    }
382
383    /**
384     * Equivalent to {@code parsePositiveLong(string, 10)}.
385     *
386     * @see #parsePositiveLong(String, int)
387     *
388     * @hide
389     */
390    public static long parsePositiveLong(String string) throws NumberFormatException {
391        return parsePositiveLong(string, 10);
392    }
393
394    /**
395     * Parses the specified string as a positive long value using the
396     * specified radix. 0 is considered a positive long.
397     * <p>
398     * This method behaves the same as {@link #parseLong(String, int)} except
399     * that it disallows leading '+' and '-' characters. See that method for
400     * error conditions.
401     *
402     * @see #parseLong(String, int)
403     *
404     * @hide
405     */
406    public static long parsePositiveLong(String string, int radix) throws NumberFormatException {
407        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
408            throw new NumberFormatException("Invalid radix: " + radix);
409        }
410        if (string == null || string.length() == 0) {
411            throw invalidLong(string);
412        }
413        return parse(string, 0, radix, false);
414    }
415
416    @Override
417    public short shortValue() {
418        return (short) value;
419    }
420
421    /**
422     * Converts the specified long value into its binary string representation.
423     * The returned string is a concatenation of '0' and '1' characters.
424     *
425     * @param v
426     *            the long value to convert.
427     * @return the binary string representation of {@code v}.
428     */
429    public static String toBinaryString(long v) {
430        return IntegralToString.longToBinaryString(v);
431    }
432
433    /**
434     * Converts the specified long value into its hexadecimal string
435     * representation. The returned string is a concatenation of characters from
436     * '0' to '9' and 'a' to 'f'.
437     *
438     * @param v
439     *            the long value to convert.
440     * @return the hexadecimal string representation of {@code l}.
441     */
442    public static String toHexString(long v) {
443        return IntegralToString.longToHexString(v);
444    }
445
446    /**
447     * Converts the specified long value into its octal string representation.
448     * The returned string is a concatenation of characters from '0' to '7'.
449     *
450     * @param v
451     *            the long value to convert.
452     * @return the octal string representation of {@code l}.
453     */
454    public static String toOctalString(long v) {
455        return IntegralToString.longToOctalString(v);
456    }
457
458    @Override
459    public String toString() {
460        return Long.toString(value);
461    }
462
463    /**
464     * Converts the specified long value into its decimal string representation.
465     * The returned string is a concatenation of a minus sign if the number is
466     * negative and characters from '0' to '9'.
467     *
468     * @param n
469     *            the long to convert.
470     * @return the decimal string representation of {@code l}.
471     */
472    public static String toString(long n) {
473        return IntegralToString.longToString(n);
474    }
475
476    /**
477     * Converts the specified signed long value into a string representation based on
478     * the specified radix. The returned string is a concatenation of a minus
479     * sign if the number is negative and characters from '0' to '9' and 'a' to
480     * 'z', depending on the radix. If {@code radix} is not in the interval
481     * defined by {@code Character.MIN_RADIX} and {@code Character.MAX_RADIX}
482     * then 10 is used as the base for the conversion.
483     *
484     * <p>This method treats its argument as signed. If you want to convert an
485     * unsigned value to one of the common non-decimal bases, you may find
486     * {@link #toBinaryString}, {@code #toHexString}, or {@link #toOctalString}
487     * more convenient.
488     *
489     * @param v
490     *            the signed long to convert.
491     * @param radix
492     *            the base to use for the conversion.
493     * @return the string representation of {@code v}.
494     */
495    public static String toString(long v, int radix) {
496        return IntegralToString.longToString(v, radix);
497    }
498
499    /**
500     * Parses the specified string as a signed decimal long value.
501     *
502     * @param string
503     *            the string representation of a long value.
504     * @return a {@code Long} instance containing the long value represented by
505     *         {@code string}.
506     * @throws NumberFormatException
507     *             if {@code string} cannot be parsed as a long value.
508     * @see #parseLong(String)
509     */
510    public static Long valueOf(String string) throws NumberFormatException {
511        return valueOf(parseLong(string));
512    }
513
514    /**
515     * Parses the specified string as a signed long value using the specified
516     * radix.
517     *
518     * @param string
519     *            the string representation of a long value.
520     * @param radix
521     *            the radix to use when parsing.
522     * @return a {@code Long} instance containing the long value represented by
523     *         {@code string} using {@code radix}.
524     * @throws NumberFormatException
525     *             if {@code string} cannot be parsed as a long value, or
526     *             {@code radix < Character.MIN_RADIX ||
527     *             radix > Character.MAX_RADIX}.
528     * @see #parseLong(String, int)
529     */
530    public static Long valueOf(String string, int radix) throws NumberFormatException {
531        return valueOf(parseLong(string, radix));
532    }
533
534    /**
535     * Determines the highest (leftmost) bit of the specified long value that is
536     * 1 and returns the bit mask value for that bit. This is also referred to
537     * as the Most Significant 1 Bit. Returns zero if the specified long is
538     * zero.
539     *
540     * @param v
541     *            the long to examine.
542     * @return the bit mask indicating the highest 1 bit in {@code v}.
543     * @since 1.5
544     */
545    public static long highestOneBit(long v) {
546        // Hacker's Delight, Figure 3-1
547        v |= (v >> 1);
548        v |= (v >> 2);
549        v |= (v >> 4);
550        v |= (v >> 8);
551        v |= (v >> 16);
552        v |= (v >> 32);
553        return v - (v >>> 1);
554    }
555
556    /**
557     * Determines the lowest (rightmost) bit of the specified long value that is
558     * 1 and returns the bit mask value for that bit. This is also referred to
559     * as the Least Significant 1 Bit. Returns zero if the specified long is
560     * zero.
561     *
562     * @param v
563     *            the long to examine.
564     * @return the bit mask indicating the lowest 1 bit in {@code v}.
565     * @since 1.5
566     */
567    public static long lowestOneBit(long v) {
568        return v & -v;
569    }
570
571    /**
572     * Determines the number of leading zeros in the specified long value prior
573     * to the {@link #highestOneBit(long) highest one bit}.
574     *
575     * @param v
576     *            the long to examine.
577     * @return the number of leading zeros in {@code v}.
578     * @since 1.5
579     */
580    public static int numberOfLeadingZeros(long v) {
581        // After Hacker's Delight, Figure 5-6
582        if (v < 0) {
583            return 0;
584        }
585        if (v == 0) {
586            return 64;
587        }
588        // On a 64-bit VM, the two previous tests should probably be replaced by
589        // if (v <= 0) return ((int) (~v >> 57)) & 64;
590
591        int n = 1;
592        int i = (int) (v >>> 32);
593        if (i == 0) {
594            n +=  32;
595            i = (int) v;
596        }
597        if (i >>> 16 == 0) {
598            n +=  16;
599            i <<= 16;
600        }
601        if (i >>> 24 == 0) {
602            n +=  8;
603            i <<= 8;
604        }
605        if (i >>> 28 == 0) {
606            n +=  4;
607            i <<= 4;
608        }
609        if (i >>> 30 == 0) {
610            n +=  2;
611            i <<= 2;
612        }
613        return n - (i >>> 31);
614    }
615
616    /**
617     * Determines the number of trailing zeros in the specified long value after
618     * the {@link #lowestOneBit(long) lowest one bit}.
619     *
620     * @param v
621     *            the long to examine.
622     * @return the number of trailing zeros in {@code v}.
623     * @since 1.5
624     */
625    public static int numberOfTrailingZeros(long v) {
626        int low = (int) v;
627        return low !=0 ? Integer.numberOfTrailingZeros(low)
628                       : 32 + Integer.numberOfTrailingZeros((int) (v >>> 32));
629    }
630
631    /**
632     * Counts the number of 1 bits in the specified long value; this is also
633     * referred to as population count.
634     *
635     * @param v
636     *            the long to examine.
637     * @return the number of 1 bits in {@code v}.
638     * @since 1.5
639     */
640    public static int bitCount(long v) {
641        // Combines techniques from several sources
642        v -=  (v >>> 1) & 0x5555555555555555L;
643        v = (v & 0x3333333333333333L) + ((v >>> 2) & 0x3333333333333333L);
644        int i =  ((int)(v >>> 32)) + (int) v;
645        i = (i & 0x0F0F0F0F) + ((i >>> 4) & 0x0F0F0F0F);
646        i += i >>> 8;
647        i += i >>> 16;
648        return i  & 0x0000007F;
649    }
650
651    /*
652     * On a modern 64-bit processor with a fast hardware multiply, this is
653     * much faster (assuming you're running a 64-bit VM):
654     *
655     * // http://chessprogramming.wikispaces.com/Population+Count
656     * int bitCount (long x) {
657     *     x -=  (x >>> 1) & 0x5555555555555555L;
658     *     x = (x & 0x3333333333333333L) + ((x >>> 2) & 0x3333333333333333L);
659     *     x = (x + (x >>> 4)) & 0x0f0f0f0f0f0f0f0fL;
660     *     x = (x * 0x0101010101010101L) >>> 56;
661     *     return (int) x;
662     * }
663     *
664     * Really modern processors (e.g., Nehalem, K-10) have hardware popcount
665     * instructions.
666     */
667
668    /**
669     * Rotates the bits of the specified long value to the left by the specified
670     * number of bits.
671     *
672     * @param v
673     *            the long value to rotate left.
674     * @param distance
675     *            the number of bits to rotate.
676     * @return the rotated value.
677     * @since 1.5
678     */
679    public static long rotateLeft(long v, int distance) {
680        // Shift distances are mod 64 (JLS3 15.19), so we needn't mask -distance
681        return (v << distance) | (v >>> -distance);
682    }
683
684    /**
685     * Rotates the bits of the specified long value to the right by the
686     * specified number of bits.
687     *
688     * @param v
689     *            the long value to rotate right.
690     * @param distance
691     *            the number of bits to rotate.
692     * @return the rotated value.
693     * @since 1.5
694     */
695    public static long rotateRight(long v, int distance) {
696        // Shift distances are mod 64 (JLS3 15.19), so we needn't mask -distance
697        return (v >>> distance) | (v << -distance);
698    }
699
700    /**
701     * Reverses the order of the bytes of the specified long value.
702     *
703     * @param v
704     *            the long value for which to reverse the byte order.
705     * @return the reversed value.
706     * @since 1.5
707     */
708    public static long reverseBytes(long v) {
709        // Hacker's Delight 7-1, with minor tweak from Veldmeijer
710        // http://graphics.stanford.edu/~seander/bithacks.html
711        v = ((v >>> 8) & 0x00FF00FF00FF00FFL) | ((v & 0x00FF00FF00FF00FFL) << 8);
712        v = ((v >>>16) & 0x0000FFFF0000FFFFL) | ((v & 0x0000FFFF0000FFFFL) <<16);
713        return ((v >>>32)                   ) | ((v                      ) <<32);
714    }
715
716    /**
717     * Reverses the order of the bits of the specified long value.
718     *
719     * @param v
720     *            the long value for which to reverse the bit order.
721     * @return the reversed value.
722     * @since 1.5
723     */
724    public static long reverse(long v) {
725        // Hacker's Delight 7-1, with minor tweak from Veldmeijer
726        // http://graphics.stanford.edu/~seander/bithacks.html
727        v = ((v >>> 1) & 0x5555555555555555L) | ((v & 0x5555555555555555L) << 1);
728        v = ((v >>> 2) & 0x3333333333333333L) | ((v & 0x3333333333333333L) << 2);
729        v = ((v >>> 4) & 0x0F0F0F0F0F0F0F0FL) | ((v & 0x0F0F0F0F0F0F0F0FL) << 4);
730        v = ((v >>> 8) & 0x00FF00FF00FF00FFL) | ((v & 0x00FF00FF00FF00FFL) << 8);
731        v = ((v >>>16) & 0x0000FFFF0000FFFFL) | ((v & 0x0000FFFF0000FFFFL) <<16);
732        return ((v >>>32)                   ) | ((v                      ) <<32);
733    }
734
735    /**
736     * Returns the value of the {@code signum} function for the specified long
737     * value.
738     *
739     * @param v
740     *            the long value to check.
741     * @return -1 if {@code v} is negative, 1 if {@code v} is positive, 0 if
742     *         {@code v} is zero.
743     * @since 1.5
744     */
745    public static int signum(long v) {
746        return v < 0 ? -1 : (v == 0 ? 0 : 1);
747    }
748
749    /**
750     * Returns a {@code Long} instance for the specified long value.
751     * <p>
752     * If it is not necessary to get a new {@code Long} instance, it is
753     * recommended to use this method instead of the constructor, since it
754     * maintains a cache of instances which may result in better performance.
755     *
756     * @param v
757     *            the long value to store in the instance.
758     * @return a {@code Long} instance containing {@code v}.
759     * @since 1.5
760     */
761    public static Long valueOf(long v) {
762        return  v >= 128 || v < -128 ? new Long(v) : SMALL_VALUES[((int) v) + 128];
763    }
764
765    /**
766     * A cache of instances used by {@link Long#valueOf(long)} and auto-boxing.
767     */
768    private static final Long[] SMALL_VALUES = new Long[256];
769
770    static {
771        for (int i = -128; i < 128; i++) {
772            SMALL_VALUES[i + 128] = new Long(i);
773        }
774    }
775}
776