001/*
002 * Copyright (C) 2008 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.primitives;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkElementIndex;
019import static com.google.common.base.Preconditions.checkNotNull;
020import static com.google.common.base.Preconditions.checkPositionIndexes;
021
022import com.google.common.annotations.Beta;
023import com.google.common.annotations.GwtCompatible;
024import com.google.common.base.Converter;
025import java.io.Serializable;
026import java.util.AbstractList;
027import java.util.Arrays;
028import java.util.Collection;
029import java.util.Collections;
030import java.util.Comparator;
031import java.util.List;
032import java.util.RandomAccess;
033import javax.annotation.CheckForNull;
034import javax.annotation.Nullable;
035
036/**
037 * Static utility methods pertaining to {@code long} primitives, that are not already found in
038 * either {@link Long} or {@link Arrays}.
039 *
040 * <p>See the Guava User Guide article on
041 * <a href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>.
042 *
043 * @author Kevin Bourrillion
044 * @since 1.0
045 */
046@GwtCompatible
047public final class Longs {
048  private Longs() {}
049
050  /**
051   * The number of bytes required to represent a primitive {@code long} value.
052   *
053   * <p><b>Java 8 users:</b> use {@link Long#BYTES} instead.
054   */
055  public static final int BYTES = Long.SIZE / Byte.SIZE;
056
057  /**
058   * The largest power of two that can be represented as a {@code long}.
059   *
060   * @since 10.0
061   */
062  public static final long MAX_POWER_OF_TWO = 1L << (Long.SIZE - 2);
063
064  /**
065   * Returns a hash code for {@code value}; equal to the result of invoking
066   * {@code ((Long) value).hashCode()}.
067   *
068   * <p>This method always return the value specified by {@link Long#hashCode()} in java, which
069   * might be different from {@code ((Long) value).hashCode()} in GWT because
070   * {@link Long#hashCode()} in GWT does not obey the JRE contract.
071   *
072   * <p><b>Java 8 users:</b> use {@link Long#hashCode(long)} instead.
073   *
074   * @param value a primitive {@code long} value
075   * @return a hash code for the value
076   */
077  public static int hashCode(long value) {
078    return (int) (value ^ (value >>> 32));
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 for Java 7 and later:</b> this method 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  public static int compare(long a, long b) {
094    return (a < b) ? -1 : ((a > b) ? 1 : 0);
095  }
096
097  /**
098   * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}.
099   *
100   * @param array an array of {@code long} values, possibly empty
101   * @param target a primitive {@code long} value
102   * @return {@code true} if {@code array[i] == target} for some value of {@code
103   *     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
138   * target} within {@code array}, or {@code -1} if there is no such occurrence.
139   *
140   * <p>More formally, returns the lowest index {@code i} such that
141   * {@code Arrays.copyOfRange(array, i, i + target.length)} contains exactly the same elements as
142   * {@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
231   * {@code value} is greater than {@code max}, {@code max} is returned.
232   *
233   * @param value the {@code long} value to constrain
234   * @param min the lower bound (inclusive) of the range to constrain {@code value} to
235   * @param max the upper bound (inclusive) of the range to constrain {@code value} to
236   * @throws IllegalArgumentException if {@code min > max}
237   * @since 21.0
238   */
239  @Beta
240  public static long constrainToRange(long value, long min, long max) {
241    checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max);
242    return Math.min(Math.max(value, min), max);
243  }
244
245  /**
246   * Returns the values from each provided array combined into a single array. For example,
247   * {@code concat(new long[] {a, b}, new long[] {}, new long[] {c}} returns the array
248   * {@code {a, b, c}}.
249   *
250   * @param arrays zero or more {@code long} arrays
251   * @return a single array containing all the values from the source arrays, in order
252   */
253  public static long[] concat(long[]... arrays) {
254    int length = 0;
255    for (long[] array : arrays) {
256      length += array.length;
257    }
258    long[] result = new long[length];
259    int pos = 0;
260    for (long[] array : arrays) {
261      System.arraycopy(array, 0, result, pos, array.length);
262      pos += array.length;
263    }
264    return result;
265  }
266
267  /**
268   * Returns a big-endian representation of {@code value} in an 8-element byte array; equivalent to
269   * {@code ByteBuffer.allocate(8).putLong(value).array()}. For example, the input value
270   * {@code 0x1213141516171819L} would yield the byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16,
271   * 0x17, 0x18, 0x19}}.
272   *
273   * <p>If you need to convert and concatenate several values (possibly even of different types),
274   * use a shared {@link java.nio.ByteBuffer} instance, or use
275   * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer.
276   */
277  public static byte[] toByteArray(long value) {
278    // Note that this code needs to stay compatible with GWT, which has known
279    // bugs when narrowing byte casts of long values occur.
280    byte[] result = new byte[8];
281    for (int i = 7; i >= 0; i--) {
282      result[i] = (byte) (value & 0xffL);
283      value >>= 8;
284    }
285    return result;
286  }
287
288  /**
289   * Returns the {@code long} value whose big-endian representation is stored in the first 8 bytes
290   * of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getLong()}. For example, the
291   * input byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}} would yield the
292   * {@code long} value {@code 0x1213141516171819L}.
293   *
294   * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more
295   * flexibility at little cost in readability.
296   *
297   * @throws IllegalArgumentException if {@code bytes} has fewer than 8 elements
298   */
299  public static long fromByteArray(byte[] bytes) {
300    checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES);
301    return fromBytes(
302        bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]);
303  }
304
305  /**
306   * Returns the {@code long} value whose byte representation is the given 8 bytes, in big-endian
307   * order; equivalent to {@code Longs.fromByteArray(new byte[] {b1, b2, b3, b4, b5, b6, b7, b8})}.
308   *
309   * @since 7.0
310   */
311  public static long fromBytes(
312      byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7, byte b8) {
313    return (b1 & 0xFFL) << 56
314        | (b2 & 0xFFL) << 48
315        | (b3 & 0xFFL) << 40
316        | (b4 & 0xFFL) << 32
317        | (b5 & 0xFFL) << 24
318        | (b6 & 0xFFL) << 16
319        | (b7 & 0xFFL) << 8
320        | (b8 & 0xFFL);
321  }
322
323  private static final byte[] asciiDigits = createAsciiDigits();
324
325  private static byte[] createAsciiDigits() {
326    byte[] result = new byte[128];
327    Arrays.fill(result, (byte) -1);
328    for (int i = 0; i <= 9; i++) {
329      result['0' + i] = (byte) i;
330    }
331    for (int i = 0; i <= 26; i++) {
332      result['A' + i] = (byte) (10 + i);
333      result['a' + i] = (byte) (10 + i);
334    }
335    return result;
336  }
337
338  private static int digit(char c) {
339    return (c < 128) ? asciiDigits[c] : -1;
340  }
341
342  /**
343   * Parses the specified string as a signed decimal long value. The ASCII character {@code '-'}
344   * (<code>'&#92;u002D'</code>) is recognized as the minus sign.
345   *
346   * <p>Unlike {@link Long#parseLong(String)}, this method returns {@code null} instead of throwing
347   * an exception if parsing fails. Additionally, this method only accepts ASCII digits, and returns
348   * {@code null} if non-ASCII digits are present in the string.
349   *
350   * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite
351   * the change to {@link Long#parseLong(String)} for that version.
352   *
353   * @param string the string representation of a long value
354   * @return the long value represented by {@code string}, or {@code null} if {@code string} has a
355   *     length of zero or cannot be parsed as a long value
356   * @since 14.0
357   */
358  @Beta
359  @Nullable
360  @CheckForNull
361  public static Long tryParse(String string) {
362    return tryParse(string, 10);
363  }
364
365  /**
366   * Parses the specified string as a signed long value using the specified radix. The ASCII
367   * character {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the minus sign.
368   *
369   * <p>Unlike {@link Long#parseLong(String, int)}, this method returns {@code null} instead of
370   * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits,
371   * and returns {@code null} if non-ASCII digits are present in the string.
372   *
373   * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite
374   * the change to {@link Long#parseLong(String, int)} for that version.
375   *
376   * @param string the string representation of an long value
377   * @param radix the radix to use when parsing
378   * @return the long value represented by {@code string} using {@code radix}, or {@code null} if
379   *     {@code string} has a length of zero or cannot be parsed as a long value
380   * @throws IllegalArgumentException if {@code radix < Character.MIN_RADIX} or
381   *     {@code radix > Character.MAX_RADIX}
382   * @since 19.0
383   */
384  @Beta
385  @Nullable
386  @CheckForNull
387  public static Long tryParse(String string, int radix) {
388    if (checkNotNull(string).isEmpty()) {
389      return null;
390    }
391    if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
392      throw new IllegalArgumentException(
393          "radix must be between MIN_RADIX and MAX_RADIX but was " + radix);
394    }
395    boolean negative = string.charAt(0) == '-';
396    int index = negative ? 1 : 0;
397    if (index == string.length()) {
398      return null;
399    }
400    int digit = digit(string.charAt(index++));
401    if (digit < 0 || digit >= radix) {
402      return null;
403    }
404    long accum = -digit;
405
406    long cap = Long.MIN_VALUE / radix;
407
408    while (index < string.length()) {
409      digit = digit(string.charAt(index++));
410      if (digit < 0 || digit >= radix || accum < cap) {
411        return null;
412      }
413      accum *= radix;
414      if (accum < Long.MIN_VALUE + digit) {
415        return null;
416      }
417      accum -= digit;
418    }
419
420    if (negative) {
421      return accum;
422    } else if (accum == Long.MIN_VALUE) {
423      return null;
424    } else {
425      return -accum;
426    }
427  }
428
429  private static final class LongConverter extends Converter<String, Long> implements Serializable {
430    static final LongConverter INSTANCE = new LongConverter();
431
432    @Override
433    protected Long doForward(String value) {
434      return Long.decode(value);
435    }
436
437    @Override
438    protected String doBackward(Long value) {
439      return value.toString();
440    }
441
442    @Override
443    public String toString() {
444      return "Longs.stringConverter()";
445    }
446
447    private Object readResolve() {
448      return INSTANCE;
449    }
450
451    private static final long serialVersionUID = 1;
452  }
453
454  /**
455   * Returns a serializable converter object that converts between strings and longs using
456   * {@link Long#decode} and {@link Long#toString()}. The returned converter throws
457   * {@link NumberFormatException} if the input string is invalid.
458   *
459   * <p><b>Warning:</b> please see {@link Long#decode} to understand exactly how strings are parsed.
460   * For example, the string {@code "0123"} is treated as <i>octal</i> and converted to the value
461   * {@code 83L}.
462   *
463   * @since 16.0
464   */
465  @Beta
466  public static Converter<String, Long> stringConverter() {
467    return LongConverter.INSTANCE;
468  }
469
470  /**
471   * Returns an array containing the same values as {@code array}, but guaranteed to be of a
472   * specified minimum length. If {@code array} already has a length of at least {@code minLength},
473   * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is
474   * returned, containing the values of {@code array}, and zeroes in the remaining places.
475   *
476   * @param array the source array
477   * @param minLength the minimum length the returned array must guarantee
478   * @param padding an extra amount to "grow" the array by if growth is necessary
479   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative
480   * @return an array containing the values of {@code array}, with guaranteed minimum length
481   *     {@code minLength}
482   */
483  public static long[] ensureCapacity(long[] array, int minLength, int padding) {
484    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
485    checkArgument(padding >= 0, "Invalid padding: %s", padding);
486    return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array;
487  }
488
489  /**
490   * Returns a string containing the supplied {@code long} values separated by {@code separator}.
491   * For example, {@code join("-", 1L, 2L, 3L)} returns the string {@code "1-2-3"}.
492   *
493   * @param separator the text that should appear between consecutive values in the resulting string
494   *     (but not at the start or end)
495   * @param array an array of {@code long} values, possibly empty
496   */
497  public static String join(String separator, long... array) {
498    checkNotNull(separator);
499    if (array.length == 0) {
500      return "";
501    }
502
503    // For pre-sizing a builder, just get the right order of magnitude
504    StringBuilder builder = new StringBuilder(array.length * 10);
505    builder.append(array[0]);
506    for (int i = 1; i < array.length; i++) {
507      builder.append(separator).append(array[i]);
508    }
509    return builder.toString();
510  }
511
512  /**
513   * Returns a comparator that compares two {@code long} arrays <a
514   * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it
515   * compares, using {@link #compare(long, long)}), the first pair of values that follow any common
516   * prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For
517   * example, {@code [] < [1L] < [1L, 2L] < [2L]}.
518   *
519   * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
520   * support only identity equality), but it is consistent with
521   * {@link Arrays#equals(long[], long[])}.
522   *
523   * @since 2.0
524   */
525  public static Comparator<long[]> lexicographicalComparator() {
526    return LexicographicalComparator.INSTANCE;
527  }
528
529  private enum LexicographicalComparator implements Comparator<long[]> {
530    INSTANCE;
531
532    @Override
533    public int compare(long[] left, long[] right) {
534      int minLength = Math.min(left.length, right.length);
535      for (int i = 0; i < minLength; i++) {
536        int result = Longs.compare(left[i], right[i]);
537        if (result != 0) {
538          return result;
539        }
540      }
541      return left.length - right.length;
542    }
543
544    @Override
545    public String toString() {
546      return "Longs.lexicographicalComparator()";
547    }
548  }
549
550  /**
551   * Returns an array containing each value of {@code collection}, converted to a {@code long} value
552   * in the manner of {@link Number#longValue}.
553   *
554   * <p>Elements are copied from the argument collection as if by {@code
555   * collection.toArray()}. Calling this method is as thread-safe as calling that method.
556   *
557   * @param collection a collection of {@code Number} instances
558   * @return an array containing the same values as {@code collection}, in the same order, converted
559   *     to primitives
560   * @throws NullPointerException if {@code collection} or any of its elements is null
561   * @since 1.0 (parameter was {@code Collection<Long>} before 12.0)
562   */
563  public static long[] toArray(Collection<? extends Number> collection) {
564    if (collection instanceof LongArrayAsList) {
565      return ((LongArrayAsList) collection).toLongArray();
566    }
567
568    Object[] boxedArray = collection.toArray();
569    int len = boxedArray.length;
570    long[] array = new long[len];
571    for (int i = 0; i < len; i++) {
572      // checkNotNull for GWT (do not optimize)
573      array[i] = ((Number) checkNotNull(boxedArray[i])).longValue();
574    }
575    return array;
576  }
577
578  /**
579   * Returns a fixed-size list backed by the specified array, similar to
580   * {@link Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any
581   * attempt to set a value to {@code null} will result in a {@link NullPointerException}.
582   *
583   * <p>The returned list maintains the values, but not the identities, of {@code Long} objects
584   * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
585   * the returned list is unspecified.
586   *
587   * @param backingArray the array to back the list
588   * @return a list view of the array
589   */
590  public static List<Long> asList(long... backingArray) {
591    if (backingArray.length == 0) {
592      return Collections.emptyList();
593    }
594    return new LongArrayAsList(backingArray);
595  }
596
597  @GwtCompatible
598  private static class LongArrayAsList extends AbstractList<Long>
599      implements RandomAccess, Serializable {
600    final long[] array;
601    final int start;
602    final int end;
603
604    LongArrayAsList(long[] array) {
605      this(array, 0, array.length);
606    }
607
608    LongArrayAsList(long[] array, int start, int end) {
609      this.array = array;
610      this.start = start;
611      this.end = end;
612    }
613
614    @Override
615    public int size() {
616      return end - start;
617    }
618
619    @Override
620    public boolean isEmpty() {
621      return false;
622    }
623
624    @Override
625    public Long get(int index) {
626      checkElementIndex(index, size());
627      return array[start + index];
628    }
629
630    @Override
631    public boolean contains(Object target) {
632      // Overridden to prevent a ton of boxing
633      return (target instanceof Long) && Longs.indexOf(array, (Long) target, start, end) != -1;
634    }
635
636    @Override
637    public int indexOf(Object target) {
638      // Overridden to prevent a ton of boxing
639      if (target instanceof Long) {
640        int i = Longs.indexOf(array, (Long) target, start, end);
641        if (i >= 0) {
642          return i - start;
643        }
644      }
645      return -1;
646    }
647
648    @Override
649    public int lastIndexOf(Object target) {
650      // Overridden to prevent a ton of boxing
651      if (target instanceof Long) {
652        int i = Longs.lastIndexOf(array, (Long) target, start, end);
653        if (i >= 0) {
654          return i - start;
655        }
656      }
657      return -1;
658    }
659
660    @Override
661    public Long set(int index, Long element) {
662      checkElementIndex(index, size());
663      long oldValue = array[start + index];
664      // checkNotNull for GWT (do not optimize)
665      array[start + index] = checkNotNull(element);
666      return oldValue;
667    }
668
669    @Override
670    public List<Long> subList(int fromIndex, int toIndex) {
671      int size = size();
672      checkPositionIndexes(fromIndex, toIndex, size);
673      if (fromIndex == toIndex) {
674        return Collections.emptyList();
675      }
676      return new LongArrayAsList(array, start + fromIndex, start + toIndex);
677    }
678
679    @Override
680    public boolean equals(@Nullable Object object) {
681      if (object == this) {
682        return true;
683      }
684      if (object instanceof LongArrayAsList) {
685        LongArrayAsList that = (LongArrayAsList) object;
686        int size = size();
687        if (that.size() != size) {
688          return false;
689        }
690        for (int i = 0; i < size; i++) {
691          if (array[start + i] != that.array[that.start + i]) {
692            return false;
693          }
694        }
695        return true;
696      }
697      return super.equals(object);
698    }
699
700    @Override
701    public int hashCode() {
702      int result = 1;
703      for (int i = start; i < end; i++) {
704        result = 31 * result + Longs.hashCode(array[i]);
705      }
706      return result;
707    }
708
709    @Override
710    public String toString() {
711      StringBuilder builder = new StringBuilder(size() * 10);
712      builder.append('[').append(array[start]);
713      for (int i = start + 1; i < end; i++) {
714        builder.append(", ").append(array[i]);
715      }
716      return builder.append(']').toString();
717    }
718
719    long[] toLongArray() {
720      return Arrays.copyOfRange(array, start, end);
721    }
722
723    private static final long serialVersionUID = 0;
724  }
725}