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