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