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