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