001/*
002 * Copyright (C) 2008 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.primitives;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkElementIndex;
019import static com.google.common.base.Preconditions.checkNotNull;
020import static com.google.common.base.Preconditions.checkPositionIndexes;
021
022import com.google.common.annotations.GwtCompatible;
023import com.google.common.base.Converter;
024import com.google.errorprone.annotations.InlineMe;
025import java.io.Serializable;
026import java.util.AbstractList;
027import java.util.Arrays;
028import java.util.Collection;
029import java.util.Collections;
030import java.util.Comparator;
031import java.util.List;
032import java.util.RandomAccess;
033import java.util.Spliterator;
034import java.util.Spliterators;
035import org.jspecify.annotations.Nullable;
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
048public final class Longs {
049  private Longs() {}
050
051  /**
052   * The number of bytes required to represent a primitive {@code long} value.
053   *
054   * <p><b>Java 8+ users:</b> use {@link Long#BYTES} instead.
055   */
056  public static final int BYTES = Long.SIZE / Byte.SIZE;
057
058  /**
059   * The largest power of two that can be represented as a {@code long}.
060   *
061   * @since 10.0
062   */
063  public static final long MAX_POWER_OF_TWO = 1L << (Long.SIZE - 2);
064
065  /**
066   * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Long)
067   * value).hashCode()}.
068   *
069   * <p>This method always return the value specified by {@link Long#hashCode()} in java, which
070   * might be different from {@code ((Long) value).hashCode()} in GWT because {@link
071   * Long#hashCode()} in GWT does not obey the JRE contract.
072   *
073   * <p><b>Java 8+ users:</b> use {@link Long#hashCode(long)} instead.
074   *
075   * @param value a primitive {@code long} value
076   * @return a hash code for the value
077   */
078  public static int hashCode(long value) {
079    return (int) (value ^ (value >>> 32));
080  }
081
082  /**
083   * Compares the two specified {@code long} values. The sign of the value returned is the same as
084   * that of {@code ((Long) a).compareTo(b)}.
085   *
086   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated; use the
087   * equivalent {@link Long#compare} method instead.
088   *
089   * @param a the first {@code long} to compare
090   * @param b the second {@code long} to compare
091   * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is
092   *     greater than {@code b}; or zero if they are equal
093   */
094  @InlineMe(replacement = "Long.compare(a, b)")
095  public static int compare(long a, long b) {
096    return Long.compare(a, b);
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   * <p><b>Java 21+ users:</b> Use {@code Math.clamp} instead. Note that that method 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      System.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  public static byte[] toByteArray(long value) {
289    // Note that this code needs to stay compatible with GWT, which has known
290    // bugs when narrowing byte casts of long values occur.
291    byte[] result = new byte[8];
292    for (int i = 7; i >= 0; i--) {
293      result[i] = (byte) (value & 0xffL);
294      value >>= 8;
295    }
296    return result;
297  }
298
299  /**
300   * Returns the {@code long} value whose big-endian representation is stored in the first 8 bytes
301   * of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getLong()}. For example, the
302   * input byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}} would yield the
303   * {@code long} value {@code 0x1213141516171819L}.
304   *
305   * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more
306   * flexibility at little cost in readability.
307   *
308   * @throws IllegalArgumentException if {@code bytes} has fewer than 8 elements
309   */
310  public static long fromByteArray(byte[] bytes) {
311    checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES);
312    return fromBytes(
313        bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]);
314  }
315
316  /**
317   * Returns the {@code long} value whose byte representation is the given 8 bytes, in big-endian
318   * order; equivalent to {@code Longs.fromByteArray(new byte[] {b1, b2, b3, b4, b5, b6, b7, b8})}.
319   *
320   * @since 7.0
321   */
322  public static long fromBytes(
323      byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7, byte b8) {
324    return (b1 & 0xFFL) << 56
325        | (b2 & 0xFFL) << 48
326        | (b3 & 0xFFL) << 40
327        | (b4 & 0xFFL) << 32
328        | (b5 & 0xFFL) << 24
329        | (b6 & 0xFFL) << 16
330        | (b7 & 0xFFL) << 8
331        | (b8 & 0xFFL);
332  }
333
334  /*
335   * Moving asciiDigits into this static holder class lets ProGuard eliminate and inline the Longs
336   * class.
337   */
338  static final class AsciiDigits {
339    private AsciiDigits() {}
340
341    private static final byte[] asciiDigits;
342
343    static {
344      byte[] result = new byte[128];
345      Arrays.fill(result, (byte) -1);
346      for (int i = 0; i < 10; i++) {
347        result['0' + i] = (byte) i;
348      }
349      for (int i = 0; i < 26; i++) {
350        result['A' + i] = (byte) (10 + i);
351        result['a' + i] = (byte) (10 + i);
352      }
353      asciiDigits = result;
354    }
355
356    static int digit(char c) {
357      return (c < 128) ? asciiDigits[c] : -1;
358    }
359  }
360
361  /**
362   * Parses the specified string as a signed decimal long value. The ASCII character {@code '-'} (
363   * <code>'&#92;u002D'</code>) is recognized as the minus sign.
364   *
365   * <p>Unlike {@link Long#parseLong(String)}, this method returns {@code null} instead of throwing
366   * an exception if parsing fails. Additionally, this method only accepts ASCII digits, and returns
367   * {@code null} if non-ASCII digits are present in the string.
368   *
369   * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even though {@link
370   * Integer#parseInt(String)} accepts them.
371   *
372   * @param string the string representation of a long value
373   * @return the long value represented by {@code string}, or {@code null} if {@code string} has a
374   *     length of zero or cannot be parsed as a long value
375   * @throws NullPointerException if {@code string} is {@code null}
376   * @since 14.0
377   */
378  public static @Nullable Long tryParse(String string) {
379    return tryParse(string, 10);
380  }
381
382  /**
383   * Parses the specified string as a signed long value using the specified radix. The ASCII
384   * character {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the minus sign.
385   *
386   * <p>Unlike {@link Long#parseLong(String, int)}, this method returns {@code null} instead of
387   * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits,
388   * and returns {@code null} if non-ASCII digits are present in the string.
389   *
390   * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even though {@link
391   * Integer#parseInt(String)} accepts them.
392   *
393   * @param string the string representation of a long value
394   * @param radix the radix to use when parsing
395   * @return the long value represented by {@code string} using {@code radix}, or {@code null} if
396   *     {@code string} has a length of zero or cannot be parsed as a long value
397   * @throws IllegalArgumentException if {@code radix < Character.MIN_RADIX} or {@code radix >
398   *     Character.MAX_RADIX}
399   * @throws NullPointerException if {@code string} is {@code null}
400   * @since 19.0
401   */
402  public static @Nullable Long tryParse(String string, int radix) {
403    if (checkNotNull(string).isEmpty()) {
404      return null;
405    }
406    if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
407      throw new IllegalArgumentException(
408          "radix must be between MIN_RADIX and MAX_RADIX but was " + radix);
409    }
410    boolean negative = string.charAt(0) == '-';
411    int index = negative ? 1 : 0;
412    if (index == string.length()) {
413      return null;
414    }
415    int digit = AsciiDigits.digit(string.charAt(index++));
416    if (digit < 0 || digit >= radix) {
417      return null;
418    }
419    long accum = -digit;
420
421    long cap = Long.MIN_VALUE / radix;
422
423    while (index < string.length()) {
424      digit = AsciiDigits.digit(string.charAt(index++));
425      if (digit < 0 || digit >= radix || accum < cap) {
426        return null;
427      }
428      accum *= radix;
429      if (accum < Long.MIN_VALUE + digit) {
430        return null;
431      }
432      accum -= digit;
433    }
434
435    if (negative) {
436      return accum;
437    } else if (accum == Long.MIN_VALUE) {
438      return null;
439    } else {
440      return -accum;
441    }
442  }
443
444  private static final class LongConverter extends Converter<String, Long> implements Serializable {
445    static final Converter<String, Long> INSTANCE = new LongConverter();
446
447    @Override
448    protected Long doForward(String value) {
449      return Long.decode(value);
450    }
451
452    @Override
453    protected String doBackward(Long value) {
454      return value.toString();
455    }
456
457    @Override
458    public String toString() {
459      return "Longs.stringConverter()";
460    }
461
462    private Object readResolve() {
463      return INSTANCE;
464    }
465
466    private static final long serialVersionUID = 1;
467  }
468
469  /**
470   * Returns a serializable converter object that converts between strings and longs using {@link
471   * Long#decode} and {@link Long#toString()}. The returned converter throws {@link
472   * NumberFormatException} if the input string is invalid.
473   *
474   * <p><b>Warning:</b> please see {@link Long#decode} to understand exactly how strings are parsed.
475   * For example, the string {@code "0123"} is treated as <i>octal</i> and converted to the value
476   * {@code 83L}.
477   *
478   * @since 16.0
479   */
480  public static Converter<String, Long> stringConverter() {
481    return LongConverter.INSTANCE;
482  }
483
484  /**
485   * Returns an array containing the same values as {@code array}, but guaranteed to be of a
486   * specified minimum length. If {@code array} already has a length of at least {@code minLength},
487   * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is
488   * returned, containing the values of {@code array}, and zeroes in the remaining places.
489   *
490   * @param array the source array
491   * @param minLength the minimum length the returned array must guarantee
492   * @param padding an extra amount to "grow" the array by if growth is necessary
493   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative
494   * @return an array containing the values of {@code array}, with guaranteed minimum length {@code
495   *     minLength}
496   */
497  public static long[] ensureCapacity(long[] array, int minLength, int padding) {
498    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
499    checkArgument(padding >= 0, "Invalid padding: %s", padding);
500    return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array;
501  }
502
503  /**
504   * Returns a string containing the supplied {@code long} values separated by {@code separator}.
505   * For example, {@code join("-", 1L, 2L, 3L)} returns the string {@code "1-2-3"}.
506   *
507   * @param separator the text that should appear between consecutive values in the resulting string
508   *     (but not at the start or end)
509   * @param array an array of {@code long} values, possibly empty
510   */
511  public static String join(String separator, long... array) {
512    checkNotNull(separator);
513    if (array.length == 0) {
514      return "";
515    }
516
517    // For pre-sizing a builder, just get the right order of magnitude
518    StringBuilder builder = new StringBuilder(array.length * 10);
519    builder.append(array[0]);
520    for (int i = 1; i < array.length; i++) {
521      builder.append(separator).append(array[i]);
522    }
523    return builder.toString();
524  }
525
526  /**
527   * Returns a comparator that compares two {@code long} arrays <a
528   * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it
529   * compares, using {@link #compare(long, long)}), the first pair of values that follow any common
530   * prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For
531   * example, {@code [] < [1L] < [1L, 2L] < [2L]}.
532   *
533   * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
534   * support only identity equality), but it is consistent with {@link Arrays#equals(long[],
535   * long[])}.
536   *
537   * @since 2.0
538   */
539  public static Comparator<long[]> lexicographicalComparator() {
540    return LexicographicalComparator.INSTANCE;
541  }
542
543  private enum LexicographicalComparator implements Comparator<long[]> {
544    INSTANCE;
545
546    @Override
547    public int compare(long[] left, long[] right) {
548      int minLength = Math.min(left.length, right.length);
549      for (int i = 0; i < minLength; i++) {
550        int result = Long.compare(left[i], right[i]);
551        if (result != 0) {
552          return result;
553        }
554      }
555      return left.length - right.length;
556    }
557
558    @Override
559    public String toString() {
560      return "Longs.lexicographicalComparator()";
561    }
562  }
563
564  /**
565   * Sorts the elements of {@code array} in descending order.
566   *
567   * @since 23.1
568   */
569  public static void sortDescending(long[] array) {
570    checkNotNull(array);
571    sortDescending(array, 0, array.length);
572  }
573
574  /**
575   * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
576   * exclusive in descending order.
577   *
578   * @since 23.1
579   */
580  public static void sortDescending(long[] array, int fromIndex, int toIndex) {
581    checkNotNull(array);
582    checkPositionIndexes(fromIndex, toIndex, array.length);
583    Arrays.sort(array, fromIndex, toIndex);
584    reverse(array, fromIndex, toIndex);
585  }
586
587  /**
588   * Reverses the elements of {@code array}. This is equivalent to {@code
589   * Collections.reverse(Longs.asList(array))}, but is likely to be more efficient.
590   *
591   * @since 23.1
592   */
593  public static void reverse(long[] array) {
594    checkNotNull(array);
595    reverse(array, 0, array.length);
596  }
597
598  /**
599   * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
600   * exclusive. This is equivalent to {@code
601   * Collections.reverse(Longs.asList(array).subList(fromIndex, toIndex))}, but is likely to be more
602   * efficient.
603   *
604   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
605   *     {@code toIndex > fromIndex}
606   * @since 23.1
607   */
608  public static void reverse(long[] array, int fromIndex, int toIndex) {
609    checkNotNull(array);
610    checkPositionIndexes(fromIndex, toIndex, array.length);
611    for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) {
612      long tmp = array[i];
613      array[i] = array[j];
614      array[j] = tmp;
615    }
616  }
617
618  /**
619   * Performs a right rotation of {@code array} of "distance" places, so that the first element is
620   * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
621   * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Longs.asList(array),
622   * distance)}, but is considerably faster and avoids allocation and garbage collection.
623   *
624   * <p>The provided "distance" may be negative, which will rotate left.
625   *
626   * @since 32.0.0
627   */
628  public static void rotate(long[] array, int distance) {
629    rotate(array, distance, 0, array.length);
630  }
631
632  /**
633   * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
634   * toIndex} exclusive. This is equivalent to {@code
635   * Collections.rotate(Longs.asList(array).subList(fromIndex, toIndex), distance)}, but is
636   * considerably faster and avoids allocations and garbage collection.
637   *
638   * <p>The provided "distance" may be negative, which will rotate left.
639   *
640   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
641   *     {@code toIndex > fromIndex}
642   * @since 32.0.0
643   */
644  public static void rotate(long[] array, int distance, int fromIndex, int toIndex) {
645    // See Ints.rotate for more details about possible algorithms here.
646    checkNotNull(array);
647    checkPositionIndexes(fromIndex, toIndex, array.length);
648    if (array.length <= 1) {
649      return;
650    }
651
652    int length = toIndex - fromIndex;
653    // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
654    // places left to rotate.
655    int m = -distance % length;
656    m = (m < 0) ? m + length : m;
657    // The current index of what will become the first element of the rotated section.
658    int newFirstIndex = m + fromIndex;
659    if (newFirstIndex == fromIndex) {
660      return;
661    }
662
663    reverse(array, fromIndex, newFirstIndex);
664    reverse(array, newFirstIndex, toIndex);
665    reverse(array, fromIndex, toIndex);
666  }
667
668  /**
669   * Returns an array containing each value of {@code collection}, converted to a {@code long} value
670   * in the manner of {@link Number#longValue}.
671   *
672   * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}.
673   * Calling this method is as thread-safe as calling that method.
674   *
675   * @param collection a collection of {@code Number} instances
676   * @return an array containing the same values as {@code collection}, in the same order, converted
677   *     to primitives
678   * @throws NullPointerException if {@code collection} or any of its elements is null
679   * @since 1.0 (parameter was {@code Collection<Long>} before 12.0)
680   */
681  public static long[] toArray(Collection<? extends Number> collection) {
682    if (collection instanceof LongArrayAsList) {
683      return ((LongArrayAsList) collection).toLongArray();
684    }
685
686    Object[] boxedArray = collection.toArray();
687    int len = boxedArray.length;
688    long[] array = new long[len];
689    for (int i = 0; i < len; i++) {
690      // checkNotNull for GWT (do not optimize)
691      array[i] = ((Number) checkNotNull(boxedArray[i])).longValue();
692    }
693    return array;
694  }
695
696  /**
697   * Returns a fixed-size list backed by the specified array, similar to {@link
698   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
699   * set a value to {@code null} will result in a {@link NullPointerException}.
700   *
701   * <p>The returned list maintains the values, but not the identities, of {@code Long} objects
702   * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
703   * the returned list is unspecified.
704   *
705   * <p>The returned list is serializable.
706   *
707   * <p><b>Note:</b> when possible, you should represent your data as an {@link ImmutableLongArray}
708   * instead, which has an {@link ImmutableLongArray#asList asList} view.
709   *
710   * @param backingArray the array to back the list
711   * @return a list view of the array
712   */
713  public static List<Long> asList(long... backingArray) {
714    if (backingArray.length == 0) {
715      return Collections.emptyList();
716    }
717    return new LongArrayAsList(backingArray);
718  }
719
720  @GwtCompatible
721  private static class LongArrayAsList extends AbstractList<Long>
722      implements RandomAccess, Serializable {
723    final long[] array;
724    final int start;
725    final int end;
726
727    LongArrayAsList(long[] array) {
728      this(array, 0, array.length);
729    }
730
731    LongArrayAsList(long[] array, int start, int end) {
732      this.array = array;
733      this.start = start;
734      this.end = end;
735    }
736
737    @Override
738    public int size() {
739      return end - start;
740    }
741
742    @Override
743    public boolean isEmpty() {
744      return false;
745    }
746
747    @Override
748    public Long get(int index) {
749      checkElementIndex(index, size());
750      return array[start + index];
751    }
752
753    @Override
754    public Spliterator.OfLong spliterator() {
755      return Spliterators.spliterator(array, start, end, 0);
756    }
757
758    @Override
759    public boolean contains(@Nullable Object target) {
760      // Overridden to prevent a ton of boxing
761      return (target instanceof Long) && Longs.indexOf(array, (Long) target, start, end) != -1;
762    }
763
764    @Override
765    public int indexOf(@Nullable Object target) {
766      // Overridden to prevent a ton of boxing
767      if (target instanceof Long) {
768        int i = Longs.indexOf(array, (Long) target, start, end);
769        if (i >= 0) {
770          return i - start;
771        }
772      }
773      return -1;
774    }
775
776    @Override
777    public int lastIndexOf(@Nullable Object target) {
778      // Overridden to prevent a ton of boxing
779      if (target instanceof Long) {
780        int i = Longs.lastIndexOf(array, (Long) target, start, end);
781        if (i >= 0) {
782          return i - start;
783        }
784      }
785      return -1;
786    }
787
788    @Override
789    public Long set(int index, Long element) {
790      checkElementIndex(index, size());
791      long oldValue = array[start + index];
792      // checkNotNull for GWT (do not optimize)
793      array[start + index] = checkNotNull(element);
794      return oldValue;
795    }
796
797    @Override
798    public List<Long> subList(int fromIndex, int toIndex) {
799      int size = size();
800      checkPositionIndexes(fromIndex, toIndex, size);
801      if (fromIndex == toIndex) {
802        return Collections.emptyList();
803      }
804      return new LongArrayAsList(array, start + fromIndex, start + toIndex);
805    }
806
807    @Override
808    public boolean equals(@Nullable Object object) {
809      if (object == this) {
810        return true;
811      }
812      if (object instanceof LongArrayAsList) {
813        LongArrayAsList that = (LongArrayAsList) object;
814        int size = size();
815        if (that.size() != size) {
816          return false;
817        }
818        for (int i = 0; i < size; i++) {
819          if (array[start + i] != that.array[that.start + i]) {
820            return false;
821          }
822        }
823        return true;
824      }
825      return super.equals(object);
826    }
827
828    @Override
829    public int hashCode() {
830      int result = 1;
831      for (int i = start; i < end; i++) {
832        result = 31 * result + Longs.hashCode(array[i]);
833      }
834      return result;
835    }
836
837    @Override
838    public String toString() {
839      StringBuilder builder = new StringBuilder(size() * 10);
840      builder.append('[').append(array[start]);
841      for (int i = start + 1; i < end; i++) {
842        builder.append(", ").append(array[i]);
843      }
844      return builder.append(']').toString();
845    }
846
847    long[] toLongArray() {
848      return Arrays.copyOfRange(array, start, end);
849    }
850
851    private static final long serialVersionUID = 0;
852  }
853}