    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
    026    import java.io.Serializable;
    027    import java.util.AbstractList;
    028    import java.util.Arrays;
    029    import java.util.Collection;
    030    import java.util.Collections;
    031    import java.util.Comparator;
    032    import java.util.List;
    033    import java.util.RandomAccess;
    034
    035    /**
    036     * Static utility methods pertaining to {@code long} primitives, that are not
    037     * already found in either {@link Long} or {@link Arrays}.
    038     *
    039     * <p>See the Guava User Guide article on <a href=
    040     * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
    041     * primitive utilities</a>.
    042     *
    043     * @author Kevin Bourrillion
    044     * @since 1.0
    045     */
    046    @GwtCompatible
    047    public final class Longs {
    048      private Longs() {}
    049
    050      /**
    051       * The number of bytes required to represent a primitive {@code long}
    052       * value.
    053       */
    054      public static final int BYTES = Long.SIZE / Byte.SIZE;
    055
    056      /**
    057       * The largest power of two that can be represented as a {@code long}.
    058       *
    059       * @since 10.0
    060       */
    061      public static final long MAX_POWER_OF_TWO = 1L << (Long.SIZE - 2);
    062
    063      /**
    064       * Returns a hash code for {@code value}; equal to the result of invoking
    065       * {@code ((Long) value).hashCode()}.
    066       *
    067       * <p>This method always return the value specified by {@link
    068       * Long#hashCode()} in java, which might be different from
    069       * {@code ((Long) value).hashCode()} in GWT because {@link Long#hashCode()}
    070       * in GWT does not obey the JRE contract.
    071       *
    072       * @param value a primitive {@code long} value
    073       * @return a hash code for the value
    074       */
    075      public static int hashCode(long value) {
    076        return (int) (value ^ (value >>> 32));
    077      }
    078
    079      /**
    080       * Compares the two specified {@code long} values. The sign of the value
    081       * returned is the same as that of {@code ((Long) a).compareTo(b)}.
    082       *
    083       * @param a the first {@code long} to compare
    084       * @param b the second {@code long} to compare
    085       * @return a negative value if {@code a} is less than {@code b}; a positive
    086       *     value if {@code a} is greater than {@code b}; or zero if they are equal
    087       */
    088      public static int compare(long a, long b) {
    089        return (a < b) ? -1 : ((a > b) ? 1 : 0);
    090      }
    091
    092      /**
    093       * Returns {@code true} if {@code target} is present as an element anywhere in
    094       * {@code array}.
    095       *
    096       * @param array an array of {@code long} values, possibly empty
    097       * @param target a primitive {@code long} value
    098       * @return {@code true} if {@code array[i] == target} for some value of {@code
    099       *     i}
    100       */
    101      public static boolean contains(long[] array, long target) {
    102        for (long value : array) {
    103          if (value == target) {
    104            return true;
    105          }
    106        }
    107        return false;
    108      }
    109
    110      /**
    111       * Returns the index of the first appearance of the value {@code target} in
    112       * {@code array}.
    113       *
    114       * @param array an array of {@code long} values, possibly empty
    115       * @param target a primitive {@code long} value
    116       * @return the least index {@code i} for which {@code array[i] == target}, or
    117       *     {@code -1} if no such index exists.
    118       */
    119      public static int indexOf(long[] array, long target) {
    120        return indexOf(array, target, 0, array.length);
    121      }
    122
    123      // TODO(kevinb): consider making this public
    124      private static int indexOf(
    125          long[] array, long target, int start, int end) {
    126        for (int i = start; i < end; i++) {
    127          if (array[i] == target) {
    128            return i;
    129          }
    130        }
    131        return -1;
    132      }
    133
    134      /**
    135       * Returns the start position of the first occurrence of the specified {@code
    136       * target} within {@code array}, or {@code -1} if there is no such occurrence.
    137       *
    138       * <p>More formally, returns the lowest index {@code i} such that {@code
    139       * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
    140       * the same elements as {@code target}.
    141       *
    142       * @param array the array to search for the sequence {@code target}
    143       * @param target the array to search for as a sub-sequence of {@code array}
    144       */
    145      public static int indexOf(long[] array, long[] target) {
    146        checkNotNull(array, "array");
    147        checkNotNull(target, "target");
    148        if (target.length == 0) {
    149          return 0;
    150        }
    151
    152        outer:
    153        for (int i = 0; i < array.length - target.length + 1; i++) {
    154          for (int j = 0; j < target.length; j++) {
    155            if (array[i + j] != target[j]) {
    156              continue outer;
    157            }
    158          }
    159          return i;
    160        }
    161        return -1;
    162      }
    163
    164      /**
    165       * Returns the index of the last appearance of the value {@code target} in
    166       * {@code array}.
    167       *
    168       * @param array an array of {@code long} values, possibly empty
    169       * @param target a primitive {@code long} value
    170       * @return the greatest index {@code i} for which {@code array[i] == target},
    171       *     or {@code -1} if no such index exists.
    172       */
    173      public static int lastIndexOf(long[] array, long target) {
    174        return lastIndexOf(array, target, 0, array.length);
    175      }
    176
    177      // TODO(kevinb): consider making this public
    178      private static int lastIndexOf(
    179          long[] array, long target, int start, int end) {
    180        for (int i = end - 1; i >= start; i--) {
    181          if (array[i] == target) {
    182            return i;
    183          }
    184        }
    185        return -1;
    186      }
    187
    188      /**
    189       * Returns the least value present in {@code array}.
    190       *
    191       * @param array a <i>nonempty</i> array of {@code long} values
    192       * @return the value present in {@code array} that is less than or equal to
    193       *     every other value in the array
    194       * @throws IllegalArgumentException if {@code array} is empty
    195       */
    196      public static long min(long... array) {
    197        checkArgument(array.length > 0);
    198        long min = array[0];
    199        for (int i = 1; i < array.length; i++) {
    200          if (array[i] < min) {
    201            min = array[i];
    202          }
    203        }
    204        return min;
    205      }
    206
    207      /**
    208       * Returns the greatest value present in {@code array}.
    209       *
    210       * @param array a <i>nonempty</i> array of {@code long} values
    211       * @return the value present in {@code array} that is greater than or equal to
    212       *     every other value in the array
    213       * @throws IllegalArgumentException if {@code array} is empty
    214       */
    215      public static long max(long... array) {
    216        checkArgument(array.length > 0);
    217        long max = array[0];
    218        for (int i = 1; i < array.length; i++) {
    219          if (array[i] > max) {
    220            max = array[i];
    221          }
    222        }
    223        return max;
    224      }
    225
    226      /**
    227       * Returns the values from each provided array combined into a single array.
    228       * For example, {@code concat(new long[] {a, b}, new long[] {}, new
    229       * long[] {c}} returns the array {@code {a, b, c}}.
    230       *
    231       * @param arrays zero or more {@code long} arrays
    232       * @return a single array containing all the values from the source arrays, in
    233       *     order
    234       */
    235      public static long[] concat(long[]... arrays) {
    236        int length = 0;
    237        for (long[] array : arrays) {
    238          length += array.length;
    239        }
    240        long[] result = new long[length];
    241        int pos = 0;
    242        for (long[] array : arrays) {
    243          System.arraycopy(array, 0, result, pos, array.length);
    244          pos += array.length;
    245        }
    246        return result;
    247      }
    248
    249      /**
    250       * Returns a big-endian representation of {@code value} in an 8-element byte
    251       * array; equivalent to {@code ByteBuffer.allocate(8).putLong(value).array()}.
    252       * For example, the input value {@code 0x1213141516171819L} would yield the
    253       * byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}}.
    254       *
    255       * <p>If you need to convert and concatenate several values (possibly even of
    256       * different types), use a shared {@link java.nio.ByteBuffer} instance, or use
    257       * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable
    258       * buffer.
    259       */
    260      public static byte[] toByteArray(long value) {
    261        // Note that this code needs to stay compatible with GWT, which has known
    262        // bugs when narrowing byte casts of long values occur.
    263        byte[] result = new byte[8];
    264        for (int i = 7; i >= 0; i--) {
    265          result[i] = (byte) (value & 0xffL);
    266          value >>= 8;
    267        }
    268        return result;
    269      }
    270
    271      /**
    272       * Returns the {@code long} value whose big-endian representation is
    273       * stored in the first 8 bytes of {@code bytes}; equivalent to {@code
    274       * ByteBuffer.wrap(bytes).getLong()}. For example, the input byte array
    275       * {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}} would yield the
    276       * {@code long} value {@code 0x1213141516171819L}.
    277       *
    278       * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that
    279       * library exposes much more flexibility at little cost in readability.
    280       *
    281       * @throws IllegalArgumentException if {@code bytes} has fewer than 8
    282       *     elements
    283       */
    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      public static long fromBytes(byte b1, byte b2, byte b3, byte b4,
    299          byte b5, byte b6, byte b7, byte b8) {
    300        return (b1 & 0xFFL) << 56
    301            | (b2 & 0xFFL) << 48
    302            | (b3 & 0xFFL) << 40
    303            | (b4 & 0xFFL) << 32
    304            | (b5 & 0xFFL) << 24
    305            | (b6 & 0xFFL) << 16
    306            | (b7 & 0xFFL) << 8
    307            | (b8 & 0xFFL);
    308      }
    309
    310      /**
    311       * Returns an array containing the same values as {@code array}, but
    312       * guaranteed to be of a specified minimum length. If {@code array} already
    313       * has a length of at least {@code minLength}, it is returned directly.
    314       * Otherwise, a new array of size {@code minLength + padding} is returned,
    315       * containing the values of {@code array}, and zeroes in the remaining places.
    316       *
    317       * @param array the source array
    318       * @param minLength the minimum length the returned array must guarantee
    319       * @param padding an extra amount to "grow" the array by if growth is
    320       *     necessary
    321       * @throws IllegalArgumentException if {@code minLength} or {@code padding} is
    322       *     negative
    323       * @return an array containing the values of {@code array}, with guaranteed
    324       *     minimum length {@code minLength}
    325       */
    326      public static long[] ensureCapacity(
    327          long[] array, int minLength, int padding) {
    328        checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
    329        checkArgument(padding >= 0, "Invalid padding: %s", padding);
    330        return (array.length < minLength)
    331            ? copyOf(array, minLength + padding)
    332            : array;
    333      }
    334
    335      // Arrays.copyOf() requires Java 6
    336      private static long[] copyOf(long[] original, int length) {
    337        long[] copy = new long[length];
    338        System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
    339        return copy;
    340      }
    341
    342      /**
    343       * Returns a string containing the supplied {@code long} values separated
    344       * by {@code separator}. For example, {@code join("-", 1L, 2L, 3L)} returns
    345       * the string {@code "1-2-3"}.
    346       *
    347       * @param separator the text that should appear between consecutive values in
    348       *     the resulting string (but not at the start or end)
    349       * @param array an array of {@code long} values, possibly empty
    350       */
    351      public static String join(String separator, long... array) {
    352        checkNotNull(separator);
    353        if (array.length == 0) {
    354          return "";
    355        }
    356
    357        // For pre-sizing a builder, just get the right order of magnitude
    358        StringBuilder builder = new StringBuilder(array.length * 10);
    359        builder.append(array[0]);
    360        for (int i = 1; i < array.length; i++) {
    361          builder.append(separator).append(array[i]);
    362        }
    363        return builder.toString();
    364      }
    365
    366      /**
    367       * Returns a comparator that compares two {@code long} arrays
    368       * lexicographically. That is, it compares, using {@link
    369       * #compare(long, long)}), the first pair of values that follow any
    370       * common prefix, or when one array is a prefix of the other, treats the
    371       * shorter array as the lesser. For example,
    372       * {@code [] < [1L] < [1L, 2L] < [2L]}.
    373       *
    374       * <p>The returned comparator is inconsistent with {@link
    375       * Object#equals(Object)} (since arrays support only identity equality), but
    376       * it is consistent with {@link Arrays#equals(long[], long[])}.
    377       *
    378       * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
    379       *     Lexicographical order article at Wikipedia</a>
    380       * @since 2.0
    381       */
    382      public static Comparator<long[]> lexicographicalComparator() {
    383        return LexicographicalComparator.INSTANCE;
    384      }
    385
    386      private enum LexicographicalComparator implements Comparator<long[]> {
    387        INSTANCE;
    388
    389        @Override
    390        public int compare(long[] left, long[] right) {
    391          int minLength = Math.min(left.length, right.length);
    392          for (int i = 0; i < minLength; i++) {
    393            int result = Longs.compare(left[i], right[i]);
    394            if (result != 0) {
    395              return result;
    396            }
    397          }
    398          return left.length - right.length;
    399        }
    400      }
    401
    402      /**
    403       * Returns an array containing each value of {@code collection}, converted to
    404       * a {@code long} value in the manner of {@link Number#longValue}.
    405       *
    406       * <p>Elements are copied from the argument collection as if by {@code
    407       * collection.toArray()}.  Calling this method is as thread-safe as calling
    408       * that method.
    409       *
    410       * @param collection a collection of {@code Number} instances
    411       * @return an array containing the same values as {@code collection}, in the
    412       *     same order, converted to primitives
    413       * @throws NullPointerException if {@code collection} or any of its elements
    414       *     is null
    415       * @since 1.0 (parameter was {@code Collection<Long>} before 12.0)
    416       */
    417      public static long[] toArray(Collection<? extends Number> 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] = ((Number) checkNotNull(boxedArray[i])).longValue();
    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          // checkNotNull for GWT (do not optimize)
    515          array[start + index] = checkNotNull(element);
    516          return oldValue;
    517        }
    518
    519        @Override public List<Long> subList(int fromIndex, int toIndex) {
    520          int size = size();
    521          checkPositionIndexes(fromIndex, toIndex, size);
    522          if (fromIndex == toIndex) {
    523            return Collections.emptyList();
    524          }
    525          return new LongArrayAsList(array, start + fromIndex, start + toIndex);
    526        }
    527
    528        @Override public boolean equals(Object object) {
    529          if (object == this) {
    530            return true;
    531          }
    532          if (object instanceof LongArrayAsList) {
    533            LongArrayAsList that = (LongArrayAsList) object;
    534            int size = size();
    535            if (that.size() != size) {
    536              return false;
    537            }
    538            for (int i = 0; i < size; i++) {
    539              if (array[start + i] != that.array[that.start + i]) {
    540                return false;
    541              }
    542            }
    543            return true;
    544          }
    545          return super.equals(object);
    546        }
    547
    548        @Override public int hashCode() {
    549          int result = 1;
    550          for (int i = start; i < end; i++) {
    551            result = 31 * result + Longs.hashCode(array[i]);
    552          }
    553          return result;
    554        }
    555
    556        @Override public String toString() {
    557          StringBuilder builder = new StringBuilder(size() * 10);
    558          builder.append('[').append(array[start]);
    559          for (int i = start + 1; i < end; i++) {
    560            builder.append(", ").append(array[i]);
    561          }
    562          return builder.append(']').toString();
    563        }
    564
    565        long[] toLongArray() {
    566          // Arrays.copyOfRange() is not available under GWT
    567          int size = size();
    568          long[] result = new long[size];
    569          System.arraycopy(array, start, result, 0, size);
    570          return result;
    571        }
    572
    573        private static final long serialVersionUID = 0;
    574      }
    575    }