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