001/*
002 * Copyright (C) 2008 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.primitives;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkElementIndex;
019import static com.google.common.base.Preconditions.checkNotNull;
020import static com.google.common.base.Preconditions.checkPositionIndexes;
021
022import com.google.common.annotations.GwtCompatible;
023import com.google.common.base.Converter;
024import com.google.errorprone.annotations.InlineMe;
025import java.io.Serializable;
026import java.util.AbstractList;
027import java.util.Arrays;
028import java.util.Collection;
029import java.util.Collections;
030import java.util.Comparator;
031import java.util.List;
032import java.util.RandomAccess;
033import java.util.Spliterator;
034import java.util.Spliterators;
035import javax.annotation.CheckForNull;
036
037/**
038 * Static utility methods pertaining to {@code long} primitives, that are not already found in
039 * either {@link Long} or {@link Arrays}.
040 *
041 * <p>See the Guava User Guide article on <a
042 * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>.
043 *
044 * @author Kevin Bourrillion
045 * @since 1.0
046 */
047@GwtCompatible
048@ElementTypesAreNonnullByDefault
049public final class Longs {
050  private Longs() {}
051
052  /**
053   * The number of bytes required to represent a primitive {@code long} value.
054   *
055   * <p><b>Java 8+ users:</b> use {@link Long#BYTES} instead.
056   */
057  public static final int BYTES = Long.SIZE / Byte.SIZE;
058
059  /**
060   * The largest power of two that can be represented as a {@code long}.
061   *
062   * @since 10.0
063   */
064  public static final long MAX_POWER_OF_TWO = 1L << (Long.SIZE - 2);
065
066  /**
067   * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Long)
068   * value).hashCode()}.
069   *
070   * <p>This method always return the value specified by {@link Long#hashCode()} in java, which
071   * might be different from {@code ((Long) value).hashCode()} in GWT because {@link
072   * Long#hashCode()} in GWT does not obey the JRE contract.
073   *
074   * <p><b>Java 8+ users:</b> use {@link Long#hashCode(long)} instead.
075   *
076   * @param value a primitive {@code long} value
077   * @return a hash code for the value
078   */
079  public static int hashCode(long value) {
080    return (int) (value ^ (value >>> 32));
081  }
082
083  /**
084   * Compares the two specified {@code long} values. The sign of the value returned is the same as
085   * that of {@code ((Long) a).compareTo(b)}.
086   *
087   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated; use the
088   * equivalent {@link Long#compare} method instead.
089   *
090   * @param a the first {@code long} to compare
091   * @param b the second {@code long} to compare
092   * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is
093   *     greater than {@code b}; or zero if they are equal
094   */
095  @InlineMe(replacement = "Long.compare(a, b)")
096  public static int compare(long a, long b) {
097    return Long.compare(a, b);
098  }
099
100  /**
101   * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}.
102   *
103   * @param array an array of {@code long} values, possibly empty
104   * @param target a primitive {@code long} value
105   * @return {@code true} if {@code array[i] == target} for some value of {@code i}
106   */
107  public static boolean contains(long[] array, long target) {
108    for (long value : array) {
109      if (value == target) {
110        return true;
111      }
112    }
113    return false;
114  }
115
116  /**
117   * Returns the index of the first appearance of the value {@code target} in {@code array}.
118   *
119   * @param array an array of {@code long} values, possibly empty
120   * @param target a primitive {@code long} value
121   * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no
122   *     such index exists.
123   */
124  public static int indexOf(long[] array, long target) {
125    return indexOf(array, target, 0, array.length);
126  }
127
128  // TODO(kevinb): consider making this public
129  private static int indexOf(long[] array, long target, int start, int end) {
130    for (int i = start; i < end; i++) {
131      if (array[i] == target) {
132        return i;
133      }
134    }
135    return -1;
136  }
137
138  /**
139   * Returns the start position of the first occurrence of the specified {@code target} within
140   * {@code array}, or {@code -1} if there is no such occurrence.
141   *
142   * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array,
143   * i, i + target.length)} contains exactly the same elements as {@code target}.
144   *
145   * @param array the array to search for the sequence {@code target}
146   * @param target the array to search for as a sub-sequence of {@code array}
147   */
148  public static int indexOf(long[] array, long[] target) {
149    checkNotNull(array, "array");
150    checkNotNull(target, "target");
151    if (target.length == 0) {
152      return 0;
153    }
154
155    outer:
156    for (int i = 0; i < array.length - target.length + 1; i++) {
157      for (int j = 0; j < target.length; j++) {
158        if (array[i + j] != target[j]) {
159          continue outer;
160        }
161      }
162      return i;
163    }
164    return -1;
165  }
166
167  /**
168   * Returns the index of the last appearance of the value {@code target} in {@code array}.
169   *
170   * @param array an array of {@code long} values, possibly empty
171   * @param target a primitive {@code long} value
172   * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no
173   *     such index exists.
174   */
175  public static int lastIndexOf(long[] array, long target) {
176    return lastIndexOf(array, target, 0, array.length);
177  }
178
179  // TODO(kevinb): consider making this public
180  private static int lastIndexOf(long[] array, long target, int start, int end) {
181    for (int i = end - 1; i >= start; i--) {
182      if (array[i] == target) {
183        return i;
184      }
185    }
186    return -1;
187  }
188
189  /**
190   * Returns the least value present in {@code array}.
191   *
192   * @param array a <i>nonempty</i> array of {@code long} values
193   * @return the value present in {@code array} that is less than or equal to every other value in
194   *     the array
195   * @throws IllegalArgumentException if {@code array} is empty
196   */
197  public static long min(long... array) {
198    checkArgument(array.length > 0);
199    long min = array[0];
200    for (int i = 1; i < array.length; i++) {
201      if (array[i] < min) {
202        min = array[i];
203      }
204    }
205    return min;
206  }
207
208  /**
209   * Returns the greatest value present in {@code array}.
210   *
211   * @param array a <i>nonempty</i> array of {@code long} values
212   * @return the value present in {@code array} that is greater than or equal to every other value
213   *     in the array
214   * @throws IllegalArgumentException if {@code array} is empty
215   */
216  public static long max(long... array) {
217    checkArgument(array.length > 0);
218    long max = array[0];
219    for (int i = 1; i < array.length; i++) {
220      if (array[i] > max) {
221        max = array[i];
222      }
223    }
224    return max;
225  }
226
227  /**
228   * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}.
229   *
230   * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned
231   * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code
232   * value} is greater than {@code max}, {@code max} is returned.
233   *
234   * @param value the {@code long} value to constrain
235   * @param min the lower bound (inclusive) of the range to constrain {@code value} to
236   * @param max the upper bound (inclusive) of the range to constrain {@code value} to
237   * @throws IllegalArgumentException if {@code min > max}
238   * @since 21.0
239   */
240  public static long constrainToRange(long value, long min, long max) {
241    checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max);
242    return Math.min(Math.max(value, min), max);
243  }
244
245  /**
246   * Returns the values from each provided array combined into a single array. For example, {@code
247   * concat(new long[] {a, b}, new long[] {}, new long[] {c}} returns the array {@code {a, b, c}}.
248   *
249   * @param arrays zero or more {@code long} arrays
250   * @return a single array containing all the values from the source arrays, in order
251   * @throws IllegalArgumentException if the total number of elements in {@code arrays} does not fit
252   *     in an {@code int}
253   */
254  public static long[] concat(long[]... arrays) {
255    long length = 0;
256    for (long[] array : arrays) {
257      length += array.length;
258    }
259    long[] result = new long[checkNoOverflow(length)];
260    int pos = 0;
261    for (long[] array : arrays) {
262      System.arraycopy(array, 0, result, pos, array.length);
263      pos += array.length;
264    }
265    return result;
266  }
267
268  private static int checkNoOverflow(long result) {
269    checkArgument(
270        result == (int) result,
271        "the total number of elements (%s) in the arrays must fit in an int",
272        result);
273    return (int) result;
274  }
275
276  /**
277   * Returns a big-endian representation of {@code value} in an 8-element byte array; equivalent to
278   * {@code ByteBuffer.allocate(8).putLong(value).array()}. For example, the input value {@code
279   * 0x1213141516171819L} would yield the byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
280   * 0x18, 0x19}}.
281   *
282   * <p>If you need to convert and concatenate several values (possibly even of different types),
283   * use a shared {@link java.nio.ByteBuffer} instance, or use {@link
284   * com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer.
285   */
286  public static byte[] toByteArray(long value) {
287    // Note that this code needs to stay compatible with GWT, which has known
288    // bugs when narrowing byte casts of long values occur.
289    byte[] result = new byte[8];
290    for (int i = 7; i >= 0; i--) {
291      result[i] = (byte) (value & 0xffL);
292      value >>= 8;
293    }
294    return result;
295  }
296
297  /**
298   * Returns the {@code long} value whose big-endian representation is stored in the first 8 bytes
299   * of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getLong()}. For example, the
300   * input byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}} would yield the
301   * {@code long} value {@code 0x1213141516171819L}.
302   *
303   * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more
304   * flexibility at little cost in readability.
305   *
306   * @throws IllegalArgumentException if {@code bytes} has fewer than 8 elements
307   */
308  public static long fromByteArray(byte[] bytes) {
309    checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES);
310    return fromBytes(
311        bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]);
312  }
313
314  /**
315   * Returns the {@code long} value whose byte representation is the given 8 bytes, in big-endian
316   * order; equivalent to {@code Longs.fromByteArray(new byte[] {b1, b2, b3, b4, b5, b6, b7, b8})}.
317   *
318   * @since 7.0
319   */
320  public static long fromBytes(
321      byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7, byte b8) {
322    return (b1 & 0xFFL) << 56
323        | (b2 & 0xFFL) << 48
324        | (b3 & 0xFFL) << 40
325        | (b4 & 0xFFL) << 32
326        | (b5 & 0xFFL) << 24
327        | (b6 & 0xFFL) << 16
328        | (b7 & 0xFFL) << 8
329        | (b8 & 0xFFL);
330  }
331
332  /*
333   * Moving asciiDigits into this static holder class lets ProGuard eliminate and inline the Longs
334   * class.
335   */
336  static final class AsciiDigits {
337    private AsciiDigits() {}
338
339    private static final byte[] asciiDigits;
340
341    static {
342      byte[] result = new byte[128];
343      Arrays.fill(result, (byte) -1);
344      for (int i = 0; i < 10; i++) {
345        result['0' + i] = (byte) i;
346      }
347      for (int i = 0; i < 26; i++) {
348        result['A' + i] = (byte) (10 + i);
349        result['a' + i] = (byte) (10 + i);
350      }
351      asciiDigits = result;
352    }
353
354    static int digit(char c) {
355      return (c < 128) ? asciiDigits[c] : -1;
356    }
357  }
358
359  /**
360   * Parses the specified string as a signed decimal long value. The ASCII character {@code '-'} (
361   * <code>'&#92;u002D'</code>) is recognized as the minus sign.
362   *
363   * <p>Unlike {@link Long#parseLong(String)}, this method returns {@code null} instead of throwing
364   * an exception if parsing fails. Additionally, this method only accepts ASCII digits, and returns
365   * {@code null} if non-ASCII digits are present in the string.
366   *
367   * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even though {@link
368   * Integer#parseInt(String)} accepts them.
369   *
370   * @param string the string representation of a long value
371   * @return the long value represented by {@code string}, or {@code null} if {@code string} has a
372   *     length of zero or cannot be parsed as a long value
373   * @throws NullPointerException if {@code string} is {@code null}
374   * @since 14.0
375   */
376  @CheckForNull
377  public static Long tryParse(String string) {
378    return tryParse(string, 10);
379  }
380
381  /**
382   * Parses the specified string as a signed long value using the specified radix. The ASCII
383   * character {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the minus sign.
384   *
385   * <p>Unlike {@link Long#parseLong(String, int)}, this method returns {@code null} instead of
386   * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits,
387   * and returns {@code null} if non-ASCII digits are present in the string.
388   *
389   * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even though {@link
390   * Integer#parseInt(String)} accepts them.
391   *
392   * @param string the string representation of a long value
393   * @param radix the radix to use when parsing
394   * @return the long value represented by {@code string} using {@code radix}, or {@code null} if
395   *     {@code string} has a length of zero or cannot be parsed as a long value
396   * @throws IllegalArgumentException if {@code radix < Character.MIN_RADIX} or {@code radix >
397   *     Character.MAX_RADIX}
398   * @throws NullPointerException if {@code string} is {@code null}
399   * @since 19.0
400   */
401  @CheckForNull
402  public static Long tryParse(String string, int radix) {
403    if (checkNotNull(string).isEmpty()) {
404      return null;
405    }
406    if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
407      throw new IllegalArgumentException(
408          "radix must be between MIN_RADIX and MAX_RADIX but was " + radix);
409    }
410    boolean negative = string.charAt(0) == '-';
411    int index = negative ? 1 : 0;
412    if (index == string.length()) {
413      return null;
414    }
415    int digit = AsciiDigits.digit(string.charAt(index++));
416    if (digit < 0 || digit >= radix) {
417      return null;
418    }
419    long accum = -digit;
420
421    long cap = Long.MIN_VALUE / radix;
422
423    while (index < string.length()) {
424      digit = AsciiDigits.digit(string.charAt(index++));
425      if (digit < 0 || digit >= radix || accum < cap) {
426        return null;
427      }
428      accum *= radix;
429      if (accum < Long.MIN_VALUE + digit) {
430        return null;
431      }
432      accum -= digit;
433    }
434
435    if (negative) {
436      return accum;
437    } else if (accum == Long.MIN_VALUE) {
438      return null;
439    } else {
440      return -accum;
441    }
442  }
443
444  private static final class LongConverter extends Converter<String, Long> implements Serializable {
445    static final Converter<String, Long> INSTANCE = new LongConverter();
446
447    @Override
448    protected Long doForward(String value) {
449      return Long.decode(value);
450    }
451
452    @Override
453    protected String doBackward(Long value) {
454      return value.toString();
455    }
456
457    @Override
458    public String toString() {
459      return "Longs.stringConverter()";
460    }
461
462    private Object readResolve() {
463      return INSTANCE;
464    }
465
466    private static final long serialVersionUID = 1;
467  }
468
469  /**
470   * Returns a serializable converter object that converts between strings and longs using {@link
471   * Long#decode} and {@link Long#toString()}. The returned converter throws {@link
472   * NumberFormatException} if the input string is invalid.
473   *
474   * <p><b>Warning:</b> please see {@link Long#decode} to understand exactly how strings are parsed.
475   * For example, the string {@code "0123"} is treated as <i>octal</i> and converted to the value
476   * {@code 83L}.
477   *
478   * @since 16.0
479   */
480  public static Converter<String, Long> stringConverter() {
481    return LongConverter.INSTANCE;
482  }
483
484  /**
485   * Returns an array containing the same values as {@code array}, but guaranteed to be of a
486   * specified minimum length. If {@code array} already has a length of at least {@code minLength},
487   * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is
488   * returned, containing the values of {@code array}, and zeroes in the remaining places.
489   *
490   * @param array the source array
491   * @param minLength the minimum length the returned array must guarantee
492   * @param padding an extra amount to "grow" the array by if growth is necessary
493   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative
494   * @return an array containing the values of {@code array}, with guaranteed minimum length {@code
495   *     minLength}
496   */
497  public static long[] ensureCapacity(long[] array, int minLength, int padding) {
498    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
499    checkArgument(padding >= 0, "Invalid padding: %s", padding);
500    return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array;
501  }
502
503  /**
504   * Returns a string containing the supplied {@code long} values separated by {@code separator}.
505   * For example, {@code join("-", 1L, 2L, 3L)} returns the string {@code "1-2-3"}.
506   *
507   * @param separator the text that should appear between consecutive values in the resulting string
508   *     (but not at the start or end)
509   * @param array an array of {@code long} values, possibly empty
510   */
511  public static String join(String separator, long... array) {
512    checkNotNull(separator);
513    if (array.length == 0) {
514      return "";
515    }
516
517    // For pre-sizing a builder, just get the right order of magnitude
518    StringBuilder builder = new StringBuilder(array.length * 10);
519    builder.append(array[0]);
520    for (int i = 1; i < array.length; i++) {
521      builder.append(separator).append(array[i]);
522    }
523    return builder.toString();
524  }
525
526  /**
527   * Returns a comparator that compares two {@code long} arrays <a
528   * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it
529   * compares, using {@link #compare(long, long)}), the first pair of values that follow any common
530   * prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For
531   * example, {@code [] < [1L] < [1L, 2L] < [2L]}.
532   *
533   * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
534   * support only identity equality), but it is consistent with {@link Arrays#equals(long[],
535   * long[])}.
536   *
537   * @since 2.0
538   */
539  public static Comparator<long[]> lexicographicalComparator() {
540    return LexicographicalComparator.INSTANCE;
541  }
542
543  private enum LexicographicalComparator implements Comparator<long[]> {
544    INSTANCE;
545
546    @Override
547    public int compare(long[] left, long[] right) {
548      int minLength = Math.min(left.length, right.length);
549      for (int i = 0; i < minLength; i++) {
550        int result = Long.compare(left[i], right[i]);
551        if (result != 0) {
552          return result;
553        }
554      }
555      return left.length - right.length;
556    }
557
558    @Override
559    public String toString() {
560      return "Longs.lexicographicalComparator()";
561    }
562  }
563
564  /**
565   * Sorts the elements of {@code array} in descending order.
566   *
567   * @since 23.1
568   */
569  public static void sortDescending(long[] array) {
570    checkNotNull(array);
571    sortDescending(array, 0, array.length);
572  }
573
574  /**
575   * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
576   * exclusive in descending order.
577   *
578   * @since 23.1
579   */
580  public static void sortDescending(long[] array, int fromIndex, int toIndex) {
581    checkNotNull(array);
582    checkPositionIndexes(fromIndex, toIndex, array.length);
583    Arrays.sort(array, fromIndex, toIndex);
584    reverse(array, fromIndex, toIndex);
585  }
586
587  /**
588   * Reverses the elements of {@code array}. This is equivalent to {@code
589   * Collections.reverse(Longs.asList(array))}, but is likely to be more efficient.
590   *
591   * @since 23.1
592   */
593  public static void reverse(long[] array) {
594    checkNotNull(array);
595    reverse(array, 0, array.length);
596  }
597
598  /**
599   * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
600   * exclusive. This is equivalent to {@code
601   * Collections.reverse(Longs.asList(array).subList(fromIndex, toIndex))}, but is likely to be more
602   * efficient.
603   *
604   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
605   *     {@code toIndex > fromIndex}
606   * @since 23.1
607   */
608  public static void reverse(long[] array, int fromIndex, int toIndex) {
609    checkNotNull(array);
610    checkPositionIndexes(fromIndex, toIndex, array.length);
611    for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) {
612      long tmp = array[i];
613      array[i] = array[j];
614      array[j] = tmp;
615    }
616  }
617
618  /**
619   * Performs a right rotation of {@code array} of "distance" places, so that the first element is
620   * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
621   * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Longs.asList(array),
622   * distance)}, but is considerably faster and avoids allocation and garbage collection.
623   *
624   * <p>The provided "distance" may be negative, which will rotate left.
625   *
626   * @since 32.0.0
627   */
628  public static void rotate(long[] array, int distance) {
629    rotate(array, distance, 0, array.length);
630  }
631
632  /**
633   * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
634   * toIndex} exclusive. This is equivalent to {@code
635   * Collections.rotate(Longs.asList(array).subList(fromIndex, toIndex), distance)}, but is
636   * considerably faster and avoids allocations and garbage collection.
637   *
638   * <p>The provided "distance" may be negative, which will rotate left.
639   *
640   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
641   *     {@code toIndex > fromIndex}
642   * @since 32.0.0
643   */
644  public static void rotate(long[] array, int distance, int fromIndex, int toIndex) {
645    // See Ints.rotate for more details about possible algorithms here.
646    checkNotNull(array);
647    checkPositionIndexes(fromIndex, toIndex, array.length);
648    if (array.length <= 1) {
649      return;
650    }
651
652    int length = toIndex - fromIndex;
653    // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
654    // places left to rotate.
655    int m = -distance % length;
656    m = (m < 0) ? m + length : m;
657    // The current index of what will become the first element of the rotated section.
658    int newFirstIndex = m + fromIndex;
659    if (newFirstIndex == fromIndex) {
660      return;
661    }
662
663    reverse(array, fromIndex, newFirstIndex);
664    reverse(array, newFirstIndex, toIndex);
665    reverse(array, fromIndex, toIndex);
666  }
667
668  /**
669   * Returns an array containing each value of {@code collection}, converted to a {@code long} value
670   * in the manner of {@link Number#longValue}.
671   *
672   * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}.
673   * Calling this method is as thread-safe as calling that method.
674   *
675   * @param collection a collection of {@code Number} instances
676   * @return an array containing the same values as {@code collection}, in the same order, converted
677   *     to primitives
678   * @throws NullPointerException if {@code collection} or any of its elements is null
679   * @since 1.0 (parameter was {@code Collection<Long>} before 12.0)
680   */
681  public static long[] toArray(Collection<? extends Number> collection) {
682    if (collection instanceof LongArrayAsList) {
683      return ((LongArrayAsList) collection).toLongArray();
684    }
685
686    Object[] boxedArray = collection.toArray();
687    int len = boxedArray.length;
688    long[] array = new long[len];
689    for (int i = 0; i < len; i++) {
690      // checkNotNull for GWT (do not optimize)
691      array[i] = ((Number) checkNotNull(boxedArray[i])).longValue();
692    }
693    return array;
694  }
695
696  /**
697   * Returns a fixed-size list backed by the specified array, similar to {@link
698   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
699   * set a value to {@code null} will result in a {@link NullPointerException}.
700   *
701   * <p>The returned list maintains the values, but not the identities, of {@code Long} objects
702   * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
703   * the returned list is unspecified.
704   *
705   * <p>The returned list is serializable.
706   *
707   * <p><b>Note:</b> when possible, you should represent your data as an {@link ImmutableLongArray}
708   * instead, which has an {@link ImmutableLongArray#asList asList} view.
709   *
710   * @param backingArray the array to back the list
711   * @return a list view of the array
712   */
713  public static List<Long> asList(long... backingArray) {
714    if (backingArray.length == 0) {
715      return Collections.emptyList();
716    }
717    return new LongArrayAsList(backingArray);
718  }
719
720  @GwtCompatible
721  private static class LongArrayAsList extends AbstractList<Long>
722      implements RandomAccess, Serializable {
723    final long[] array;
724    final int start;
725    final int end;
726
727    LongArrayAsList(long[] array) {
728      this(array, 0, array.length);
729    }
730
731    LongArrayAsList(long[] array, int start, int end) {
732      this.array = array;
733      this.start = start;
734      this.end = end;
735    }
736
737    @Override
738    public int size() {
739      return end - start;
740    }
741
742    @Override
743    public boolean isEmpty() {
744      return false;
745    }
746
747    @Override
748    public Long get(int index) {
749      checkElementIndex(index, size());
750      return array[start + index];
751    }
752
753    @Override
754    public Spliterator.OfLong spliterator() {
755      return Spliterators.spliterator(array, start, end, 0);
756    }
757
758    @Override
759    public boolean contains(@CheckForNull Object target) {
760      // Overridden to prevent a ton of boxing
761      return (target instanceof Long) && Longs.indexOf(array, (Long) target, start, end) != -1;
762    }
763
764    @Override
765    public int indexOf(@CheckForNull Object target) {
766      // Overridden to prevent a ton of boxing
767      if (target instanceof Long) {
768        int i = Longs.indexOf(array, (Long) target, start, end);
769        if (i >= 0) {
770          return i - start;
771        }
772      }
773      return -1;
774    }
775
776    @Override
777    public int lastIndexOf(@CheckForNull Object target) {
778      // Overridden to prevent a ton of boxing
779      if (target instanceof Long) {
780        int i = Longs.lastIndexOf(array, (Long) target, start, end);
781        if (i >= 0) {
782          return i - start;
783        }
784      }
785      return -1;
786    }
787
788    @Override
789    public Long set(int index, Long element) {
790      checkElementIndex(index, size());
791      long oldValue = array[start + index];
792      // checkNotNull for GWT (do not optimize)
793      array[start + index] = checkNotNull(element);
794      return oldValue;
795    }
796
797    @Override
798    public List<Long> subList(int fromIndex, int toIndex) {
799      int size = size();
800      checkPositionIndexes(fromIndex, toIndex, size);
801      if (fromIndex == toIndex) {
802        return Collections.emptyList();
803      }
804      return new LongArrayAsList(array, start + fromIndex, start + toIndex);
805    }
806
807    @Override
808    public boolean equals(@CheckForNull Object object) {
809      if (object == this) {
810        return true;
811      }
812      if (object instanceof LongArrayAsList) {
813        LongArrayAsList that = (LongArrayAsList) object;
814        int size = size();
815        if (that.size() != size) {
816          return false;
817        }
818        for (int i = 0; i < size; i++) {
819          if (array[start + i] != that.array[that.start + i]) {
820            return false;
821          }
822        }
823        return true;
824      }
825      return super.equals(object);
826    }
827
828    @Override
829    public int hashCode() {
830      int result = 1;
831      for (int i = start; i < end; i++) {
832        result = 31 * result + Longs.hashCode(array[i]);
833      }
834      return result;
835    }
836
837    @Override
838    public String toString() {
839      StringBuilder builder = new StringBuilder(size() * 10);
840      builder.append('[').append(array[start]);
841      for (int i = start + 1; i < end; i++) {
842        builder.append(", ").append(array[i]);
843      }
844      return builder.append(']').toString();
845    }
846
847    long[] toLongArray() {
848      return Arrays.copyOfRange(array, start, end);
849    }
850
851    private static final long serialVersionUID = 0;
852  }
853}