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