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    
017    package com.google.common.primitives;
018    
019    import static com.google.common.base.Preconditions.checkArgument;
020    import static com.google.common.base.Preconditions.checkElementIndex;
021    import static com.google.common.base.Preconditions.checkNotNull;
022    import static com.google.common.base.Preconditions.checkPositionIndexes;
023    
024    import com.google.common.annotations.GwtCompatible;
025    import com.google.common.annotations.GwtIncompatible;
026    
027    import java.io.Serializable;
028    import java.util.AbstractList;
029    import java.util.Arrays;
030    import java.util.Collection;
031    import java.util.Collections;
032    import java.util.Comparator;
033    import java.util.List;
034    import 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(emulated = true)
048    public 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      @GwtIncompatible("doesn't work")
262      public static byte[] toByteArray(long value) {
263        return new byte[] {
264            (byte) (value >> 56),
265            (byte) (value >> 48),
266            (byte) (value >> 40),
267            (byte) (value >> 32),
268            (byte) (value >> 24),
269            (byte) (value >> 16),
270            (byte) (value >> 8),
271            (byte) value};
272      }
273    
274      /**
275       * Returns the {@code long} value whose big-endian representation is
276       * stored in the first 8 bytes of {@code bytes}; equivalent to {@code
277       * ByteBuffer.wrap(bytes).getLong()}. For example, the input byte array
278       * {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}} would yield the
279       * {@code long} value {@code 0x1213141516171819L}.
280       *
281       * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that
282       * library exposes much more flexibility at little cost in readability.
283       *
284       * @throws IllegalArgumentException if {@code bytes} has fewer than 8
285       *     elements
286       */
287      @GwtIncompatible("doesn't work")
288      public static long fromByteArray(byte[] bytes) {
289        checkArgument(bytes.length >= BYTES,
290            "array too small: %s < %s", bytes.length, BYTES);
291        return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3],
292            bytes[4], bytes[5], bytes[6], bytes[7]) ;
293      }
294    
295      /**
296       * Returns the {@code long} value whose byte representation is the given 8
297       * bytes, in big-endian order; equivalent to {@code Longs.fromByteArray(new
298       * byte[] {b1, b2, b3, b4, b5, b6, b7, b8})}.
299       *
300       * @since 7.0
301       */
302      @GwtIncompatible("doesn't work")
303      public static long fromBytes(byte b1, byte b2, byte b3, byte b4,
304          byte b5, byte b6, byte b7, byte b8) {
305        return (b1 & 0xFFL) << 56
306            | (b2 & 0xFFL) << 48
307            | (b3 & 0xFFL) << 40
308            | (b4 & 0xFFL) << 32
309            | (b5 & 0xFFL) << 24
310            | (b6 & 0xFFL) << 16
311            | (b7 & 0xFFL) << 8
312            | (b8 & 0xFFL);
313      }
314    
315      /**
316       * Returns an array containing the same values as {@code array}, but
317       * guaranteed to be of a specified minimum length. If {@code array} already
318       * has a length of at least {@code minLength}, it is returned directly.
319       * Otherwise, a new array of size {@code minLength + padding} is returned,
320       * containing the values of {@code array}, and zeroes in the remaining places.
321       *
322       * @param array the source array
323       * @param minLength the minimum length the returned array must guarantee
324       * @param padding an extra amount to "grow" the array by if growth is
325       *     necessary
326       * @throws IllegalArgumentException if {@code minLength} or {@code padding} is
327       *     negative
328       * @return an array containing the values of {@code array}, with guaranteed
329       *     minimum length {@code minLength}
330       */
331      public static long[] ensureCapacity(
332          long[] array, int minLength, int padding) {
333        checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
334        checkArgument(padding >= 0, "Invalid padding: %s", padding);
335        return (array.length < minLength)
336            ? copyOf(array, minLength + padding)
337            : array;
338      }
339    
340      // Arrays.copyOf() requires Java 6
341      private static long[] copyOf(long[] original, int length) {
342        long[] copy = new long[length];
343        System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
344        return copy;
345      }
346    
347      /**
348       * Returns a string containing the supplied {@code long} values separated
349       * by {@code separator}. For example, {@code join("-", 1L, 2L, 3L)} returns
350       * the string {@code "1-2-3"}.
351       *
352       * @param separator the text that should appear between consecutive values in
353       *     the resulting string (but not at the start or end)
354       * @param array an array of {@code long} values, possibly empty
355       */
356      public static String join(String separator, long... array) {
357        checkNotNull(separator);
358        if (array.length == 0) {
359          return "";
360        }
361    
362        // For pre-sizing a builder, just get the right order of magnitude
363        StringBuilder builder = new StringBuilder(array.length * 10);
364        builder.append(array[0]);
365        for (int i = 1; i < array.length; i++) {
366          builder.append(separator).append(array[i]);
367        }
368        return builder.toString();
369      }
370    
371      /**
372       * Returns a comparator that compares two {@code long} arrays
373       * lexicographically. That is, it compares, using {@link
374       * #compare(long, long)}), the first pair of values that follow any
375       * common prefix, or when one array is a prefix of the other, treats the
376       * shorter array as the lesser. For example,
377       * {@code [] < [1L] < [1L, 2L] < [2L]}.
378       *
379       * <p>The returned comparator is inconsistent with {@link
380       * Object#equals(Object)} (since arrays support only identity equality), but
381       * it is consistent with {@link Arrays#equals(long[], long[])}.
382       *
383       * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
384       *     Lexicographical order article at Wikipedia</a>
385       * @since 2.0
386       */
387      public static Comparator<long[]> lexicographicalComparator() {
388        return LexicographicalComparator.INSTANCE;
389      }
390    
391      private enum LexicographicalComparator implements Comparator<long[]> {
392        INSTANCE;
393    
394        @Override
395        public int compare(long[] left, long[] right) {
396          int minLength = Math.min(left.length, right.length);
397          for (int i = 0; i < minLength; i++) {
398            int result = Longs.compare(left[i], right[i]);
399            if (result != 0) {
400              return result;
401            }
402          }
403          return left.length - right.length;
404        }
405      }
406    
407      /**
408       * Returns an array containing each value of {@code collection}, converted to
409       * a {@code long} value in the manner of {@link Number#longValue}.
410       *
411       * <p>Elements are copied from the argument collection as if by {@code
412       * collection.toArray()}.  Calling this method is as thread-safe as calling
413       * that method.
414       *
415       * @param collection a collection of {@code Number} instances
416       * @return an array containing the same values as {@code collection}, in the
417       *     same order, converted to primitives
418       * @throws NullPointerException if {@code collection} or any of its elements
419       *     is null
420       * @since 1.0 (parameter was {@code Collection<Long>} before 12.0)
421       */
422      public static long[] toArray(Collection<? extends Number> collection) {
423        if (collection instanceof LongArrayAsList) {
424          return ((LongArrayAsList) collection).toLongArray();
425        }
426    
427        Object[] boxedArray = collection.toArray();
428        int len = boxedArray.length;
429        long[] array = new long[len];
430        for (int i = 0; i < len; i++) {
431          // checkNotNull for GWT (do not optimize)
432          array[i] = ((Number) checkNotNull(boxedArray[i])).longValue();
433        }
434        return array;
435      }
436    
437      /**
438       * Returns a fixed-size list backed by the specified array, similar to {@link
439       * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
440       * but any attempt to set a value to {@code null} will result in a {@link
441       * NullPointerException}.
442       *
443       * <p>The returned list maintains the values, but not the identities, of
444       * {@code Long} objects written to or read from it.  For example, whether
445       * {@code list.get(0) == list.get(0)} is true for the returned list is
446       * unspecified.
447       *
448       * @param backingArray the array to back the list
449       * @return a list view of the array
450       */
451      public static List<Long> asList(long... backingArray) {
452        if (backingArray.length == 0) {
453          return Collections.emptyList();
454        }
455        return new LongArrayAsList(backingArray);
456      }
457    
458      @GwtCompatible
459      private static class LongArrayAsList extends AbstractList<Long>
460          implements RandomAccess, Serializable {
461        final long[] array;
462        final int start;
463        final int end;
464    
465        LongArrayAsList(long[] array) {
466          this(array, 0, array.length);
467        }
468    
469        LongArrayAsList(long[] array, int start, int end) {
470          this.array = array;
471          this.start = start;
472          this.end = end;
473        }
474    
475        @Override public int size() {
476          return end - start;
477        }
478    
479        @Override public boolean isEmpty() {
480          return false;
481        }
482    
483        @Override public Long get(int index) {
484          checkElementIndex(index, size());
485          return array[start + index];
486        }
487    
488        @Override public boolean contains(Object target) {
489          // Overridden to prevent a ton of boxing
490          return (target instanceof Long)
491              && Longs.indexOf(array, (Long) target, start, end) != -1;
492        }
493    
494        @Override public int indexOf(Object target) {
495          // Overridden to prevent a ton of boxing
496          if (target instanceof Long) {
497            int i = Longs.indexOf(array, (Long) target, start, end);
498            if (i >= 0) {
499              return i - start;
500            }
501          }
502          return -1;
503        }
504    
505        @Override public int lastIndexOf(Object target) {
506          // Overridden to prevent a ton of boxing
507          if (target instanceof Long) {
508            int i = Longs.lastIndexOf(array, (Long) target, start, end);
509            if (i >= 0) {
510              return i - start;
511            }
512          }
513          return -1;
514        }
515    
516        @Override public Long set(int index, Long element) {
517          checkElementIndex(index, size());
518          long oldValue = array[start + index];
519          array[start + index] = checkNotNull(element);  // checkNotNull for GWT (do not optimize)
520          return oldValue;
521        }
522    
523        @Override public List<Long> subList(int fromIndex, int toIndex) {
524          int size = size();
525          checkPositionIndexes(fromIndex, toIndex, size);
526          if (fromIndex == toIndex) {
527            return Collections.emptyList();
528          }
529          return new LongArrayAsList(array, start + fromIndex, start + toIndex);
530        }
531    
532        @Override public boolean equals(Object object) {
533          if (object == this) {
534            return true;
535          }
536          if (object instanceof LongArrayAsList) {
537            LongArrayAsList that = (LongArrayAsList) object;
538            int size = size();
539            if (that.size() != size) {
540              return false;
541            }
542            for (int i = 0; i < size; i++) {
543              if (array[start + i] != that.array[that.start + i]) {
544                return false;
545              }
546            }
547            return true;
548          }
549          return super.equals(object);
550        }
551    
552        @Override public int hashCode() {
553          int result = 1;
554          for (int i = start; i < end; i++) {
555            result = 31 * result + Longs.hashCode(array[i]);
556          }
557          return result;
558        }
559    
560        @Override public String toString() {
561          StringBuilder builder = new StringBuilder(size() * 10);
562          builder.append('[').append(array[start]);
563          for (int i = start + 1; i < end; i++) {
564            builder.append(", ").append(array[i]);
565          }
566          return builder.append(']').toString();
567        }
568    
569        long[] toLongArray() {
570          // Arrays.copyOfRange() requires Java 6
571          int size = size();
572          long[] result = new long[size];
573          System.arraycopy(array, start, result, 0, size);
574          return result;
575        }
576    
577        private static final long serialVersionUID = 0;
578      }
579    }