/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Converter; /** * Static utility methods pertaining to {@code long} primitives, that are not * already found in either {@link Long} or {@link Arrays}. * *
* See the Guava User Guide article on * * primitive utilities. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible public final class Longs { private Longs() { } /** * The number of bytes required to represent a primitive {@code long} value. */ public static final int BYTES = Long.SIZE / Byte.SIZE; /** * The largest power of two that can be represented as a {@code long}. * * @since 10.0 */ public static final long MAX_POWER_OF_TWO = 1L << (Long.SIZE - 2); /** * Returns a hash code for {@code value}; equal to the result of invoking * {@code ((Long) value).hashCode()}. * *
* This method always return the value specified by {@link Long#hashCode()} in * java, which might be different from {@code ((Long) value).hashCode()} in GWT * because {@link Long#hashCode()} in GWT does not obey the JRE contract. * * @param value a primitive {@code long} value * @return a hash code for the value */ public static int hashCode(long value) { return (int) (value ^ (value >>> 32)); } /** * Compares the two specified {@code long} values. The sign of the value * returned is the same as that of {@code ((Long) a).compareTo(b)}. * *
* Note: projects using JDK 7 or later should use the equivalent * {@link Long#compare} method instead. * * @param a the first {@code long} to compare * @param b the second {@code long} to compare * @return a negative value if {@code a} is less than {@code b}; a positive * value if {@code a} is greater than {@code b}; or zero if they are * equal */ public static int compare(long a, long b) { return (a < b) ? -1 : ((a > b) ? 1 : 0); } /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. * * @param array an array of {@code long} values, possibly empty * @param target a primitive {@code long} value * @return {@code true} if {@code array[i] == target} for some value of {@code * i} */ public static boolean contains(long[] array, long target) { for (long value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code long} values, possibly empty * @param target a primitive {@code long} value * @return the least index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int indexOf(long[] array, long target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf(long[] array, long target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code * target} within {@code array}, or {@code -1} if there is no such occurrence. * *
* More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly * the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(long[] array, long[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code long} values, possibly empty * @param target a primitive {@code long} value * @return the greatest index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int lastIndexOf(long[] array, long target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf(long[] array, long target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}. * * @param array a nonempty array of {@code long} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static long min(long... array) { checkArgument(array.length > 0); long min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a nonempty array of {@code long} values * @return the value present in {@code array} that is greater than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static long max(long... array) { checkArgument(array.length > 0); long max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the values from each provided array combined into a single array. For * example, {@code concat(new long[] {a, b}, new long[] {}, new long[] {c}} * returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code long} arrays * @return a single array containing all the values from the source arrays, in * order */ public static long[] concat(long[]... arrays) { int length = 0; for (long[] array : arrays) { length += array.length; } long[] result = new long[length]; int pos = 0; for (long[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns a big-endian representation of {@code value} in an 8-element byte * array; equivalent to {@code ByteBuffer.allocate(8).putLong(value).array()}. * For example, the input value {@code 0x1213141516171819L} would yield the byte * array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}}. * *
* If you need to convert and concatenate several values (possibly even of * different types), use a shared {@link java.nio.ByteBuffer} instance, or use * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable * buffer. */ public static byte[] toByteArray(long value) { // Note that this code needs to stay compatible with GWT, which has known // bugs when narrowing byte casts of long values occur. byte[] result = new byte[8]; for (int i = 7; i >= 0; i--) { result[i] = (byte) (value & 0xffL); value >>= 8; } return result; } /** * Returns the {@code long} value whose big-endian representation is stored in * the first 8 bytes of {@code bytes}; equivalent to {@code * ByteBuffer.wrap(bytes).getLong()}. For example, the input byte array * {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}} would yield the * {@code long} value {@code 0x1213141516171819L}. * *
* Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library
* exposes much more flexibility at little cost in readability.
*
* @throws IllegalArgumentException if {@code bytes} has fewer than 8 elements
*/
public static long fromByteArray(byte[] bytes) {
checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES);
return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]);
}
/**
* Returns the {@code long} value whose byte representation is the given 8
* bytes, in big-endian order; equivalent to {@code Longs.fromByteArray(new
* byte[] {b1, b2, b3, b4, b5, b6, b7, b8})}.
*
* @since 7.0
*/
public static long fromBytes(byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7, byte b8) {
return (b1 & 0xFFL) << 56 | (b2 & 0xFFL) << 48 | (b3 & 0xFFL) << 40 | (b4 & 0xFFL) << 32 | (b5 & 0xFFL) << 24
| (b6 & 0xFFL) << 16 | (b7 & 0xFFL) << 8 | (b8 & 0xFFL);
}
/**
* Parses the specified string as a signed decimal long value. The ASCII
* character {@code '-'} ('\u002D'
) is recognized as the minus
* sign.
*
*
* Unlike {@link Long#parseLong(String)}, this method returns {@code null} * instead of throwing an exception if parsing fails. Additionally, this method * only accepts ASCII digits, and returns {@code null} if non-ASCII digits are * present in the string. * *
* Note that strings prefixed with ASCII {@code '+'} are rejected, even under
* JDK 7, despite the change to {@link Long#parseLong(String)} for that version.
*
* @param string the string representation of a long value
* @return the long value represented by {@code string}, or {@code null} if
* {@code string} has a length of zero or cannot be parsed as a long
* value
* @since 14.0
*/
@Beta
public static Long tryParse(String string) {
if (checkNotNull(string).isEmpty()) {
return null;
}
boolean negative = string.charAt(0) == '-';
int index = negative ? 1 : 0;
if (index == string.length()) {
return null;
}
int digit = string.charAt(index++) - '0';
if (digit < 0 || digit > 9) {
return null;
}
long accum = -digit;
while (index < string.length()) {
digit = string.charAt(index++) - '0';
if (digit < 0 || digit > 9 || accum < Long.MIN_VALUE / 10) {
return null;
}
accum *= 10;
if (accum < Long.MIN_VALUE + digit) {
return null;
}
accum -= digit;
}
if (negative) {
return accum;
} else if (accum == Long.MIN_VALUE) {
return null;
} else {
return -accum;
}
}
private static final class LongConverter extends Converter
* The returned comparator is inconsistent with {@link Object#equals(Object)}
* (since arrays support only identity equality), but it is consistent with
* {@link Arrays#equals(long[], long[])}.
*
* @see
* Lexicographical order article at Wikipedia
* @since 2.0
*/
public static Comparator
* Elements are copied from the argument collection as if by {@code
* collection.toArray()}. Calling this method is as thread-safe as calling that
* method.
*
* @param collection a collection of {@code Number} instances
* @return an array containing the same values as {@code collection}, in the
* same order, converted to primitives
* @throws NullPointerException if {@code collection} or any of its elements is
* null
* @since 1.0 (parameter was {@code Collection
* The returned list maintains the values, but not the identities, of
* {@code Long} objects written to or read from it. For example, whether
* {@code list.get(0) == list.get(0)} is true for the returned list is
* unspecified.
*
* @param backingArray the array to back the list
* @return a list view of the array
*/
public static List