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;
026
027import java.io.Serializable;
028import java.util.AbstractList;
029import java.util.Arrays;
030import java.util.Collection;
031import java.util.Collections;
032import java.util.Comparator;
033import java.util.List;
034import java.util.RandomAccess;
035
036/**
037 * Static utility methods pertaining to {@code long} primitives, that are not
038 * already found in either {@link Long} or {@link Arrays}.
039 *
040 * <p>See the Guava User Guide article on <a href=
041 * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
042 * 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}
053   * value.
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
069   * Long#hashCode()} in java, which might be different from
070   * {@code ((Long) value).hashCode()} in GWT because {@link Long#hashCode()}
071   * in GWT does not obey the JRE contract.
072   *
073   * @param value a primitive {@code long} value
074   * @return a hash code for the value
075   */
076  public static int hashCode(long value) {
077    return (int) (value ^ (value >>> 32));
078  }
079
080  /**
081   * Compares the two specified {@code long} values. The sign of the value
082   * returned is the same as that of {@code ((Long) a).compareTo(b)}.
083   *
084   * @param a the first {@code long} to compare
085   * @param b the second {@code long} to compare
086   * @return a negative value if {@code a} is less than {@code b}; a positive
087   *     value if {@code a} is greater than {@code b}; or zero if they are equal
088   */
089  public static int compare(long a, long b) {
090    return (a < b) ? -1 : ((a > b) ? 1 : 0);
091  }
092
093  /**
094   * Returns {@code true} if {@code target} is present as an element anywhere in
095   * {@code array}.
096   *
097   * @param array an array of {@code long} values, possibly empty
098   * @param target a primitive {@code long} value
099   * @return {@code true} if {@code array[i] == target} for some value of {@code
100   *     i}
101   */
102  public static boolean contains(long[] array, long target) {
103    for (long value : array) {
104      if (value == target) {
105        return true;
106      }
107    }
108    return false;
109  }
110
111  /**
112   * Returns the index of the first appearance of the value {@code target} in
113   * {@code array}.
114   *
115   * @param array an array of {@code long} values, possibly empty
116   * @param target a primitive {@code long} value
117   * @return the least index {@code i} for which {@code array[i] == target}, or
118   *     {@code -1} if no such index exists.
119   */
120  public static int indexOf(long[] array, long target) {
121    return indexOf(array, target, 0, array.length);
122  }
123
124  // TODO(kevinb): consider making this public
125  private static int indexOf(
126      long[] array, long target, int start, int end) {
127    for (int i = start; i < end; i++) {
128      if (array[i] == target) {
129        return i;
130      }
131    }
132    return -1;
133  }
134
135  /**
136   * Returns the start position of the first occurrence of the specified {@code
137   * target} within {@code array}, or {@code -1} if there is no such occurrence.
138   *
139   * <p>More formally, returns the lowest index {@code i} such that {@code
140   * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
141   * the same elements as {@code target}.
142   *
143   * @param array the array to search for the sequence {@code target}
144   * @param target the array to search for as a sub-sequence of {@code array}
145   */
146  public static int indexOf(long[] array, long[] target) {
147    checkNotNull(array, "array");
148    checkNotNull(target, "target");
149    if (target.length == 0) {
150      return 0;
151    }
152
153    outer:
154    for (int i = 0; i < array.length - target.length + 1; i++) {
155      for (int j = 0; j < target.length; j++) {
156        if (array[i + j] != target[j]) {
157          continue outer;
158        }
159      }
160      return i;
161    }
162    return -1;
163  }
164
165  /**
166   * Returns the index of the last appearance of the value {@code target} in
167   * {@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},
172   *     or {@code -1} if no 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(
180      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
194   *     every other value in 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
213   *     every other value 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 values from each provided array combined into a single array.
229   * For example, {@code concat(new long[] {a, b}, new long[] {}, new
230   * long[] {c}} returns the array {@code {a, b, c}}.
231   *
232   * @param arrays zero or more {@code long} arrays
233   * @return a single array containing all the values from the source arrays, in
234   *     order
235   */
236  public static long[] concat(long[]... arrays) {
237    int length = 0;
238    for (long[] array : arrays) {
239      length += array.length;
240    }
241    long[] result = new long[length];
242    int pos = 0;
243    for (long[] array : arrays) {
244      System.arraycopy(array, 0, result, pos, array.length);
245      pos += array.length;
246    }
247    return result;
248  }
249
250  /**
251   * Returns a big-endian representation of {@code value} in an 8-element byte
252   * array; equivalent to {@code ByteBuffer.allocate(8).putLong(value).array()}.
253   * For example, the input value {@code 0x1213141516171819L} would yield the
254   * byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}}.
255   *
256   * <p>If you need to convert and concatenate several values (possibly even of
257   * different types), use a shared {@link java.nio.ByteBuffer} instance, or use
258   * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable
259   * buffer.
260   */
261  public static byte[] toByteArray(long value) {
262    // Note that this code needs to stay compatible with GWT, which has known
263    // bugs when narrowing byte casts of long values occur.
264    byte[] result = new byte[8];
265    for (int i = 7; i >= 0; i--) {
266      result[i] = (byte) (value & 0xffL);
267      value >>= 8;
268    }
269    return result;
270  }
271
272  /**
273   * Returns the {@code long} value whose big-endian representation is
274   * stored in the first 8 bytes of {@code bytes}; equivalent to {@code
275   * ByteBuffer.wrap(bytes).getLong()}. For example, the input byte array
276   * {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}} would yield the
277   * {@code long} value {@code 0x1213141516171819L}.
278   *
279   * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that
280   * library exposes much more flexibility at little cost in readability.
281   *
282   * @throws IllegalArgumentException if {@code bytes} has fewer than 8
283   *     elements
284   */
285  public static long fromByteArray(byte[] bytes) {
286    checkArgument(bytes.length >= BYTES,
287        "array too small: %s < %s", bytes.length, BYTES);
288    return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3],
289        bytes[4], bytes[5], bytes[6], bytes[7]) ;
290  }
291
292  /**
293   * Returns the {@code long} value whose byte representation is the given 8
294   * bytes, in big-endian order; equivalent to {@code Longs.fromByteArray(new
295   * byte[] {b1, b2, b3, b4, b5, b6, b7, b8})}.
296   *
297   * @since 7.0
298   */
299  public static long fromBytes(byte b1, byte b2, byte b3, byte b4,
300      byte b5, byte b6, byte b7, byte b8) {
301    return (b1 & 0xFFL) << 56
302        | (b2 & 0xFFL) << 48
303        | (b3 & 0xFFL) << 40
304        | (b4 & 0xFFL) << 32
305        | (b5 & 0xFFL) << 24
306        | (b6 & 0xFFL) << 16
307        | (b7 & 0xFFL) << 8
308        | (b8 & 0xFFL);
309  }
310
311  /**
312   * Parses the specified string as a signed decimal long value. The ASCII
313   * character {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the
314   * minus sign.
315   *
316   * <p>Unlike {@link Long#parseLong(String)}, this method returns
317   * {@code null} instead of throwing an exception if parsing fails.
318   *
319   * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even
320   * under JDK 7, despite the change to {@link Long#parseLong(String)} for
321   * that version.
322   *
323   * @param string the string representation of a long value
324   * @return the long value represented by {@code string}, or {@code null} if
325   *     {@code string} has a length of zero or cannot be parsed as a long
326   *     value
327   * @since 14.0
328   */
329  @Beta
330  public static Long tryParse(String string) {
331    if (checkNotNull(string).isEmpty()) {
332      return null;
333    }
334    boolean negative = string.charAt(0) == '-';
335    int index = negative ? 1 : 0;
336    if (index == string.length()) {
337      return null;
338    }
339    int digit = string.charAt(index++) - '0';
340    if (digit < 0 || digit > 9) {
341      return null;
342    }
343    long accum = -digit;
344    while (index < string.length()) {
345      digit = string.charAt(index++) - '0';
346      if (digit < 0 || digit > 9 || accum < Long.MIN_VALUE / 10) {
347        return null;
348      }
349      accum *= 10;
350      if (accum < Long.MIN_VALUE + digit) {
351        return null;
352      }
353      accum -= digit;
354    }
355
356    if (negative) {
357      return accum;
358    } else if (accum == Long.MIN_VALUE) {
359      return null;
360    } else {
361      return -accum;
362    }
363  }
364
365  /**
366   * Returns an array containing the same values as {@code array}, but
367   * guaranteed to be of a specified minimum length. If {@code array} already
368   * has a length of at least {@code minLength}, it is returned directly.
369   * Otherwise, a new array of size {@code minLength + padding} is returned,
370   * containing the values of {@code array}, and zeroes in the remaining places.
371   *
372   * @param array the source array
373   * @param minLength the minimum length the returned array must guarantee
374   * @param padding an extra amount to "grow" the array by if growth is
375   *     necessary
376   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is
377   *     negative
378   * @return an array containing the values of {@code array}, with guaranteed
379   *     minimum length {@code minLength}
380   */
381  public static long[] ensureCapacity(
382      long[] array, int minLength, int padding) {
383    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
384    checkArgument(padding >= 0, "Invalid padding: %s", padding);
385    return (array.length < minLength)
386        ? copyOf(array, minLength + padding)
387        : array;
388  }
389
390  // Arrays.copyOf() requires Java 6
391  private static long[] copyOf(long[] original, int length) {
392    long[] copy = new long[length];
393    System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
394    return copy;
395  }
396
397  /**
398   * Returns a string containing the supplied {@code long} values separated
399   * by {@code separator}. For example, {@code join("-", 1L, 2L, 3L)} returns
400   * the string {@code "1-2-3"}.
401   *
402   * @param separator the text that should appear between consecutive values in
403   *     the resulting string (but not at the start or end)
404   * @param array an array of {@code long} values, possibly empty
405   */
406  public static String join(String separator, long... array) {
407    checkNotNull(separator);
408    if (array.length == 0) {
409      return "";
410    }
411
412    // For pre-sizing a builder, just get the right order of magnitude
413    StringBuilder builder = new StringBuilder(array.length * 10);
414    builder.append(array[0]);
415    for (int i = 1; i < array.length; i++) {
416      builder.append(separator).append(array[i]);
417    }
418    return builder.toString();
419  }
420
421  /**
422   * Returns a comparator that compares two {@code long} arrays
423   * lexicographically. That is, it compares, using {@link
424   * #compare(long, long)}), the first pair of values that follow any
425   * common prefix, or when one array is a prefix of the other, treats the
426   * shorter array as the lesser. For example,
427   * {@code [] < [1L] < [1L, 2L] < [2L]}.
428   *
429   * <p>The returned comparator is inconsistent with {@link
430   * Object#equals(Object)} (since arrays support only identity equality), but
431   * it is consistent with {@link Arrays#equals(long[], long[])}.
432   *
433   * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
434   *     Lexicographical order article at Wikipedia</a>
435   * @since 2.0
436   */
437  public static Comparator<long[]> lexicographicalComparator() {
438    return LexicographicalComparator.INSTANCE;
439  }
440
441  private enum LexicographicalComparator implements Comparator<long[]> {
442    INSTANCE;
443
444    @Override
445    public int compare(long[] left, long[] right) {
446      int minLength = Math.min(left.length, right.length);
447      for (int i = 0; i < minLength; i++) {
448        int result = Longs.compare(left[i], right[i]);
449        if (result != 0) {
450          return result;
451        }
452      }
453      return left.length - right.length;
454    }
455  }
456
457  /**
458   * Returns an array containing each value of {@code collection}, converted to
459   * a {@code long} value in the manner of {@link Number#longValue}.
460   *
461   * <p>Elements are copied from the argument collection as if by {@code
462   * collection.toArray()}.  Calling this method is as thread-safe as calling
463   * that method.
464   *
465   * @param collection a collection of {@code Number} instances
466   * @return an array containing the same values as {@code collection}, in the
467   *     same order, converted to primitives
468   * @throws NullPointerException if {@code collection} or any of its elements
469   *     is null
470   * @since 1.0 (parameter was {@code Collection<Long>} before 12.0)
471   */
472  public static long[] toArray(Collection<? extends Number> collection) {
473    if (collection instanceof LongArrayAsList) {
474      return ((LongArrayAsList) collection).toLongArray();
475    }
476
477    Object[] boxedArray = collection.toArray();
478    int len = boxedArray.length;
479    long[] array = new long[len];
480    for (int i = 0; i < len; i++) {
481      // checkNotNull for GWT (do not optimize)
482      array[i] = ((Number) checkNotNull(boxedArray[i])).longValue();
483    }
484    return array;
485  }
486
487  /**
488   * Returns a fixed-size list backed by the specified array, similar to {@link
489   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
490   * but any attempt to set a value to {@code null} will result in a {@link
491   * NullPointerException}.
492   *
493   * <p>The returned list maintains the values, but not the identities, of
494   * {@code Long} objects written to or read from it.  For example, whether
495   * {@code list.get(0) == list.get(0)} is true for the returned list is
496   * unspecified.
497   *
498   * @param backingArray the array to back the list
499   * @return a list view of the array
500   */
501  public static List<Long> asList(long... backingArray) {
502    if (backingArray.length == 0) {
503      return Collections.emptyList();
504    }
505    return new LongArrayAsList(backingArray);
506  }
507
508  @GwtCompatible
509  private static class LongArrayAsList extends AbstractList<Long>
510      implements RandomAccess, Serializable {
511    final long[] array;
512    final int start;
513    final int end;
514
515    LongArrayAsList(long[] array) {
516      this(array, 0, array.length);
517    }
518
519    LongArrayAsList(long[] array, int start, int end) {
520      this.array = array;
521      this.start = start;
522      this.end = end;
523    }
524
525    @Override public int size() {
526      return end - start;
527    }
528
529    @Override public boolean isEmpty() {
530      return false;
531    }
532
533    @Override public Long get(int index) {
534      checkElementIndex(index, size());
535      return array[start + index];
536    }
537
538    @Override public boolean contains(Object target) {
539      // Overridden to prevent a ton of boxing
540      return (target instanceof Long)
541          && Longs.indexOf(array, (Long) target, start, end) != -1;
542    }
543
544    @Override public int indexOf(Object target) {
545      // Overridden to prevent a ton of boxing
546      if (target instanceof Long) {
547        int i = Longs.indexOf(array, (Long) target, start, end);
548        if (i >= 0) {
549          return i - start;
550        }
551      }
552      return -1;
553    }
554
555    @Override public int lastIndexOf(Object target) {
556      // Overridden to prevent a ton of boxing
557      if (target instanceof Long) {
558        int i = Longs.lastIndexOf(array, (Long) target, start, end);
559        if (i >= 0) {
560          return i - start;
561        }
562      }
563      return -1;
564    }
565
566    @Override public Long set(int index, Long element) {
567      checkElementIndex(index, size());
568      long oldValue = array[start + index];
569      // checkNotNull for GWT (do not optimize)
570      array[start + index] = checkNotNull(element);
571      return oldValue;
572    }
573
574    @Override public List<Long> subList(int fromIndex, int toIndex) {
575      int size = size();
576      checkPositionIndexes(fromIndex, toIndex, size);
577      if (fromIndex == toIndex) {
578        return Collections.emptyList();
579      }
580      return new LongArrayAsList(array, start + fromIndex, start + toIndex);
581    }
582
583    @Override public boolean equals(Object object) {
584      if (object == this) {
585        return true;
586      }
587      if (object instanceof LongArrayAsList) {
588        LongArrayAsList that = (LongArrayAsList) object;
589        int size = size();
590        if (that.size() != size) {
591          return false;
592        }
593        for (int i = 0; i < size; i++) {
594          if (array[start + i] != that.array[that.start + i]) {
595            return false;
596          }
597        }
598        return true;
599      }
600      return super.equals(object);
601    }
602
603    @Override public int hashCode() {
604      int result = 1;
605      for (int i = start; i < end; i++) {
606        result = 31 * result + Longs.hashCode(array[i]);
607      }
608      return result;
609    }
610
611    @Override public String toString() {
612      StringBuilder builder = new StringBuilder(size() * 10);
613      builder.append('[').append(array[start]);
614      for (int i = start + 1; i < end; i++) {
615        builder.append(", ").append(array[i]);
616      }
617      return builder.append(']').toString();
618    }
619
620    long[] toLongArray() {
621      // Arrays.copyOfRange() is not available under GWT
622      int size = size();
623      long[] result = new long[size];
624      System.arraycopy(array, start, result, 0, size);
625      return result;
626    }
627
628    private static final long serialVersionUID = 0;
629  }
630}