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