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