1/*
2 * Copyright (C) 2008 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.common.primitives;
18
19import static com.google.common.base.Preconditions.checkArgument;
20import static com.google.common.base.Preconditions.checkElementIndex;
21import static com.google.common.base.Preconditions.checkNotNull;
22import static com.google.common.base.Preconditions.checkPositionIndexes;
23
24import com.google.common.annotations.GwtCompatible;
25import com.google.common.annotations.GwtIncompatible;
26
27import java.io.Serializable;
28import java.util.AbstractList;
29import java.util.Arrays;
30import java.util.Collection;
31import java.util.Collections;
32import java.util.Comparator;
33import java.util.List;
34import java.util.RandomAccess;
35
36/**
37 * Static utility methods pertaining to {@code long} primitives, that are not
38 * already found in either {@link Long} or {@link Arrays}.
39 *
40 * @author Kevin Bourrillion
41 * @since 1.0
42 */
43@GwtCompatible(emulated = true)
44public final class Longs {
45  private Longs() {}
46
47  /**
48   * The number of bytes required to represent a primitive {@code long}
49   * value.
50   */
51  public static final int BYTES = Long.SIZE / Byte.SIZE;
52
53  /**
54   * The largest power of two that can be represented as a {@code long}.
55   *
56   * @since 10.0
57   */
58  public static final long MAX_POWER_OF_TWO = 1L << (Long.SIZE - 2);
59
60  /**
61   * Returns a hash code for {@code value}; equal to the result of invoking
62   * {@code ((Long) value).hashCode()}.
63   *
64   * <p>This method always return the value specified by {@link
65   * Long#hashCode()} in java, which might be different from
66   * {@code ((Long) value).hashCode()} in GWT because {@link Long#hashCode()}
67   * in GWT does not obey the JRE contract.
68   *
69   * @param value a primitive {@code long} value
70   * @return a hash code for the value
71   */
72  public static int hashCode(long value) {
73    return (int) (value ^ (value >>> 32));
74  }
75
76  /**
77   * Compares the two specified {@code long} values. The sign of the value
78   * returned is the same as that of {@code ((Long) a).compareTo(b)}.
79   *
80   * @param a the first {@code long} to compare
81   * @param b the second {@code long} to compare
82   * @return a negative value if {@code a} is less than {@code b}; a positive
83   *     value if {@code a} is greater than {@code b}; or zero if they are equal
84   */
85  public static int compare(long a, long b) {
86    return (a < b) ? -1 : ((a > b) ? 1 : 0);
87  }
88
89  /**
90   * Returns {@code true} if {@code target} is present as an element anywhere in
91   * {@code array}.
92   *
93   * @param array an array of {@code long} values, possibly empty
94   * @param target a primitive {@code long} value
95   * @return {@code true} if {@code array[i] == target} for some value of {@code
96   *     i}
97   */
98  public static boolean contains(long[] array, long target) {
99    for (long value : array) {
100      if (value == target) {
101        return true;
102      }
103    }
104    return false;
105  }
106
107  /**
108   * Returns the index of the first appearance of the value {@code target} in
109   * {@code array}.
110   *
111   * @param array an array of {@code long} values, possibly empty
112   * @param target a primitive {@code long} value
113   * @return the least index {@code i} for which {@code array[i] == target}, or
114   *     {@code -1} if no such index exists.
115   */
116  public static int indexOf(long[] array, long target) {
117    return indexOf(array, target, 0, array.length);
118  }
119
120  // TODO(kevinb): consider making this public
121  private static int indexOf(
122      long[] array, long target, int start, int end) {
123    for (int i = start; i < end; i++) {
124      if (array[i] == target) {
125        return i;
126      }
127    }
128    return -1;
129  }
130
131  /**
132   * Returns the start position of the first occurrence of the specified {@code
133   * target} within {@code array}, or {@code -1} if there is no such occurrence.
134   *
135   * <p>More formally, returns the lowest index {@code i} such that {@code
136   * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
137   * the same elements as {@code target}.
138   *
139   * @param array the array to search for the sequence {@code target}
140   * @param target the array to search for as a sub-sequence of {@code array}
141   */
142  public static int indexOf(long[] array, long[] target) {
143    checkNotNull(array, "array");
144    checkNotNull(target, "target");
145    if (target.length == 0) {
146      return 0;
147    }
148
149    outer:
150    for (int i = 0; i < array.length - target.length + 1; i++) {
151      for (int j = 0; j < target.length; j++) {
152        if (array[i + j] != target[j]) {
153          continue outer;
154        }
155      }
156      return i;
157    }
158    return -1;
159  }
160
161  /**
162   * Returns the index of the last appearance of the value {@code target} in
163   * {@code array}.
164   *
165   * @param array an array of {@code long} values, possibly empty
166   * @param target a primitive {@code long} value
167   * @return the greatest index {@code i} for which {@code array[i] == target},
168   *     or {@code -1} if no such index exists.
169   */
170  public static int lastIndexOf(long[] array, long target) {
171    return lastIndexOf(array, target, 0, array.length);
172  }
173
174  // TODO(kevinb): consider making this public
175  private static int lastIndexOf(
176      long[] array, long target, int start, int end) {
177    for (int i = end - 1; i >= start; i--) {
178      if (array[i] == target) {
179        return i;
180      }
181    }
182    return -1;
183  }
184
185  /**
186   * Returns the least value present in {@code array}.
187   *
188   * @param array a <i>nonempty</i> array of {@code long} values
189   * @return the value present in {@code array} that is less than or equal to
190   *     every other value in the array
191   * @throws IllegalArgumentException if {@code array} is empty
192   */
193  public static long min(long... array) {
194    checkArgument(array.length > 0);
195    long min = array[0];
196    for (int i = 1; i < array.length; i++) {
197      if (array[i] < min) {
198        min = array[i];
199      }
200    }
201    return min;
202  }
203
204  /**
205   * Returns the greatest value present in {@code array}.
206   *
207   * @param array a <i>nonempty</i> array of {@code long} values
208   * @return the value present in {@code array} that is greater than or equal to
209   *     every other value in the array
210   * @throws IllegalArgumentException if {@code array} is empty
211   */
212  public static long max(long... array) {
213    checkArgument(array.length > 0);
214    long max = array[0];
215    for (int i = 1; i < array.length; i++) {
216      if (array[i] > max) {
217        max = array[i];
218      }
219    }
220    return max;
221  }
222
223  /**
224   * Returns the values from each provided array combined into a single array.
225   * For example, {@code concat(new long[] {a, b}, new long[] {}, new
226   * long[] {c}} returns the array {@code {a, b, c}}.
227   *
228   * @param arrays zero or more {@code long} arrays
229   * @return a single array containing all the values from the source arrays, in
230   *     order
231   */
232  public static long[] concat(long[]... arrays) {
233    int length = 0;
234    for (long[] array : arrays) {
235      length += array.length;
236    }
237    long[] result = new long[length];
238    int pos = 0;
239    for (long[] array : arrays) {
240      System.arraycopy(array, 0, result, pos, array.length);
241      pos += array.length;
242    }
243    return result;
244  }
245
246  /**
247   * Returns a big-endian representation of {@code value} in an 8-element byte
248   * array; equivalent to {@code ByteBuffer.allocate(8).putLong(value).array()}.
249   * For example, the input value {@code 0x1213141516171819L} would yield the
250   * byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}}.
251   *
252   * <p>If you need to convert and concatenate several values (possibly even of
253   * different types), use a shared {@link java.nio.ByteBuffer} instance, or use
254   * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable
255   * buffer.
256   */
257  @GwtIncompatible("doesn't work")
258  public static byte[] toByteArray(long value) {
259    return new byte[] {
260        (byte) (value >> 56),
261        (byte) (value >> 48),
262        (byte) (value >> 40),
263        (byte) (value >> 32),
264        (byte) (value >> 24),
265        (byte) (value >> 16),
266        (byte) (value >> 8),
267        (byte) value};
268  }
269
270  /**
271   * Returns the {@code long} value whose big-endian representation is
272   * stored in the first 8 bytes of {@code bytes}; equivalent to {@code
273   * ByteBuffer.wrap(bytes).getLong()}. For example, the input byte array
274   * {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}} would yield the
275   * {@code long} value {@code 0x1213141516171819L}.
276   *
277   * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that
278   * library exposes much more flexibility at little cost in readability.
279   *
280   * @throws IllegalArgumentException if {@code bytes} has fewer than 8
281   *     elements
282   */
283  @GwtIncompatible("doesn't work")
284  public static long fromByteArray(byte[] bytes) {
285    checkArgument(bytes.length >= BYTES,
286        "array too small: %s < %s", bytes.length, BYTES);
287    return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3],
288        bytes[4], bytes[5], bytes[6], bytes[7]) ;
289  }
290
291  /**
292   * Returns the {@code long} value whose byte representation is the given 8
293   * bytes, in big-endian order; equivalent to {@code Longs.fromByteArray(new
294   * byte[] {b1, b2, b3, b4, b5, b6, b7, b8})}.
295   *
296   * @since 7.0
297   */
298  @GwtIncompatible("doesn't work")
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   * Returns an array containing the same values as {@code array}, but
313   * guaranteed to be of a specified minimum length. If {@code array} already
314   * has a length of at least {@code minLength}, it is returned directly.
315   * Otherwise, a new array of size {@code minLength + padding} is returned,
316   * containing the values of {@code array}, and zeroes in the remaining places.
317   *
318   * @param array the source array
319   * @param minLength the minimum length the returned array must guarantee
320   * @param padding an extra amount to "grow" the array by if growth is
321   *     necessary
322   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is
323   *     negative
324   * @return an array containing the values of {@code array}, with guaranteed
325   *     minimum length {@code minLength}
326   */
327  public static long[] ensureCapacity(
328      long[] array, int minLength, int padding) {
329    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
330    checkArgument(padding >= 0, "Invalid padding: %s", padding);
331    return (array.length < minLength)
332        ? copyOf(array, minLength + padding)
333        : array;
334  }
335
336  // Arrays.copyOf() requires Java 6
337  private static long[] copyOf(long[] original, int length) {
338    long[] copy = new long[length];
339    System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
340    return copy;
341  }
342
343  /**
344   * Returns a string containing the supplied {@code long} values separated
345   * by {@code separator}. For example, {@code join("-", 1L, 2L, 3L)} returns
346   * the string {@code "1-2-3"}.
347   *
348   * @param separator the text that should appear between consecutive values in
349   *     the resulting string (but not at the start or end)
350   * @param array an array of {@code long} values, possibly empty
351   */
352  public static String join(String separator, long... array) {
353    checkNotNull(separator);
354    if (array.length == 0) {
355      return "";
356    }
357
358    // For pre-sizing a builder, just get the right order of magnitude
359    StringBuilder builder = new StringBuilder(array.length * 10);
360    builder.append(array[0]);
361    for (int i = 1; i < array.length; i++) {
362      builder.append(separator).append(array[i]);
363    }
364    return builder.toString();
365  }
366
367  /**
368   * Returns a comparator that compares two {@code long} arrays
369   * lexicographically. That is, it compares, using {@link
370   * #compare(long, long)}), the first pair of values that follow any
371   * common prefix, or when one array is a prefix of the other, treats the
372   * shorter array as the lesser. For example,
373   * {@code [] < [1L] < [1L, 2L] < [2L]}.
374   *
375   * <p>The returned comparator is inconsistent with {@link
376   * Object#equals(Object)} (since arrays support only identity equality), but
377   * it is consistent with {@link Arrays#equals(long[], long[])}.
378   *
379   * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
380   *     Lexicographical order article at Wikipedia</a>
381   * @since 2.0
382   */
383  public static Comparator<long[]> lexicographicalComparator() {
384    return LexicographicalComparator.INSTANCE;
385  }
386
387  private enum LexicographicalComparator implements Comparator<long[]> {
388    INSTANCE;
389
390    @Override
391    public int compare(long[] left, long[] right) {
392      int minLength = Math.min(left.length, right.length);
393      for (int i = 0; i < minLength; i++) {
394        int result = Longs.compare(left[i], right[i]);
395        if (result != 0) {
396          return result;
397        }
398      }
399      return left.length - right.length;
400    }
401  }
402
403  /**
404   * Copies a collection of {@code Long} instances into a new array of
405   * primitive {@code long} values.
406   *
407   * <p>Elements are copied from the argument collection as if by {@code
408   * collection.toArray()}.  Calling this method is as thread-safe as calling
409   * that method.
410   *
411   * @param collection a collection of {@code Long} objects
412   * @return an array containing the same values as {@code collection}, in the
413   *     same order, converted to primitives
414   * @throws NullPointerException if {@code collection} or any of its elements
415   *     is null
416   */
417  public static long[] toArray(Collection<Long> collection) {
418    if (collection instanceof LongArrayAsList) {
419      return ((LongArrayAsList) collection).toLongArray();
420    }
421
422    Object[] boxedArray = collection.toArray();
423    int len = boxedArray.length;
424    long[] array = new long[len];
425    for (int i = 0; i < len; i++) {
426      // checkNotNull for GWT (do not optimize)
427      array[i] = (Long) checkNotNull(boxedArray[i]);
428    }
429    return array;
430  }
431
432  /**
433   * Returns a fixed-size list backed by the specified array, similar to {@link
434   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
435   * but any attempt to set a value to {@code null} will result in a {@link
436   * NullPointerException}.
437   *
438   * <p>The returned list maintains the values, but not the identities, of
439   * {@code Long} objects written to or read from it.  For example, whether
440   * {@code list.get(0) == list.get(0)} is true for the returned list is
441   * unspecified.
442   *
443   * @param backingArray the array to back the list
444   * @return a list view of the array
445   */
446  public static List<Long> asList(long... backingArray) {
447    if (backingArray.length == 0) {
448      return Collections.emptyList();
449    }
450    return new LongArrayAsList(backingArray);
451  }
452
453  @GwtCompatible
454  private static class LongArrayAsList extends AbstractList<Long>
455      implements RandomAccess, Serializable {
456    final long[] array;
457    final int start;
458    final int end;
459
460    LongArrayAsList(long[] array) {
461      this(array, 0, array.length);
462    }
463
464    LongArrayAsList(long[] array, int start, int end) {
465      this.array = array;
466      this.start = start;
467      this.end = end;
468    }
469
470    @Override public int size() {
471      return end - start;
472    }
473
474    @Override public boolean isEmpty() {
475      return false;
476    }
477
478    @Override public Long get(int index) {
479      checkElementIndex(index, size());
480      return array[start + index];
481    }
482
483    @Override public boolean contains(Object target) {
484      // Overridden to prevent a ton of boxing
485      return (target instanceof Long)
486          && Longs.indexOf(array, (Long) target, start, end) != -1;
487    }
488
489    @Override public int indexOf(Object target) {
490      // Overridden to prevent a ton of boxing
491      if (target instanceof Long) {
492        int i = Longs.indexOf(array, (Long) target, start, end);
493        if (i >= 0) {
494          return i - start;
495        }
496      }
497      return -1;
498    }
499
500    @Override public int lastIndexOf(Object target) {
501      // Overridden to prevent a ton of boxing
502      if (target instanceof Long) {
503        int i = Longs.lastIndexOf(array, (Long) target, start, end);
504        if (i >= 0) {
505          return i - start;
506        }
507      }
508      return -1;
509    }
510
511    @Override public Long set(int index, Long element) {
512      checkElementIndex(index, size());
513      long oldValue = array[start + index];
514      array[start + index] = checkNotNull(element);  // checkNotNull for GWT (do not optimize)
515      return oldValue;
516    }
517
518    @Override public List<Long> subList(int fromIndex, int toIndex) {
519      int size = size();
520      checkPositionIndexes(fromIndex, toIndex, size);
521      if (fromIndex == toIndex) {
522        return Collections.emptyList();
523      }
524      return new LongArrayAsList(array, start + fromIndex, start + toIndex);
525    }
526
527    @Override public boolean equals(Object object) {
528      if (object == this) {
529        return true;
530      }
531      if (object instanceof LongArrayAsList) {
532        LongArrayAsList that = (LongArrayAsList) object;
533        int size = size();
534        if (that.size() != size) {
535          return false;
536        }
537        for (int i = 0; i < size; i++) {
538          if (array[start + i] != that.array[that.start + i]) {
539            return false;
540          }
541        }
542        return true;
543      }
544      return super.equals(object);
545    }
546
547    @Override public int hashCode() {
548      int result = 1;
549      for (int i = start; i < end; i++) {
550        result = 31 * result + Longs.hashCode(array[i]);
551      }
552      return result;
553    }
554
555    @Override public String toString() {
556      StringBuilder builder = new StringBuilder(size() * 10);
557      builder.append('[').append(array[start]);
558      for (int i = start + 1; i < end; i++) {
559        builder.append(", ").append(array[i]);
560      }
561      return builder.append(']').toString();
562    }
563
564    long[] toLongArray() {
565      // Arrays.copyOfRange() requires Java 6
566      int size = size();
567      long[] result = new long[size];
568      System.arraycopy(array, start, result, 0, size);
569      return result;
570    }
571
572    private static final long serialVersionUID = 0;
573  }
574}
575