code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* 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 com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
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;
/**
* Static utility methods pertaining to {@code short} primitives, that are not
* already found in either {@link Short} or {@link Arrays}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@GwtCompatible(emulated = true)
public final class Shorts {
private Shorts() {}
/**
* The number of bytes required to represent a primitive {@code short}
* value.
*/
public static final int BYTES = Short.SIZE / Byte.SIZE;
/**
* The largest power of two that can be represented as a {@code short}.
*
* @since 10.0
*/
public static final short MAX_POWER_OF_TWO = 1 << (Short.SIZE - 2);
/**
* Returns a hash code for {@code value}; equal to the result of invoking
* {@code ((Short) value).hashCode()}.
*
* @param value a primitive {@code short} value
* @return a hash code for the value
*/
public static int hashCode(short value) {
return value;
}
/**
* Returns the {@code short} value that is equal to {@code value}, if
* possible.
*
* @param value any value in the range of the {@code short} type
* @return the {@code short} value that equals {@code value}
* @throws IllegalArgumentException if {@code value} is greater than {@link
* Short#MAX_VALUE} or less than {@link Short#MIN_VALUE}
*/
public static short checkedCast(long value) {
short result = (short) value;
checkArgument(result == value, "Out of range: %s", value);
return result;
}
/**
* Returns the {@code short} nearest in value to {@code value}.
*
* @param value any {@code long} value
* @return the same value cast to {@code short} if it is in the range of the
* {@code short} type, {@link Short#MAX_VALUE} if it is too large,
* or {@link Short#MIN_VALUE} if it is too small
*/
public static short saturatedCast(long value) {
if (value > Short.MAX_VALUE) {
return Short.MAX_VALUE;
}
if (value < Short.MIN_VALUE) {
return Short.MIN_VALUE;
}
return (short) value;
}
/**
* Compares the two specified {@code short} values. The sign of the value
* returned is the same as that of {@code ((Short) a).compareTo(b)}.
*
* @param a the first {@code short} to compare
* @param b the second {@code short} 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(short a, short b) {
return a - b; // safe due to restricted range
}
/**
* Returns {@code true} if {@code target} is present as an element anywhere in
* {@code array}.
*
* @param array an array of {@code short} values, possibly empty
* @param target a primitive {@code short} value
* @return {@code true} if {@code array[i] == target} for some value of {@code
* i}
*/
public static boolean contains(short[] array, short target) {
for (short 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 short} values, possibly empty
* @param target a primitive {@code short} 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(short[] array, short target) {
return indexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int indexOf(
short[] array, short 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.
*
* <p>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(short[] array, short[] 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 short} values, possibly empty
* @param target a primitive {@code short} 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(short[] array, short target) {
return lastIndexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int lastIndexOf(
short[] array, short 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 <i>nonempty</i> array of {@code short} 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 short min(short... array) {
checkArgument(array.length > 0);
short 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 <i>nonempty</i> array of {@code short} 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 short max(short... array) {
checkArgument(array.length > 0);
short 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 short[] {a, b}, new short[] {}, new
* short[] {c}} returns the array {@code {a, b, c}}.
*
* @param arrays zero or more {@code short} arrays
* @return a single array containing all the values from the source arrays, in
* order
*/
public static short[] concat(short[]... arrays) {
int length = 0;
for (short[] array : arrays) {
length += array.length;
}
short[] result = new short[length];
int pos = 0;
for (short[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
/**
* Returns a big-endian representation of {@code value} in a 2-element byte
* array; equivalent to {@code
* ByteBuffer.allocate(2).putShort(value).array()}. For example, the input
* value {@code (short) 0x1234} would yield the byte array {@code {0x12,
* 0x34}}.
*
* <p>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.
*/
@GwtIncompatible("doesn't work")
public static byte[] toByteArray(short value) {
return new byte[] {
(byte) (value >> 8),
(byte) value};
}
/**
* Returns the {@code short} value whose big-endian representation is
* stored in the first 2 bytes of {@code bytes}; equivalent to {@code
* ByteBuffer.wrap(bytes).getShort()}. For example, the input byte array
* {@code {0x54, 0x32}} would yield the {@code short} value {@code 0x5432}.
*
* <p>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 2
* elements
*/
@GwtIncompatible("doesn't work")
public static short fromByteArray(byte[] bytes) {
checkArgument(bytes.length >= BYTES,
"array too small: %s < %s", bytes.length, BYTES);
return fromBytes(bytes[0], bytes[1]);
}
/**
* Returns the {@code short} value whose byte representation is the given 2
* bytes, in big-endian order; equivalent to {@code Shorts.fromByteArray(new
* byte[] {b1, b2})}.
*
* @since 7.0
*/
@GwtIncompatible("doesn't work")
public static short fromBytes(byte b1, byte b2) {
return (short) ((b1 << 8) | (b2 & 0xFF));
}
/**
* Returns an array containing the same values as {@code array}, but
* guaranteed to be of a specified minimum length. If {@code array} already
* has a length of at least {@code minLength}, it is returned directly.
* Otherwise, a new array of size {@code minLength + padding} is returned,
* containing the values of {@code array}, and zeroes in the remaining places.
*
* @param array the source array
* @param minLength the minimum length the returned array must guarantee
* @param padding an extra amount to "grow" the array by if growth is
* necessary
* @throws IllegalArgumentException if {@code minLength} or {@code padding} is
* negative
* @return an array containing the values of {@code array}, with guaranteed
* minimum length {@code minLength}
*/
public static short[] ensureCapacity(
short[] array, int minLength, int padding) {
checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
checkArgument(padding >= 0, "Invalid padding: %s", padding);
return (array.length < minLength)
? copyOf(array, minLength + padding)
: array;
}
// Arrays.copyOf() requires Java 6
private static short[] copyOf(short[] original, int length) {
short[] copy = new short[length];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
return copy;
}
/**
* Returns a string containing the supplied {@code short} values separated
* by {@code separator}. For example, {@code join("-", (short) 1, (short) 2,
* (short) 3)} returns the string {@code "1-2-3"}.
*
* @param separator the text that should appear between consecutive values in
* the resulting string (but not at the start or end)
* @param array an array of {@code short} values, possibly empty
*/
public static String join(String separator, short... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 6);
builder.append(array[0]);
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
/**
* Returns a comparator that compares two {@code short} arrays
* lexicographically. That is, it compares, using {@link
* #compare(short, short)}), the first pair of values that follow any
* common prefix, or when one array is a prefix of the other, treats the
* shorter array as the lesser. For example, {@code [] < [(short) 1] <
* [(short) 1, (short) 2] < [(short) 2]}.
*
* <p>The returned comparator is inconsistent with {@link
* Object#equals(Object)} (since arrays support only identity equality), but
* it is consistent with {@link Arrays#equals(short[], short[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
* Lexicographical order article at Wikipedia</a>
* @since 2.0
*/
public static Comparator<short[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
private enum LexicographicalComparator implements Comparator<short[]> {
INSTANCE;
@Override
public int compare(short[] left, short[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = Shorts.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
}
/**
* Returns an array containing each value of {@code collection}, converted to
* a {@code short} value in the manner of {@link Number#shortValue}.
*
* <p>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<Short>} before 12.0)
*/
public static short[] toArray(Collection<? extends Number> collection) {
if (collection instanceof ShortArrayAsList) {
return ((ShortArrayAsList) collection).toShortArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
short[] array = new short[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = ((Number) checkNotNull(boxedArray[i])).shortValue();
}
return array;
}
/**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
* but any attempt to set a value to {@code null} will result in a {@link
* NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of
* {@code Short} 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<Short> asList(short... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new ShortArrayAsList(backingArray);
}
@GwtCompatible
private static class ShortArrayAsList extends AbstractList<Short>
implements RandomAccess, Serializable {
final short[] array;
final int start;
final int end;
ShortArrayAsList(short[] array) {
this(array, 0, array.length);
}
ShortArrayAsList(short[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override public int size() {
return end - start;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Short get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override public boolean contains(Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Short)
&& Shorts.indexOf(array, (Short) target, start, end) != -1;
}
@Override public int indexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Short) {
int i = Shorts.indexOf(array, (Short) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public int lastIndexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Short) {
int i = Shorts.lastIndexOf(array, (Short) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public Short set(int index, Short element) {
checkElementIndex(index, size());
short oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override public List<Short> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new ShortArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof ShortArrayAsList) {
ShortArrayAsList that = (ShortArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Shorts.hashCode(array[i]);
}
return result;
}
@Override public String toString() {
StringBuilder builder = new StringBuilder(size() * 6);
builder.append('[').append(array[start]);
for (int i = start + 1; i < end; i++) {
builder.append(", ").append(array[i]);
}
return builder.append(']').toString();
}
short[] toShortArray() {
// Arrays.copyOfRange() is not available under GWT
int size = size();
short[] result = new short[size];
System.arraycopy(array, start, result, 0, size);
return result;
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* Copyright (C) 2011 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.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Arrays;
import java.util.Comparator;
/**
* Static utility methods pertaining to {@code int} primitives that interpret values as
* <i>unsigned</i> (that is, any negative value {@code x} is treated as the positive value
* {@code 2^32 + x}). The methods for which signedness is not an issue are in {@link Ints}, as well
* as signed versions of methods for which signedness is an issue.
*
* <p>In addition, this class provides several static methods for converting an {@code int} to a
* {@code String} and a {@code String} to an {@code int} that treat the {@code int} as an unsigned
* number.
*
* <p>Users of these utilities must be <i>extremely careful</i> not to mix up signed and unsigned
* {@code int} values. When possible, it is recommended that the {@link UnsignedInteger} wrapper
* class be used, at a small efficiency penalty, to enforce the distinction in the type system.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained#Unsigned_support">
* unsigned primitive utilities</a>.
*
* @author Louis Wasserman
* @since 11.0
*/
@Beta
@GwtCompatible
public final class UnsignedInts {
static final long INT_MASK = 0xffffffffL;
private UnsignedInts() {}
static int flip(int value) {
return value ^ Integer.MIN_VALUE;
}
/**
* Compares the two specified {@code int} values, treating them as unsigned values between
* {@code 0} and {@code 2^32 - 1} inclusive.
*
* @param a the first unsigned {@code int} to compare
* @param b the second unsigned {@code int} 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(int a, int b) {
return Ints.compare(flip(a), flip(b));
}
/**
* Returns the value of the given {@code int} as a {@code long}, when treated as unsigned.
*/
public static long toLong(int value) {
return value & INT_MASK;
}
/**
* Returns the least value present in {@code array}, treating values as unsigned.
*
* @param array a <i>nonempty</i> array of unsigned {@code int} values
* @return the value present in {@code array} that is less than or equal to every other value in
* the array according to {@link #compare}
* @throws IllegalArgumentException if {@code array} is empty
*/
public static int min(int... array) {
checkArgument(array.length > 0);
int min = flip(array[0]);
for (int i = 1; i < array.length; i++) {
int next = flip(array[i]);
if (next < min) {
min = next;
}
}
return flip(min);
}
/**
* Returns the greatest value present in {@code array}, treating values as unsigned.
*
* @param array a <i>nonempty</i> array of unsigned {@code int} values
* @return the value present in {@code array} that is greater than or equal to every other value
* in the array according to {@link #compare}
* @throws IllegalArgumentException if {@code array} is empty
*/
public static int max(int... array) {
checkArgument(array.length > 0);
int max = flip(array[0]);
for (int i = 1; i < array.length; i++) {
int next = flip(array[i]);
if (next > max) {
max = next;
}
}
return flip(max);
}
/**
* Returns a string containing the supplied unsigned {@code int} values separated by
* {@code separator}. For example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}.
*
* @param separator the text that should appear between consecutive values in the resulting
* string (but not at the start or end)
* @param array an array of unsigned {@code int} values, possibly empty
*/
public static String join(String separator, int... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 5);
builder.append(toString(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(toString(array[i]));
}
return builder.toString();
}
/**
* Returns a comparator that compares two arrays of unsigned {@code int} values lexicographically.
* That is, it compares, using {@link #compare(int, int)}), the first pair of values that follow
* any common prefix, or when one array is a prefix of the other, treats the shorter array as the
* lesser. For example, {@code [] < [1] < [1, 2] < [2] < [1 << 31]}.
*
* <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
* support only identity equality), but it is consistent with {@link Arrays#equals(int[], int[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> Lexicographical order
* article at Wikipedia</a>
*/
public static Comparator<int[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
enum LexicographicalComparator implements Comparator<int[]> {
INSTANCE;
@Override
public int compare(int[] left, int[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
if (left[i] != right[i]) {
return UnsignedInts.compare(left[i], right[i]);
}
}
return left.length - right.length;
}
}
/**
* Returns dividend / divisor, where the dividend and divisor are treated as unsigned 32-bit
* quantities.
*
* @param dividend the dividend (numerator)
* @param divisor the divisor (denominator)
* @throws ArithmeticException if divisor is 0
*/
public static int divide(int dividend, int divisor) {
return (int) (toLong(dividend) / toLong(divisor));
}
/**
* Returns dividend % divisor, where the dividend and divisor are treated as unsigned 32-bit
* quantities.
*
* @param dividend the dividend (numerator)
* @param divisor the divisor (denominator)
* @throws ArithmeticException if divisor is 0
*/
public static int remainder(int dividend, int divisor) {
return (int) (toLong(dividend) % toLong(divisor));
}
/**
* Returns the unsigned {@code int} value represented by the given string.
*
* Accepts a decimal, hexadecimal, or octal number given by specifying the following prefix:
*
* <ul>
* <li>{@code 0x}<i>HexDigits</i>
* <li>{@code 0X}<i>HexDigits</i>
* <li>{@code #}<i>HexDigits</i>
* <li>{@code 0}<i>OctalDigits</i>
* </ul>
*
* @throws NumberFormatException if the string does not contain a valid unsigned {@code int} value
* @since 13.0
*/
public static int decode(String stringValue) {
ParseRequest request = ParseRequest.fromString(stringValue);
try {
return parseUnsignedInt(request.rawValue, request.radix);
} catch (NumberFormatException e) {
NumberFormatException decodeException =
new NumberFormatException("Error parsing value: " + stringValue);
decodeException.initCause(e);
throw decodeException;
}
}
/**
* Returns the unsigned {@code int} value represented by the given decimal string.
*
* @throws NumberFormatException if the string does not contain a valid unsigned {@code int} value
* @throws NullPointerException if {@code s} is null
* (in contrast to {@link Integer#parseInt(String)})
*/
public static int parseUnsignedInt(String s) {
return parseUnsignedInt(s, 10);
}
/**
* Returns the unsigned {@code int} value represented by a string with the given radix.
*
* @param string the string containing the unsigned integer representation to be parsed.
* @param radix the radix to use while parsing {@code s}; must be between
* {@link Character#MIN_RADIX} and {@link Character#MAX_RADIX}.
* @throws NumberFormatException if the string does not contain a valid unsigned {@code int}, or
* if supplied radix is invalid.
* @throws NullPointerException if {@code s} is null
* (in contrast to {@link Integer#parseInt(String)})
*/
public static int parseUnsignedInt(String string, int radix) {
checkNotNull(string);
long result = Long.parseLong(string, radix);
if ((result & INT_MASK) != result) {
throw new NumberFormatException("Input " + string + " in base " + radix
+ " is not in the range of an unsigned integer");
}
return (int) result;
}
/**
* Returns a string representation of x, where x is treated as unsigned.
*/
public static String toString(int x) {
return toString(x, 10);
}
/**
* Returns a string representation of {@code x} for the given radix, where {@code x} is treated
* as unsigned.
*
* @param x the value to convert to a string.
* @param radix the radix to use while working with {@code x}
* @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX}
* and {@link Character#MAX_RADIX}.
*/
public static String toString(int x, int radix) {
long asLong = x & INT_MASK;
return Long.toString(asLong, radix);
}
}
| Java |
/*
* Copyright (C) 2010 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.
*/
/**
* Static utilities for working with the eight primitive types and {@code void},
* and value types for treating them as unsigned.
*
* <p>This package is a part of the open-source
* <a href="http://guava-libraries.googlecode.com">Guava libraries</a>.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* <h2>Contents</h2>
*
* <h3>General static utilities</h3>
*
* <ul>
* <li>{@link com.google.common.primitives.Primitives}
* </ul>
*
* <h3>Per-type static utilities</h3>
*
* <ul>
* <li>{@link com.google.common.primitives.Booleans}
* <li>{@link com.google.common.primitives.Bytes}
* <ul>
* <li>{@link com.google.common.primitives.SignedBytes}
* <li>{@link com.google.common.primitives.UnsignedBytes}
* </ul>
* <li>{@link com.google.common.primitives.Chars}
* <li>{@link com.google.common.primitives.Doubles}
* <li>{@link com.google.common.primitives.Floats}
* <li>{@link com.google.common.primitives.Ints}
* <ul>
* <li>{@link com.google.common.primitives.UnsignedInts}
* </ul>
* <li>{@link com.google.common.primitives.Longs}
* <ul>
* <li>{@link com.google.common.primitives.UnsignedLongs}
* </ul>
* <li>{@link com.google.common.primitives.Shorts}
* </ul>
*
* <h3>Value types</h3>
* <ul>
* <li>{@link com.google.common.primitives.UnsignedInteger}
* <li>{@link com.google.common.primitives.UnsignedLong}
* </ul>
*/
@ParametersAreNonnullByDefault
package com.google.common.primitives;
import javax.annotation.ParametersAreNonnullByDefault;
| Java |
/*
* Copyright (C) 2011 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.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Comparator;
/**
* Static utility methods pertaining to {@code long} primitives that interpret values as
* <i>unsigned</i> (that is, any negative value {@code x} is treated as the positive value
* {@code 2^64 + x}). The methods for which signedness is not an issue are in {@link Longs}, as
* well as signed versions of methods for which signedness is an issue.
*
* <p>In addition, this class provides several static methods for converting a {@code long} to a
* {@code String} and a {@code String} to a {@code long} that treat the {@code long} as an unsigned
* number.
*
* <p>Users of these utilities must be <i>extremely careful</i> not to mix up signed and unsigned
* {@code long} values. When possible, it is recommended that the {@link UnsignedLong} wrapper
* class be used, at a small efficiency penalty, to enforce the distinction in the type system.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained#Unsigned_support">
* unsigned primitive utilities</a>.
*
* @author Louis Wasserman
* @author Brian Milch
* @author Colin Evans
* @since 10.0
*/
@Beta
@GwtCompatible
public final class UnsignedLongs {
private UnsignedLongs() {}
public static final long MAX_VALUE = -1L; // Equivalent to 2^64 - 1
/**
* A (self-inverse) bijection which converts the ordering on unsigned longs to the ordering on
* longs, that is, {@code a <= b} as unsigned longs if and only if {@code flip(a) <= flip(b)}
* as signed longs.
*/
private static long flip(long a) {
return a ^ Long.MIN_VALUE;
}
/**
* Compares the two specified {@code long} values, treating them as unsigned values between
* {@code 0} and {@code 2^64 - 1} inclusive.
*
* @param a the first unsigned {@code long} to compare
* @param b the second unsigned {@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 Longs.compare(flip(a), flip(b));
}
/**
* Returns the least value present in {@code array}, treating values as unsigned.
*
* @param array a <i>nonempty</i> array of unsigned {@code long} values
* @return the value present in {@code array} that is less than or equal to every other value in
* the array according to {@link #compare}
* @throws IllegalArgumentException if {@code array} is empty
*/
public static long min(long... array) {
checkArgument(array.length > 0);
long min = flip(array[0]);
for (int i = 1; i < array.length; i++) {
long next = flip(array[i]);
if (next < min) {
min = next;
}
}
return flip(min);
}
/**
* Returns the greatest value present in {@code array}, treating values as unsigned.
*
* @param array a <i>nonempty</i> array of unsigned {@code long} values
* @return the value present in {@code array} that is greater than or equal to every other value
* in the array according to {@link #compare}
* @throws IllegalArgumentException if {@code array} is empty
*/
public static long max(long... array) {
checkArgument(array.length > 0);
long max = flip(array[0]);
for (int i = 1; i < array.length; i++) {
long next = flip(array[i]);
if (next > max) {
max = next;
}
}
return flip(max);
}
/**
* Returns a string containing the supplied unsigned {@code long} values separated by
* {@code separator}. For example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}.
*
* @param separator the text that should appear between consecutive values in the resulting
* string (but not at the start or end)
* @param array an array of unsigned {@code long} values, possibly empty
*/
public static String join(String separator, long... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 5);
builder.append(toString(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(toString(array[i]));
}
return builder.toString();
}
/**
* Returns a comparator that compares two arrays of unsigned {@code long} values
* lexicographically. That is, it compares, using {@link #compare(long, long)}), the first pair of
* values that follow any common prefix, or when one array is a prefix of the other, treats the
* shorter array as the lesser. For example, {@code [] < [1L] < [1L, 2L] < [2L] < [1L << 63]}.
*
* <p>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 <a href="http://en.wikipedia.org/wiki/Lexicographical_order">Lexicographical order
* article at Wikipedia</a>
*/
public static Comparator<long[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
enum LexicographicalComparator implements Comparator<long[]> {
INSTANCE;
@Override
public int compare(long[] left, long[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
if (left[i] != right[i]) {
return UnsignedLongs.compare(left[i], right[i]);
}
}
return left.length - right.length;
}
}
/**
* Returns dividend / divisor, where the dividend and divisor are treated as unsigned 64-bit
* quantities.
*
* @param dividend the dividend (numerator)
* @param divisor the divisor (denominator)
* @throws ArithmeticException if divisor is 0
*/
public static long divide(long dividend, long divisor) {
if (divisor < 0) { // i.e., divisor >= 2^63:
if (compare(dividend, divisor) < 0) {
return 0; // dividend < divisor
} else {
return 1; // dividend >= divisor
}
}
// Optimization - use signed division if dividend < 2^63
if (dividend >= 0) {
return dividend / divisor;
}
/*
* Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is
* guaranteed to be either exact or one less than the correct value. This follows from fact
* that floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not
* quite trivial.
*/
long quotient = ((dividend >>> 1) / divisor) << 1;
long rem = dividend - quotient * divisor;
return quotient + (compare(rem, divisor) >= 0 ? 1 : 0);
}
/**
* Returns dividend % divisor, where the dividend and divisor are treated as unsigned 64-bit
* quantities.
*
* @param dividend the dividend (numerator)
* @param divisor the divisor (denominator)
* @throws ArithmeticException if divisor is 0
* @since 11.0
*/
public static long remainder(long dividend, long divisor) {
if (divisor < 0) { // i.e., divisor >= 2^63:
if (compare(dividend, divisor) < 0) {
return dividend; // dividend < divisor
} else {
return dividend - divisor; // dividend >= divisor
}
}
// Optimization - use signed modulus if dividend < 2^63
if (dividend >= 0) {
return dividend % divisor;
}
/*
* Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is
* guaranteed to be either exact or one less than the correct value. This follows from fact
* that floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not
* quite trivial.
*/
long quotient = ((dividend >>> 1) / divisor) << 1;
long rem = dividend - quotient * divisor;
return rem - (compare(rem, divisor) >= 0 ? divisor : 0);
}
/**
* Returns the unsigned {@code long} value represented by the given decimal string.
*
* @throws NumberFormatException if the string does not contain a valid unsigned {@code long}
* value
* @throws NullPointerException if {@code s} is null
* (in contrast to {@link Long#parseLong(String)})
*/
public static long parseUnsignedLong(String s) {
return parseUnsignedLong(s, 10);
}
/**
* Returns the unsigned {@code long} value represented by the given string.
*
* Accepts a decimal, hexadecimal, or octal number given by specifying the following prefix:
*
* <ul>
* <li>{@code 0x}<i>HexDigits</i>
* <li>{@code 0X}<i>HexDigits</i>
* <li>{@code #}<i>HexDigits</i>
* <li>{@code 0}<i>OctalDigits</i>
* </ul>
*
* @throws NumberFormatException if the string does not contain a valid unsigned {@code long}
* value
* @since 13.0
*/
public static long decode(String stringValue) {
ParseRequest request = ParseRequest.fromString(stringValue);
try {
return parseUnsignedLong(request.rawValue, request.radix);
} catch (NumberFormatException e) {
NumberFormatException decodeException =
new NumberFormatException("Error parsing value: " + stringValue);
decodeException.initCause(e);
throw decodeException;
}
}
/**
* Returns the unsigned {@code long} value represented by a string with the given radix.
*
* @param s the string containing the unsigned {@code long} representation to be parsed.
* @param radix the radix to use while parsing {@code s}
* @throws NumberFormatException if the string does not contain a valid unsigned {@code long}
* with the given radix, or if {@code radix} is not between {@link Character#MIN_RADIX}
* and {@link Character#MAX_RADIX}.
* @throws NullPointerException if {@code s} is null
* (in contrast to {@link Long#parseLong(String)})
*/
public static long parseUnsignedLong(String s, int radix) {
checkNotNull(s);
if (s.length() == 0) {
throw new NumberFormatException("empty string");
}
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
throw new NumberFormatException("illegal radix: " + radix);
}
int max_safe_pos = maxSafeDigits[radix] - 1;
long value = 0;
for (int pos = 0; pos < s.length(); pos++) {
int digit = Character.digit(s.charAt(pos), radix);
if (digit == -1) {
throw new NumberFormatException(s);
}
if (pos > max_safe_pos && overflowInParse(value, digit, radix)) {
throw new NumberFormatException("Too large for unsigned long: " + s);
}
value = (value * radix) + digit;
}
return value;
}
/**
* Returns true if (current * radix) + digit is a number too large to be represented by an
* unsigned long. This is useful for detecting overflow while parsing a string representation of
* a number. Does not verify whether supplied radix is valid, passing an invalid radix will give
* undefined results or an ArrayIndexOutOfBoundsException.
*/
private static boolean overflowInParse(long current, int digit, int radix) {
if (current >= 0) {
if (current < maxValueDivs[radix]) {
return false;
}
if (current > maxValueDivs[radix]) {
return true;
}
// current == maxValueDivs[radix]
return (digit > maxValueMods[radix]);
}
// current < 0: high bit is set
return true;
}
/**
* Returns a string representation of x, where x is treated as unsigned.
*/
public static String toString(long x) {
return toString(x, 10);
}
/**
* Returns a string representation of {@code x} for the given radix, where {@code x} is treated
* as unsigned.
*
* @param x the value to convert to a string.
* @param radix the radix to use while working with {@code x}
* @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX}
* and {@link Character#MAX_RADIX}.
*/
public static String toString(long x, int radix) {
checkArgument(radix >= Character.MIN_RADIX && radix <= Character.MAX_RADIX,
"radix (%s) must be between Character.MIN_RADIX and Character.MAX_RADIX", radix);
if (x == 0) {
// Simply return "0"
return "0";
} else {
char[] buf = new char[64];
int i = buf.length;
if (x < 0) {
// Separate off the last digit using unsigned division. That will leave
// a number that is nonnegative as a signed integer.
long quotient = divide(x, radix);
long rem = x - quotient * radix;
buf[--i] = Character.forDigit((int) rem, radix);
x = quotient;
}
// Simple modulo/division approach
while (x > 0) {
buf[--i] = Character.forDigit((int) (x % radix), radix);
x /= radix;
}
// Generate string
return new String(buf, i, buf.length - i);
}
}
// calculated as 0xffffffffffffffff / radix
private static final long[] maxValueDivs = new long[Character.MAX_RADIX + 1];
private static final int[] maxValueMods = new int[Character.MAX_RADIX + 1];
private static final int[] maxSafeDigits = new int[Character.MAX_RADIX + 1];
static {
BigInteger overflow = new BigInteger("10000000000000000", 16);
for (int i = Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) {
maxValueDivs[i] = divide(MAX_VALUE, i);
maxValueMods[i] = (int) remainder(MAX_VALUE, i);
maxSafeDigits[i] = overflow.toString(i).length() - 1;
}
}
}
| Java |
/*
* 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 static java.lang.Double.NEGATIVE_INFINITY;
import static java.lang.Double.POSITIVE_INFINITY;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
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 java.util.regex.Pattern;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to {@code double} primitives, that are not
* already found in either {@link Double} or {@link Arrays}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@GwtCompatible(emulated = true)
public final class Doubles {
private Doubles() {}
/**
* The number of bytes required to represent a primitive {@code double}
* value.
*
* @since 10.0
*/
public static final int BYTES = Double.SIZE / Byte.SIZE;
/**
* Returns a hash code for {@code value}; equal to the result of invoking
* {@code ((Double) value).hashCode()}.
*
* @param value a primitive {@code double} value
* @return a hash code for the value
*/
public static int hashCode(double value) {
return ((Double) value).hashCode();
// TODO(kevinb): do it this way when we can (GWT problem):
// long bits = Double.doubleToLongBits(value);
// return (int) (bits ^ (bits >>> 32));
}
/**
* Compares the two specified {@code double} values. The sign of the value
* returned is the same as that of <code>((Double) a).{@linkplain
* Double#compareTo compareTo}(b)</code>. As with that method, {@code NaN} is
* treated as greater than all other values, and {@code 0.0 > -0.0}.
*
* @param a the first {@code double} to compare
* @param b the second {@code double} 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(double a, double b) {
return Double.compare(a, b);
}
/**
* Returns {@code true} if {@code value} represents a real number. This is
* equivalent to, but not necessarily implemented as,
* {@code !(Double.isInfinite(value) || Double.isNaN(value))}.
*
* @since 10.0
*/
public static boolean isFinite(double value) {
return NEGATIVE_INFINITY < value & value < POSITIVE_INFINITY;
}
/**
* Returns {@code true} if {@code target} is present as an element anywhere in
* {@code array}. Note that this always returns {@code false} when {@code
* target} is {@code NaN}.
*
* @param array an array of {@code double} values, possibly empty
* @param target a primitive {@code double} value
* @return {@code true} if {@code array[i] == target} for some value of {@code
* i}
*/
public static boolean contains(double[] array, double target) {
for (double value : array) {
if (value == target) {
return true;
}
}
return false;
}
/**
* Returns the index of the first appearance of the value {@code target} in
* {@code array}. Note that this always returns {@code -1} when {@code target}
* is {@code NaN}.
*
* @param array an array of {@code double} values, possibly empty
* @param target a primitive {@code double} 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(double[] array, double target) {
return indexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int indexOf(
double[] array, double 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.
*
* <p>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}.
*
* <p>Note that this always returns {@code -1} when {@code target} contains
* {@code NaN}.
*
* @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(double[] array, double[] 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}. Note that this always returns {@code -1} when {@code target}
* is {@code NaN}.
*
* @param array an array of {@code double} values, possibly empty
* @param target a primitive {@code double} 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(double[] array, double target) {
return lastIndexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int lastIndexOf(
double[] array, double 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}, using the same rules of
* comparison as {@link Math#min(double, double)}.
*
* @param array a <i>nonempty</i> array of {@code double} 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 double min(double... array) {
checkArgument(array.length > 0);
double min = array[0];
for (int i = 1; i < array.length; i++) {
min = Math.min(min, array[i]);
}
return min;
}
/**
* Returns the greatest value present in {@code array}, using the same rules
* of comparison as {@link Math#max(double, double)}.
*
* @param array a <i>nonempty</i> array of {@code double} 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 double max(double... array) {
checkArgument(array.length > 0);
double max = array[0];
for (int i = 1; i < array.length; i++) {
max = Math.max(max, array[i]);
}
return max;
}
/**
* Returns the values from each provided array combined into a single array.
* For example, {@code concat(new double[] {a, b}, new double[] {}, new
* double[] {c}} returns the array {@code {a, b, c}}.
*
* @param arrays zero or more {@code double} arrays
* @return a single array containing all the values from the source arrays, in
* order
*/
public static double[] concat(double[]... arrays) {
int length = 0;
for (double[] array : arrays) {
length += array.length;
}
double[] result = new double[length];
int pos = 0;
for (double[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
/**
* Returns an array containing the same values as {@code array}, but
* guaranteed to be of a specified minimum length. If {@code array} already
* has a length of at least {@code minLength}, it is returned directly.
* Otherwise, a new array of size {@code minLength + padding} is returned,
* containing the values of {@code array}, and zeroes in the remaining places.
*
* @param array the source array
* @param minLength the minimum length the returned array must guarantee
* @param padding an extra amount to "grow" the array by if growth is
* necessary
* @throws IllegalArgumentException if {@code minLength} or {@code padding} is
* negative
* @return an array containing the values of {@code array}, with guaranteed
* minimum length {@code minLength}
*/
public static double[] ensureCapacity(
double[] array, int minLength, int padding) {
checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
checkArgument(padding >= 0, "Invalid padding: %s", padding);
return (array.length < minLength)
? copyOf(array, minLength + padding)
: array;
}
// Arrays.copyOf() requires Java 6
private static double[] copyOf(double[] original, int length) {
double[] copy = new double[length];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
return copy;
}
/**
* Returns a string containing the supplied {@code double} values, converted
* to strings as specified by {@link Double#toString(double)}, and separated
* by {@code separator}. For example, {@code join("-", 1.0, 2.0, 3.0)} returns
* the string {@code "1.0-2.0-3.0"}.
*
* <p>Note that {@link Double#toString(double)} formats {@code double}
* differently in GWT sometimes. In the previous example, it returns the
* string {@code "1-2-3"}.
*
* @param separator the text that should appear between consecutive values in
* the resulting string (but not at the start or end)
* @param array an array of {@code double} values, possibly empty
*/
public static String join(String separator, double... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 12);
builder.append(array[0]);
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
/**
* Returns a comparator that compares two {@code double} arrays
* lexicographically. That is, it compares, using {@link
* #compare(double, double)}), the first pair of values that follow any
* common prefix, or when one array is a prefix of the other, treats the
* shorter array as the lesser. For example,
* {@code [] < [1.0] < [1.0, 2.0] < [2.0]}.
*
* <p>The returned comparator is inconsistent with {@link
* Object#equals(Object)} (since arrays support only identity equality), but
* it is consistent with {@link Arrays#equals(double[], double[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
* Lexicographical order article at Wikipedia</a>
* @since 2.0
*/
public static Comparator<double[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
private enum LexicographicalComparator implements Comparator<double[]> {
INSTANCE;
@Override
public int compare(double[] left, double[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = Doubles.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
}
/**
* Returns an array containing each value of {@code collection}, converted to
* a {@code double} value in the manner of {@link Number#doubleValue}.
*
* <p>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<Double>} before 12.0)
*/
public static double[] toArray(Collection<? extends Number> collection) {
if (collection instanceof DoubleArrayAsList) {
return ((DoubleArrayAsList) collection).toDoubleArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
double[] array = new double[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = ((Number) checkNotNull(boxedArray[i])).doubleValue();
}
return array;
}
/**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
* but any attempt to set a value to {@code null} will result in a {@link
* NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of
* {@code Double} 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.
*
* <p>The returned list may have unexpected behavior if it contains {@code
* NaN}, or if {@code NaN} is used as a parameter to any of its methods.
*
* @param backingArray the array to back the list
* @return a list view of the array
*/
public static List<Double> asList(double... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new DoubleArrayAsList(backingArray);
}
@GwtCompatible
private static class DoubleArrayAsList extends AbstractList<Double>
implements RandomAccess, Serializable {
final double[] array;
final int start;
final int end;
DoubleArrayAsList(double[] array) {
this(array, 0, array.length);
}
DoubleArrayAsList(double[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override public int size() {
return end - start;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Double get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override public boolean contains(Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Double)
&& Doubles.indexOf(array, (Double) target, start, end) != -1;
}
@Override public int indexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Double) {
int i = Doubles.indexOf(array, (Double) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public int lastIndexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Double) {
int i = Doubles.lastIndexOf(array, (Double) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public Double set(int index, Double element) {
checkElementIndex(index, size());
double oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override public List<Double> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new DoubleArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof DoubleArrayAsList) {
DoubleArrayAsList that = (DoubleArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Doubles.hashCode(array[i]);
}
return result;
}
@Override public String toString() {
StringBuilder builder = new StringBuilder(size() * 12);
builder.append('[').append(array[start]);
for (int i = start + 1; i < end; i++) {
builder.append(", ").append(array[i]);
}
return builder.append(']').toString();
}
double[] toDoubleArray() {
// Arrays.copyOfRange() is not available under GWT
int size = size();
double[] result = new double[size];
System.arraycopy(array, start, result, 0, size);
return result;
}
private static final long serialVersionUID = 0;
}
/**
* This is adapted from the regex suggested by {@link Double#valueOf(String)}
* for prevalidating inputs. All valid inputs must pass this regex, but it's
* semantically fine if not all inputs that pass this regex are valid --
* only a performance hit is incurred, not a semantics bug.
*/
@GwtIncompatible("regular expressions")
static final Pattern FLOATING_POINT_PATTERN = fpPattern();
@GwtIncompatible("regular expressions")
private static Pattern fpPattern() {
String decimal = "(?:\\d++(?:\\.\\d*+)?|\\.\\d++)";
String completeDec = decimal + "(?:[eE][+-]?\\d++)?[fFdD]?";
String hex = "(?:\\p{XDigit}++(?:\\.\\p{XDigit}*+)?|\\.\\p{XDigit}++)";
String completeHex = "0[xX]" + hex + "[pP][+-]?\\d++[fFdD]?";
String fpPattern = "[+-]?(?:NaN|Infinity|" + completeDec + "|" + completeHex + ")";
return Pattern.compile(fpPattern);
}
/**
* Parses the specified string as a double-precision floating point value.
* The ASCII character {@code '-'} (<code>'\u002D'</code>) is recognized
* as the minus sign.
*
* <p>Unlike {@link Double#parseDouble(String)}, this method returns
* {@code null} instead of throwing an exception if parsing fails.
* Valid inputs are exactly those accepted by {@link Double#valueOf(String)},
* except that leading and trailing whitespace is not permitted.
*
* <p>This implementation is likely to be faster than {@code
* Double.parseDouble} if many failures are expected.
*
* @param string the string representation of a {@code double} value
* @return the floating point value represented by {@code string}, or
* {@code null} if {@code string} has a length of zero or cannot be
* parsed as a {@code double} value
* @since 14.0
*/
@GwtIncompatible("regular expressions")
@Nullable
@Beta
public static Double tryParse(String string) {
if (FLOATING_POINT_PATTERN.matcher(string).matches()) {
// TODO(user): could be potentially optimized, but only with
// extensive testing
try {
return Double.parseDouble(string);
} catch (NumberFormatException e) {
// Double.parseDouble has changed specs several times, so fall through
// gracefully
}
}
return null;
}
}
| Java |
/*
* Copyright (C) 2011 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 com.google.common.annotations.GwtCompatible;
/**
* A string to be parsed as a number and the radix to interpret it in.
*/
@GwtCompatible
final class ParseRequest {
final String rawValue;
final int radix;
private ParseRequest(String rawValue, int radix) {
this.rawValue = rawValue;
this.radix = radix;
}
static ParseRequest fromString(String stringValue) {
if (stringValue.length() == 0) {
throw new NumberFormatException("empty string");
}
// Handle radix specifier if present
String rawValue;
int radix;
char firstChar = stringValue.charAt(0);
if (stringValue.startsWith("0x") || stringValue.startsWith("0X")) {
rawValue = stringValue.substring(2);
radix = 16;
} else if (firstChar == '#') {
rawValue = stringValue.substring(1);
radix = 16;
} else if (firstChar == '0' && stringValue.length() > 1) {
rawValue = stringValue.substring(1);
radix = 8;
} else {
rawValue = stringValue;
radix = 10;
}
return new ParseRequest(rawValue, radix);
}
}
| Java |
/*
* Copyright (C) 2007 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.checkNotNull;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Contains static utility methods pertaining to primitive types and their
* corresponding wrapper types.
*
* @author Kevin Bourrillion
* @since 1.0
*/
public final class Primitives {
private Primitives() {}
/** A map from primitive types to their corresponding wrapper types. */
private static final Map<Class<?>, Class<?>> PRIMITIVE_TO_WRAPPER_TYPE;
/** A map from wrapper types to their corresponding primitive types. */
private static final Map<Class<?>, Class<?>> WRAPPER_TO_PRIMITIVE_TYPE;
// Sad that we can't use a BiMap. :(
static {
Map<Class<?>, Class<?>> primToWrap = new HashMap<Class<?>, Class<?>>(16);
Map<Class<?>, Class<?>> wrapToPrim = new HashMap<Class<?>, Class<?>>(16);
add(primToWrap, wrapToPrim, boolean.class, Boolean.class);
add(primToWrap, wrapToPrim, byte.class, Byte.class);
add(primToWrap, wrapToPrim, char.class, Character.class);
add(primToWrap, wrapToPrim, double.class, Double.class);
add(primToWrap, wrapToPrim, float.class, Float.class);
add(primToWrap, wrapToPrim, int.class, Integer.class);
add(primToWrap, wrapToPrim, long.class, Long.class);
add(primToWrap, wrapToPrim, short.class, Short.class);
add(primToWrap, wrapToPrim, void.class, Void.class);
PRIMITIVE_TO_WRAPPER_TYPE = Collections.unmodifiableMap(primToWrap);
WRAPPER_TO_PRIMITIVE_TYPE = Collections.unmodifiableMap(wrapToPrim);
}
private static void add(Map<Class<?>, Class<?>> forward,
Map<Class<?>, Class<?>> backward, Class<?> key, Class<?> value) {
forward.put(key, value);
backward.put(value, key);
}
/**
* Returns an immutable set of all nine primitive types (including {@code
* void}). Note that a simpler way to test whether a {@code Class} instance
* is a member of this set is to call {@link Class#isPrimitive}.
*
* @since 3.0
*/
public static Set<Class<?>> allPrimitiveTypes() {
return PRIMITIVE_TO_WRAPPER_TYPE.keySet();
}
/**
* Returns an immutable set of all nine primitive-wrapper types (including
* {@link Void}).
*
* @since 3.0
*/
public static Set<Class<?>> allWrapperTypes() {
return WRAPPER_TO_PRIMITIVE_TYPE.keySet();
}
/**
* Returns {@code true} if {@code type} is one of the nine
* primitive-wrapper types, such as {@link Integer}.
*
* @see Class#isPrimitive
*/
public static boolean isWrapperType(Class<?> type) {
return WRAPPER_TO_PRIMITIVE_TYPE.containsKey(checkNotNull(type));
}
/**
* Returns the corresponding wrapper type of {@code type} if it is a primitive
* type; otherwise returns {@code type} itself. Idempotent.
* <pre>
* wrap(int.class) == Integer.class
* wrap(Integer.class) == Integer.class
* wrap(String.class) == String.class
* </pre>
*/
public static <T> Class<T> wrap(Class<T> type) {
checkNotNull(type);
// cast is safe: long.class and Long.class are both of type Class<Long>
@SuppressWarnings("unchecked")
Class<T> wrapped = (Class<T>) PRIMITIVE_TO_WRAPPER_TYPE.get(type);
return (wrapped == null) ? type : wrapped;
}
/**
* Returns the corresponding primitive type of {@code type} if it is a
* wrapper type; otherwise returns {@code type} itself. Idempotent.
* <pre>
* unwrap(Integer.class) == int.class
* unwrap(int.class) == int.class
* unwrap(String.class) == String.class
* </pre>
*/
public static <T> Class<T> unwrap(Class<T> type) {
checkNotNull(type);
// cast is safe: long.class and Long.class are both of type Class<Long>
@SuppressWarnings("unchecked")
Class<T> unwrapped = (Class<T>) WRAPPER_TO_PRIMITIVE_TYPE.get(type);
return (unwrapped == null) ? type : unwrapped;
}
}
| Java |
/*
* Copyright (C) 2011 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.checkNotNull;
import static com.google.common.primitives.UnsignedInts.INT_MASK;
import static com.google.common.primitives.UnsignedInts.compare;
import static com.google.common.primitives.UnsignedInts.toLong;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.math.BigInteger;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
/**
* A wrapper class for unsigned {@code int} values, supporting arithmetic operations.
*
* <p>In some cases, when speed is more important than code readability, it may be faster simply to
* treat primitive {@code int} values as unsigned, using the methods from {@link UnsignedInts}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained#Unsigned_support">
* unsigned primitive utilities</a>.
*
* @author Louis Wasserman
* @since 11.0
*/
@GwtCompatible(emulated = true)
public final class UnsignedInteger extends Number implements Comparable<UnsignedInteger> {
public static final UnsignedInteger ZERO = fromIntBits(0);
public static final UnsignedInteger ONE = fromIntBits(1);
public static final UnsignedInteger MAX_VALUE = fromIntBits(-1);
private final int value;
private UnsignedInteger(int value) {
// GWT doesn't consistently overflow values to make them 32-bit, so we need to force it.
this.value = value & 0xffffffff;
}
/**
* Returns an {@code UnsignedInteger} corresponding to a given bit representation.
* The argument is interpreted as an unsigned 32-bit value. Specifically, the sign bit
* of {@code bits} is interpreted as a normal bit, and all other bits are treated as usual.
*
* <p>If the argument is nonnegative, the returned result will be equal to {@code bits},
* otherwise, the result will be equal to {@code 2^32 + bits}.
*
* <p>To represent unsigned decimal constants, consider {@link #valueOf(long)} instead.
*
* @since 14.0
*/
public static UnsignedInteger fromIntBits(int bits) {
return new UnsignedInteger(bits);
}
/**
* Returns an {@code UnsignedInteger} that is equal to {@code value},
* if possible. The inverse operation of {@link #longValue()}.
*/
public static UnsignedInteger valueOf(long value) {
checkArgument((value & INT_MASK) == value,
"value (%s) is outside the range for an unsigned integer value", value);
return fromIntBits((int) value);
}
/**
* Returns a {@code UnsignedInteger} representing the same value as the specified
* {@link BigInteger}. This is the inverse operation of {@link #bigIntegerValue()}.
*
* @throws IllegalArgumentException if {@code value} is negative or {@code value >= 2^32}
*/
public static UnsignedInteger valueOf(BigInteger value) {
checkNotNull(value);
checkArgument(value.signum() >= 0 && value.bitLength() <= Integer.SIZE,
"value (%s) is outside the range for an unsigned integer value", value);
return fromIntBits(value.intValue());
}
/**
* Returns an {@code UnsignedInteger} holding the value of the specified {@code String}, parsed
* as an unsigned {@code int} value.
*
* @throws NumberFormatException if the string does not contain a parsable unsigned {@code int}
* value
*/
public static UnsignedInteger valueOf(String string) {
return valueOf(string, 10);
}
/**
* Returns an {@code UnsignedInteger} holding the value of the specified {@code String}, parsed
* as an unsigned {@code int} value in the specified radix.
*
* @throws NumberFormatException if the string does not contain a parsable unsigned {@code int}
* value
*/
public static UnsignedInteger valueOf(String string, int radix) {
return fromIntBits(UnsignedInts.parseUnsignedInt(string, radix));
}
/**
* Returns the result of adding this and {@code val}. If the result would have more than 32 bits,
* returns the low 32 bits of the result.
*
* @since 14.0
*/
@CheckReturnValue
public UnsignedInteger plus(UnsignedInteger val) {
return fromIntBits(this.value + checkNotNull(val).value);
}
/**
* Returns the result of subtracting this and {@code val}. If the result would be negative,
* returns the low 32 bits of the result.
*
* @since 14.0
*/
@CheckReturnValue
public UnsignedInteger minus(UnsignedInteger val) {
return fromIntBits(value - checkNotNull(val).value);
}
/**
* Returns the result of multiplying this and {@code val}. If the result would have more than 32
* bits, returns the low 32 bits of the result.
*
* @since 14.0
*/
@CheckReturnValue
@GwtIncompatible("Does not truncate correctly")
public UnsignedInteger times(UnsignedInteger val) {
// TODO(user): make this GWT-compatible
return fromIntBits(value * checkNotNull(val).value);
}
/**
* Returns the result of dividing this by {@code val}.
*
* @throws ArithmeticException if {@code val} is zero
* @since 14.0
*/
@CheckReturnValue
public UnsignedInteger dividedBy(UnsignedInteger val) {
return fromIntBits(UnsignedInts.divide(value, checkNotNull(val).value));
}
/**
* Returns this mod {@code val}.
*
* @throws ArithmeticException if {@code val} is zero
* @since 14.0
*/
@CheckReturnValue
public UnsignedInteger mod(UnsignedInteger val) {
return fromIntBits(UnsignedInts.remainder(value, checkNotNull(val).value));
}
/**
* Returns the value of this {@code UnsignedInteger} as an {@code int}. This is an inverse
* operation to {@link #fromIntBits}.
*
* <p>Note that if this {@code UnsignedInteger} holds a value {@code >= 2^31}, the returned value
* will be equal to {@code this - 2^32}.
*/
@Override
public int intValue() {
return value;
}
/**
* Returns the value of this {@code UnsignedInteger} as a {@code long}.
*/
@Override
public long longValue() {
return toLong(value);
}
/**
* Returns the value of this {@code UnsignedInteger} as a {@code float}, analogous to a widening
* primitive conversion from {@code int} to {@code float}, and correctly rounded.
*/
@Override
public float floatValue() {
return longValue();
}
/**
* Returns the value of this {@code UnsignedInteger} as a {@code float}, analogous to a widening
* primitive conversion from {@code int} to {@code double}, and correctly rounded.
*/
@Override
public double doubleValue() {
return longValue();
}
/**
* Returns the value of this {@code UnsignedInteger} as a {@link BigInteger}.
*/
public BigInteger bigIntegerValue() {
return BigInteger.valueOf(longValue());
}
/**
* Compares this unsigned integer to another unsigned integer.
* Returns {@code 0} if they are equal, a negative number if {@code this < other},
* and a positive number if {@code this > other}.
*/
@Override
public int compareTo(UnsignedInteger other) {
checkNotNull(other);
return compare(value, other.value);
}
@Override
public int hashCode() {
return value;
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof UnsignedInteger) {
UnsignedInteger other = (UnsignedInteger) obj;
return value == other.value;
}
return false;
}
/**
* Returns a string representation of the {@code UnsignedInteger} value, in base 10.
*/
@Override
public String toString() {
return toString(10);
}
/**
* Returns a string representation of the {@code UnsignedInteger} value, in base {@code radix}.
* If {@code radix < Character.MIN_RADIX} or {@code radix > Character.MAX_RADIX}, the radix
* {@code 10} is used.
*/
public String toString(int radix) {
return UnsignedInts.toString(value, radix);
}
}
| Java |
/*
* 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 static java.lang.Float.NEGATIVE_INFINITY;
import static java.lang.Float.POSITIVE_INFINITY;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
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 javax.annotation.Nullable;
/**
* Static utility methods pertaining to {@code float} primitives, that are not
* already found in either {@link Float} or {@link Arrays}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@GwtCompatible(emulated = true)
public final class Floats {
private Floats() {}
/**
* The number of bytes required to represent a primitive {@code float}
* value.
*
* @since 10.0
*/
public static final int BYTES = Float.SIZE / Byte.SIZE;
/**
* Returns a hash code for {@code value}; equal to the result of invoking
* {@code ((Float) value).hashCode()}.
*
* @param value a primitive {@code float} value
* @return a hash code for the value
*/
public static int hashCode(float value) {
// TODO(kevinb): is there a better way, that's still gwt-safe?
return ((Float) value).hashCode();
}
/**
* Compares the two specified {@code float} values using {@link
* Float#compare(float, float)}. You may prefer to invoke that method
* directly; this method exists only for consistency with the other utilities
* in this package.
*
* @param a the first {@code float} to compare
* @param b the second {@code float} to compare
* @return the result of invoking {@link Float#compare(float, float)}
*/
public static int compare(float a, float b) {
return Float.compare(a, b);
}
/**
* Returns {@code true} if {@code value} represents a real number. This is
* equivalent to, but not necessarily implemented as,
* {@code !(Float.isInfinite(value) || Float.isNaN(value))}.
*
* @since 10.0
*/
public static boolean isFinite(float value) {
return NEGATIVE_INFINITY < value & value < POSITIVE_INFINITY;
}
/**
* Returns {@code true} if {@code target} is present as an element anywhere in
* {@code array}. Note that this always returns {@code false} when {@code
* target} is {@code NaN}.
*
* @param array an array of {@code float} values, possibly empty
* @param target a primitive {@code float} value
* @return {@code true} if {@code array[i] == target} for some value of {@code
* i}
*/
public static boolean contains(float[] array, float target) {
for (float value : array) {
if (value == target) {
return true;
}
}
return false;
}
/**
* Returns the index of the first appearance of the value {@code target} in
* {@code array}. Note that this always returns {@code -1} when {@code target}
* is {@code NaN}.
*
* @param array an array of {@code float} values, possibly empty
* @param target a primitive {@code float} 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(float[] array, float target) {
return indexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int indexOf(
float[] array, float 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.
*
* <p>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}.
*
* <p>Note that this always returns {@code -1} when {@code target} contains
* {@code NaN}.
*
* @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(float[] array, float[] 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}. Note that this always returns {@code -1} when {@code target}
* is {@code NaN}.
*
* @param array an array of {@code float} values, possibly empty
* @param target a primitive {@code float} 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(float[] array, float target) {
return lastIndexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int lastIndexOf(
float[] array, float 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}, using the same rules of
* comparison as {@link Math#min(float, float)}.
*
* @param array a <i>nonempty</i> array of {@code float} 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 float min(float... array) {
checkArgument(array.length > 0);
float min = array[0];
for (int i = 1; i < array.length; i++) {
min = Math.min(min, array[i]);
}
return min;
}
/**
* Returns the greatest value present in {@code array}, using the same rules
* of comparison as {@link Math#min(float, float)}.
*
* @param array a <i>nonempty</i> array of {@code float} 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 float max(float... array) {
checkArgument(array.length > 0);
float max = array[0];
for (int i = 1; i < array.length; i++) {
max = Math.max(max, array[i]);
}
return max;
}
/**
* Returns the values from each provided array combined into a single array.
* For example, {@code concat(new float[] {a, b}, new float[] {}, new
* float[] {c}} returns the array {@code {a, b, c}}.
*
* @param arrays zero or more {@code float} arrays
* @return a single array containing all the values from the source arrays, in
* order
*/
public static float[] concat(float[]... arrays) {
int length = 0;
for (float[] array : arrays) {
length += array.length;
}
float[] result = new float[length];
int pos = 0;
for (float[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
/**
* Returns an array containing the same values as {@code array}, but
* guaranteed to be of a specified minimum length. If {@code array} already
* has a length of at least {@code minLength}, it is returned directly.
* Otherwise, a new array of size {@code minLength + padding} is returned,
* containing the values of {@code array}, and zeroes in the remaining places.
*
* @param array the source array
* @param minLength the minimum length the returned array must guarantee
* @param padding an extra amount to "grow" the array by if growth is
* necessary
* @throws IllegalArgumentException if {@code minLength} or {@code padding} is
* negative
* @return an array containing the values of {@code array}, with guaranteed
* minimum length {@code minLength}
*/
public static float[] ensureCapacity(
float[] array, int minLength, int padding) {
checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
checkArgument(padding >= 0, "Invalid padding: %s", padding);
return (array.length < minLength)
? copyOf(array, minLength + padding)
: array;
}
// Arrays.copyOf() requires Java 6
private static float[] copyOf(float[] original, int length) {
float[] copy = new float[length];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
return copy;
}
/**
* Returns a string containing the supplied {@code float} values, converted
* to strings as specified by {@link Float#toString(float)}, and separated by
* {@code separator}. For example, {@code join("-", 1.0f, 2.0f, 3.0f)}
* returns the string {@code "1.0-2.0-3.0"}.
*
* <p>Note that {@link Float#toString(float)} formats {@code float}
* differently in GWT. In the previous example, it returns the string {@code
* "1-2-3"}.
*
* @param separator the text that should appear between consecutive values in
* the resulting string (but not at the start or end)
* @param array an array of {@code float} values, possibly empty
*/
public static String join(String separator, float... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 12);
builder.append(array[0]);
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
/**
* Returns a comparator that compares two {@code float} arrays
* lexicographically. That is, it compares, using {@link
* #compare(float, float)}), the first pair of values that follow any
* common prefix, or when one array is a prefix of the other, treats the
* shorter array as the lesser. For example, {@code [] < [1.0f] < [1.0f, 2.0f]
* < [2.0f]}.
*
* <p>The returned comparator is inconsistent with {@link
* Object#equals(Object)} (since arrays support only identity equality), but
* it is consistent with {@link Arrays#equals(float[], float[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
* Lexicographical order article at Wikipedia</a>
* @since 2.0
*/
public static Comparator<float[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
private enum LexicographicalComparator implements Comparator<float[]> {
INSTANCE;
@Override
public int compare(float[] left, float[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = Floats.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
}
/**
* Returns an array containing each value of {@code collection}, converted to
* a {@code float} value in the manner of {@link Number#floatValue}.
*
* <p>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<Float>} before 12.0)
*/
public static float[] toArray(Collection<? extends Number> collection) {
if (collection instanceof FloatArrayAsList) {
return ((FloatArrayAsList) collection).toFloatArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
float[] array = new float[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = ((Number) checkNotNull(boxedArray[i])).floatValue();
}
return array;
}
/**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
* but any attempt to set a value to {@code null} will result in a {@link
* NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of
* {@code Float} 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.
*
* <p>The returned list may have unexpected behavior if it contains {@code
* NaN}, or if {@code NaN} is used as a parameter to any of its methods.
*
* @param backingArray the array to back the list
* @return a list view of the array
*/
public static List<Float> asList(float... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new FloatArrayAsList(backingArray);
}
@GwtCompatible
private static class FloatArrayAsList extends AbstractList<Float>
implements RandomAccess, Serializable {
final float[] array;
final int start;
final int end;
FloatArrayAsList(float[] array) {
this(array, 0, array.length);
}
FloatArrayAsList(float[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override public int size() {
return end - start;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Float get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override public boolean contains(Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Float)
&& Floats.indexOf(array, (Float) target, start, end) != -1;
}
@Override public int indexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Float) {
int i = Floats.indexOf(array, (Float) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public int lastIndexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Float) {
int i = Floats.lastIndexOf(array, (Float) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public Float set(int index, Float element) {
checkElementIndex(index, size());
float oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override public List<Float> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new FloatArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof FloatArrayAsList) {
FloatArrayAsList that = (FloatArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Floats.hashCode(array[i]);
}
return result;
}
@Override public String toString() {
StringBuilder builder = new StringBuilder(size() * 12);
builder.append('[').append(array[start]);
for (int i = start + 1; i < end; i++) {
builder.append(", ").append(array[i]);
}
return builder.append(']').toString();
}
float[] toFloatArray() {
// Arrays.copyOfRange() is not available under GWT
int size = size();
float[] result = new float[size];
System.arraycopy(array, start, result, 0, size);
return result;
}
private static final long serialVersionUID = 0;
}
/**
* Parses the specified string as a single-precision floating point value.
* The ASCII character {@code '-'} (<code>'\u002D'</code>) is recognized
* as the minus sign.
*
* <p>Unlike {@link Float#parseFloat(String)}, this method returns
* {@code null} instead of throwing an exception if parsing fails.
* Valid inputs are exactly those accepted by {@link Float#valueOf(String)},
* except that leading and trailing whitespace is not permitted.
*
* <p>This implementation is likely to be faster than {@code
* Float.parseFloat} if many failures are expected.
*
* @param string the string representation of a {@code float} value
* @return the floating point value represented by {@code string}, or
* {@code null} if {@code string} has a length of zero or cannot be
* parsed as a {@code float} value
* @since 14.0
*/
@GwtIncompatible("regular expressions")
@Nullable
@Beta
public static Float tryParse(String string) {
if (Doubles.FLOATING_POINT_PATTERN.matcher(string).matches()) {
// TODO(user): could be potentially optimized, but only with
// extensive testing
try {
return Float.parseFloat(string);
} catch (NumberFormatException e) {
// Float.parseFloat has changed specs several times, so fall through
// gracefully
}
}
return null;
}
}
| Java |
/*
* Copyright (C) 2009 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.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
/**
* Static utility methods pertaining to {@code byte} primitives that
* interpret values as signed. The corresponding methods that treat the values
* as unsigned are found in {@link UnsignedBytes}, and the methods for which
* signedness is not an issue are in {@link Bytes}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
// TODO(kevinb): how to prevent warning on UnsignedBytes when building GWT
// javadoc?
@GwtCompatible
public final class SignedBytes {
private SignedBytes() {}
/**
* The largest power of two that can be represented as a signed {@code byte}.
*
* @since 10.0
*/
public static final byte MAX_POWER_OF_TWO = 1 << 6;
/**
* Returns the {@code byte} value that is equal to {@code value}, if possible.
*
* @param value any value in the range of the {@code byte} type
* @return the {@code byte} value that equals {@code value}
* @throws IllegalArgumentException if {@code value} is greater than {@link
* Byte#MAX_VALUE} or less than {@link Byte#MIN_VALUE}
*/
public static byte checkedCast(long value) {
byte result = (byte) value;
checkArgument(result == value, "Out of range: %s", value);
return result;
}
/**
* Returns the {@code byte} nearest in value to {@code value}.
*
* @param value any {@code long} value
* @return the same value cast to {@code byte} if it is in the range of the
* {@code byte} type, {@link Byte#MAX_VALUE} if it is too large,
* or {@link Byte#MIN_VALUE} if it is too small
*/
public static byte saturatedCast(long value) {
if (value > Byte.MAX_VALUE) {
return Byte.MAX_VALUE;
}
if (value < Byte.MIN_VALUE) {
return Byte.MIN_VALUE;
}
return (byte) value;
}
/**
* Compares the two specified {@code byte} values. The sign of the value
* returned is the same as that of {@code ((Byte) a).compareTo(b)}.
*
* @param a the first {@code byte} to compare
* @param b the second {@code byte} 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(byte a, byte b) {
return a - b; // safe due to restricted range
}
/**
* Returns the least value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code byte} 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 byte min(byte... array) {
checkArgument(array.length > 0);
byte 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 <i>nonempty</i> array of {@code byte} 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 byte max(byte... array) {
checkArgument(array.length > 0);
byte max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
/**
* Returns a string containing the supplied {@code byte} values separated
* by {@code separator}. For example, {@code join(":", 0x01, 0x02, -0x01)}
* returns the string {@code "1:2:-1"}.
*
* @param separator the text that should appear between consecutive values in
* the resulting string (but not at the start or end)
* @param array an array of {@code byte} values, possibly empty
*/
public static String join(String separator, byte... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 5);
builder.append(array[0]);
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
/**
* Returns a comparator that compares two {@code byte} arrays
* lexicographically. That is, it compares, using {@link
* #compare(byte, byte)}), the first pair of values that follow any common
* prefix, or when one array is a prefix of the other, treats the shorter
* array as the lesser. For example, {@code [] < [0x01] < [0x01, 0x80] <
* [0x01, 0x7F] < [0x02]}. Values are treated as signed.
*
* <p>The returned comparator is inconsistent with {@link
* Object#equals(Object)} (since arrays support only identity equality), but
* it is consistent with {@link java.util.Arrays#equals(byte[], byte[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
* Lexicographical order article at Wikipedia</a>
* @since 2.0
*/
public static Comparator<byte[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
private enum LexicographicalComparator implements Comparator<byte[]> {
INSTANCE;
@Override
public int compare(byte[] left, byte[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = SignedBytes.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
}
}
| Java |
/*
* 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 com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.RandomAccess;
/**
* Static utility methods pertaining to {@code byte} primitives, that are not
* already found in either {@link Byte} or {@link Arrays}, <i>and interpret
* bytes as neither signed nor unsigned</i>. The methods which specifically
* treat bytes as signed or unsigned are found in {@link SignedBytes} and {@link
* UnsignedBytes}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
// TODO(kevinb): how to prevent warning on UnsignedBytes when building GWT
// javadoc?
@GwtCompatible
public final class Bytes {
private Bytes() {}
/**
* Returns a hash code for {@code value}; equal to the result of invoking
* {@code ((Byte) value).hashCode()}.
*
* @param value a primitive {@code byte} value
* @return a hash code for the value
*/
public static int hashCode(byte value) {
return value;
}
/**
* Returns {@code true} if {@code target} is present as an element anywhere in
* {@code array}.
*
* @param array an array of {@code byte} values, possibly empty
* @param target a primitive {@code byte} value
* @return {@code true} if {@code array[i] == target} for some value of {@code
* i}
*/
public static boolean contains(byte[] array, byte target) {
for (byte 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 byte} values, possibly empty
* @param target a primitive {@code byte} 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(byte[] array, byte target) {
return indexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int indexOf(
byte[] array, byte 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.
*
* <p>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(byte[] array, byte[] 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 byte} values, possibly empty
* @param target a primitive {@code byte} 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(byte[] array, byte target) {
return lastIndexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int lastIndexOf(
byte[] array, byte target, int start, int end) {
for (int i = end - 1; i >= start; i--) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the values from each provided array combined into a single array.
* For example, {@code concat(new byte[] {a, b}, new byte[] {}, new
* byte[] {c}} returns the array {@code {a, b, c}}.
*
* @param arrays zero or more {@code byte} arrays
* @return a single array containing all the values from the source arrays, in
* order
*/
public static byte[] concat(byte[]... arrays) {
int length = 0;
for (byte[] array : arrays) {
length += array.length;
}
byte[] result = new byte[length];
int pos = 0;
for (byte[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
/**
* Returns an array containing the same values as {@code array}, but
* guaranteed to be of a specified minimum length. If {@code array} already
* has a length of at least {@code minLength}, it is returned directly.
* Otherwise, a new array of size {@code minLength + padding} is returned,
* containing the values of {@code array}, and zeroes in the remaining places.
*
* @param array the source array
* @param minLength the minimum length the returned array must guarantee
* @param padding an extra amount to "grow" the array by if growth is
* necessary
* @throws IllegalArgumentException if {@code minLength} or {@code padding} is
* negative
* @return an array containing the values of {@code array}, with guaranteed
* minimum length {@code minLength}
*/
public static byte[] ensureCapacity(
byte[] array, int minLength, int padding) {
checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
checkArgument(padding >= 0, "Invalid padding: %s", padding);
return (array.length < minLength)
? copyOf(array, minLength + padding)
: array;
}
// Arrays.copyOf() requires Java 6
private static byte[] copyOf(byte[] original, int length) {
byte[] copy = new byte[length];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
return copy;
}
/**
* Returns an array containing each value of {@code collection}, converted to
* a {@code byte} value in the manner of {@link Number#byteValue}.
*
* <p>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<Byte>} before 12.0)
*/
public static byte[] toArray(Collection<? extends Number> collection) {
if (collection instanceof ByteArrayAsList) {
return ((ByteArrayAsList) collection).toByteArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
byte[] array = new byte[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = ((Number) checkNotNull(boxedArray[i])).byteValue();
}
return array;
}
/**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
* but any attempt to set a value to {@code null} will result in a {@link
* NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of
* {@code Byte} 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<Byte> asList(byte... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new ByteArrayAsList(backingArray);
}
@GwtCompatible
private static class ByteArrayAsList extends AbstractList<Byte>
implements RandomAccess, Serializable {
final byte[] array;
final int start;
final int end;
ByteArrayAsList(byte[] array) {
this(array, 0, array.length);
}
ByteArrayAsList(byte[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override public int size() {
return end - start;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Byte get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override public boolean contains(Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Byte)
&& Bytes.indexOf(array, (Byte) target, start, end) != -1;
}
@Override public int indexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Byte) {
int i = Bytes.indexOf(array, (Byte) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public int lastIndexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Byte) {
int i = Bytes.lastIndexOf(array, (Byte) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public Byte set(int index, Byte element) {
checkElementIndex(index, size());
byte oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override public List<Byte> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new ByteArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof ByteArrayAsList) {
ByteArrayAsList that = (ByteArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Bytes.hashCode(array[i]);
}
return result;
}
@Override public String toString() {
StringBuilder builder = new StringBuilder(size() * 5);
builder.append('[').append(array[start]);
for (int i = start + 1; i < end; i++) {
builder.append(", ").append(array[i]);
}
return builder.append(']').toString();
}
byte[] toByteArray() {
// Arrays.copyOfRange() is not available under GWT
int size = size();
byte[] result = new byte[size];
System.arraycopy(array, start, result, 0, size);
return result;
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* 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 com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.RandomAccess;
/**
* Static utility methods pertaining to {@code boolean} primitives, that are not
* already found in either {@link Boolean} or {@link Arrays}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@GwtCompatible
public final class Booleans {
private Booleans() {}
/**
* Returns a hash code for {@code value}; equal to the result of invoking
* {@code ((Boolean) value).hashCode()}.
*
* @param value a primitive {@code boolean} value
* @return a hash code for the value
*/
public static int hashCode(boolean value) {
return value ? 1231 : 1237;
}
/**
* Compares the two specified {@code boolean} values in the standard way
* ({@code false} is considered less than {@code true}). The sign of the
* value returned is the same as that of {@code ((Boolean) a).compareTo(b)}.
*
* @param a the first {@code boolean} to compare
* @param b the second {@code boolean} to compare
* @return a positive number if only {@code a} is {@code true}, a negative
* number if only {@code b} is true, or zero if {@code a == b}
*/
public static int compare(boolean a, boolean b) {
return (a == b) ? 0 : (a ? 1 : -1);
}
/**
* Returns {@code true} if {@code target} is present as an element anywhere in
* {@code array}.
*
* <p><b>Note:</b> consider representing the array as a {@link
* BitSet} instead, replacing {@code Booleans.contains(array, true)}
* with {@code !bitSet.isEmpty()} and {@code Booleans.contains(array, false)}
* with {@code bitSet.nextClearBit(0) == sizeOfBitSet}.
*
* @param array an array of {@code boolean} values, possibly empty
* @param target a primitive {@code boolean} value
* @return {@code true} if {@code array[i] == target} for some value of {@code
* i}
*/
public static boolean contains(boolean[] array, boolean target) {
for (boolean value : array) {
if (value == target) {
return true;
}
}
return false;
}
/**
* Returns the index of the first appearance of the value {@code target} in
* {@code array}.
*
* <p><b>Note:</b> consider representing the array as a {@link BitSet}
* instead, and using {@link BitSet#nextSetBit(int)} or {@link
* BitSet#nextClearBit(int)}.
*
* @param array an array of {@code boolean} values, possibly empty
* @param target a primitive {@code boolean} 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(boolean[] array, boolean target) {
return indexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int indexOf(
boolean[] array, boolean 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.
*
* <p>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(boolean[] array, boolean[] 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 boolean} values, possibly empty
* @param target a primitive {@code boolean} 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(boolean[] array, boolean target) {
return lastIndexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int lastIndexOf(
boolean[] array, boolean target, int start, int end) {
for (int i = end - 1; i >= start; i--) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the values from each provided array combined into a single array.
* For example, {@code concat(new boolean[] {a, b}, new boolean[] {}, new
* boolean[] {c}} returns the array {@code {a, b, c}}.
*
* @param arrays zero or more {@code boolean} arrays
* @return a single array containing all the values from the source arrays, in
* order
*/
public static boolean[] concat(boolean[]... arrays) {
int length = 0;
for (boolean[] array : arrays) {
length += array.length;
}
boolean[] result = new boolean[length];
int pos = 0;
for (boolean[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
/**
* Returns an array containing the same values as {@code array}, but
* guaranteed to be of a specified minimum length. If {@code array} already
* has a length of at least {@code minLength}, it is returned directly.
* Otherwise, a new array of size {@code minLength + padding} is returned,
* containing the values of {@code array}, and zeroes in the remaining places.
*
* @param array the source array
* @param minLength the minimum length the returned array must guarantee
* @param padding an extra amount to "grow" the array by if growth is
* necessary
* @throws IllegalArgumentException if {@code minLength} or {@code padding} is
* negative
* @return an array containing the values of {@code array}, with guaranteed
* minimum length {@code minLength}
*/
public static boolean[] ensureCapacity(
boolean[] array, int minLength, int padding) {
checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
checkArgument(padding >= 0, "Invalid padding: %s", padding);
return (array.length < minLength)
? copyOf(array, minLength + padding)
: array;
}
// Arrays.copyOf() requires Java 6
private static boolean[] copyOf(boolean[] original, int length) {
boolean[] copy = new boolean[length];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
return copy;
}
/**
* Returns a string containing the supplied {@code boolean} values separated
* by {@code separator}. For example, {@code join("-", false, true, false)}
* returns the string {@code "false-true-false"}.
*
* @param separator the text that should appear between consecutive values in
* the resulting string (but not at the start or end)
* @param array an array of {@code boolean} values, possibly empty
*/
public static String join(String separator, boolean... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 7);
builder.append(array[0]);
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
/**
* Returns a comparator that compares two {@code boolean} arrays
* lexicographically. That is, it compares, using {@link
* #compare(boolean, boolean)}), the first pair of values that follow any
* common prefix, or when one array is a prefix of the other, treats the
* shorter array as the lesser. For example,
* {@code [] < [false] < [false, true] < [true]}.
*
* <p>The returned comparator is inconsistent with {@link
* Object#equals(Object)} (since arrays support only identity equality), but
* it is consistent with {@link Arrays#equals(boolean[], boolean[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
* Lexicographical order article at Wikipedia</a>
* @since 2.0
*/
public static Comparator<boolean[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
private enum LexicographicalComparator implements Comparator<boolean[]> {
INSTANCE;
@Override
public int compare(boolean[] left, boolean[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = Booleans.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
}
/**
* Copies a collection of {@code Boolean} instances into a new array of
* primitive {@code boolean} values.
*
* <p>Elements are copied from the argument collection as if by {@code
* collection.toArray()}. Calling this method is as thread-safe as calling
* that method.
*
* <p><b>Note:</b> consider representing the collection as a {@link
* BitSet} instead.
*
* @param collection a collection of {@code Boolean} objects
* @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
*/
public static boolean[] toArray(Collection<Boolean> collection) {
if (collection instanceof BooleanArrayAsList) {
return ((BooleanArrayAsList) collection).toBooleanArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
boolean[] array = new boolean[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = (Boolean) checkNotNull(boxedArray[i]);
}
return array;
}
/**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
* but any attempt to set a value to {@code null} will result in a {@link
* NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of
* {@code Boolean} 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<Boolean> asList(boolean... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new BooleanArrayAsList(backingArray);
}
@GwtCompatible
private static class BooleanArrayAsList extends AbstractList<Boolean>
implements RandomAccess, Serializable {
final boolean[] array;
final int start;
final int end;
BooleanArrayAsList(boolean[] array) {
this(array, 0, array.length);
}
BooleanArrayAsList(boolean[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override public int size() {
return end - start;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Boolean get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override public boolean contains(Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Boolean)
&& Booleans.indexOf(array, (Boolean) target, start, end) != -1;
}
@Override public int indexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Boolean) {
int i = Booleans.indexOf(array, (Boolean) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public int lastIndexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Boolean) {
int i = Booleans.lastIndexOf(array, (Boolean) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public Boolean set(int index, Boolean element) {
checkElementIndex(index, size());
boolean oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override public List<Boolean> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new BooleanArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof BooleanArrayAsList) {
BooleanArrayAsList that = (BooleanArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Booleans.hashCode(array[i]);
}
return result;
}
@Override public String toString() {
StringBuilder builder = new StringBuilder(size() * 7);
builder.append(array[start] ? "[true" : "[false");
for (int i = start + 1; i < end; i++) {
builder.append(array[i] ? ", true" : ", false");
}
return builder.append(']').toString();
}
boolean[] toBooleanArray() {
// Arrays.copyOfRange() is not available under GWT
int size = size();
boolean[] result = new boolean[size];
System.arraycopy(array, start, result, 0, size);
return result;
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* Copyright (C) 2011 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.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.math.BigInteger;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
/**
* A wrapper class for unsigned {@code long} values, supporting arithmetic operations.
*
* <p>In some cases, when speed is more important than code readability, it may be faster simply to
* treat primitive {@code long} values as unsigned, using the methods from {@link UnsignedLongs}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained#Unsigned_support">
* unsigned primitive utilities</a>.
*
* @author Louis Wasserman
* @author Colin Evans
* @since 11.0
*/
@GwtCompatible(serializable = true)
public final class UnsignedLong extends Number implements Comparable<UnsignedLong>, Serializable {
private static final long UNSIGNED_MASK = 0x7fffffffffffffffL;
public static final UnsignedLong ZERO = new UnsignedLong(0);
public static final UnsignedLong ONE = new UnsignedLong(1);
public static final UnsignedLong MAX_VALUE = new UnsignedLong(-1L);
private final long value;
private UnsignedLong(long value) {
this.value = value;
}
/**
* Returns an {@code UnsignedLong} corresponding to a given bit representation.
* The argument is interpreted as an unsigned 64-bit value. Specifically, the sign bit
* of {@code bits} is interpreted as a normal bit, and all other bits are treated as usual.
*
* <p>If the argument is nonnegative, the returned result will be equal to {@code bits},
* otherwise, the result will be equal to {@code 2^64 + bits}.
*
* <p>To represent decimal constants less than {@code 2^63}, consider {@link #valueOf(long)}
* instead.
*
* @since 14.0
*/
public static UnsignedLong fromLongBits(long bits) {
// TODO(user): consider caching small values, like Long.valueOf
return new UnsignedLong(bits);
}
/**
* Returns an {@code UnsignedLong} representing the same value as the specified {@code long}.
*
* @throws IllegalArgumentException if {@code value} is negative
* @since 14.0
*/
public static UnsignedLong valueOf(long value) {
checkArgument(value >= 0,
"value (%s) is outside the range for an unsigned long value", value);
return fromLongBits(value);
}
/**
* Returns a {@code UnsignedLong} representing the same value as the specified
* {@code BigInteger}. This is the inverse operation of {@link #bigIntegerValue()}.
*
* @throws IllegalArgumentException if {@code value} is negative or {@code value >= 2^64}
*/
public static UnsignedLong valueOf(BigInteger value) {
checkNotNull(value);
checkArgument(value.signum() >= 0 && value.bitLength() <= Long.SIZE,
"value (%s) is outside the range for an unsigned long value", value);
return fromLongBits(value.longValue());
}
/**
* Returns an {@code UnsignedLong} holding the value of the specified {@code String}, parsed as
* an unsigned {@code long} value.
*
* @throws NumberFormatException if the string does not contain a parsable unsigned {@code long}
* value
*/
public static UnsignedLong valueOf(String string) {
return valueOf(string, 10);
}
/**
* Returns an {@code UnsignedLong} holding the value of the specified {@code String}, parsed as
* an unsigned {@code long} value in the specified radix.
*
* @throws NumberFormatException if the string does not contain a parsable unsigned {@code long}
* value, or {@code radix} is not between {@link Character#MIN_RADIX} and
* {@link Character#MAX_RADIX}
*/
public static UnsignedLong valueOf(String string, int radix) {
return fromLongBits(UnsignedLongs.parseUnsignedLong(string, radix));
}
/**
* Returns the result of adding this and {@code val}. If the result would have more than 64 bits,
* returns the low 64 bits of the result.
*
* @since 14.0
*/
public UnsignedLong plus(UnsignedLong val) {
return fromLongBits(this.value + checkNotNull(val).value);
}
/**
* Returns the result of subtracting this and {@code val}. If the result would have more than 64
* bits, returns the low 64 bits of the result.
*
* @since 14.0
*/
public UnsignedLong minus(UnsignedLong val) {
return fromLongBits(this.value - checkNotNull(val).value);
}
/**
* Returns the result of multiplying this and {@code val}. If the result would have more than 64
* bits, returns the low 64 bits of the result.
*
* @since 14.0
*/
@CheckReturnValue
public UnsignedLong times(UnsignedLong val) {
return fromLongBits(value * checkNotNull(val).value);
}
/**
* Returns the result of dividing this by {@code val}.
*
* @since 14.0
*/
@CheckReturnValue
public UnsignedLong dividedBy(UnsignedLong val) {
return fromLongBits(UnsignedLongs.divide(value, checkNotNull(val).value));
}
/**
* Returns this modulo {@code val}.
*
* @since 14.0
*/
@CheckReturnValue
public UnsignedLong mod(UnsignedLong val) {
return fromLongBits(UnsignedLongs.remainder(value, checkNotNull(val).value));
}
/**
* Returns the value of this {@code UnsignedLong} as an {@code int}.
*/
@Override
public int intValue() {
return (int) value;
}
/**
* Returns the value of this {@code UnsignedLong} as a {@code long}. This is an inverse operation
* to {@link #fromLongBits}.
*
* <p>Note that if this {@code UnsignedLong} holds a value {@code >= 2^63}, the returned value
* will be equal to {@code this - 2^64}.
*/
@Override
public long longValue() {
return value;
}
/**
* Returns the value of this {@code UnsignedLong} as a {@code float}, analogous to a widening
* primitive conversion from {@code long} to {@code float}, and correctly rounded.
*/
@Override
public float floatValue() {
@SuppressWarnings("cast")
float fValue = (float) (value & UNSIGNED_MASK);
if (value < 0) {
fValue += 0x1.0p63f;
}
return fValue;
}
/**
* Returns the value of this {@code UnsignedLong} as a {@code double}, analogous to a widening
* primitive conversion from {@code long} to {@code double}, and correctly rounded.
*/
@Override
public double doubleValue() {
@SuppressWarnings("cast")
double dValue = (double) (value & UNSIGNED_MASK);
if (value < 0) {
dValue += 0x1.0p63;
}
return dValue;
}
/**
* Returns the value of this {@code UnsignedLong} as a {@link BigInteger}.
*/
public BigInteger bigIntegerValue() {
BigInteger bigInt = BigInteger.valueOf(value & UNSIGNED_MASK);
if (value < 0) {
bigInt = bigInt.setBit(Long.SIZE - 1);
}
return bigInt;
}
@Override
public int compareTo(UnsignedLong o) {
checkNotNull(o);
return UnsignedLongs.compare(value, o.value);
}
@Override
public int hashCode() {
return Longs.hashCode(value);
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof UnsignedLong) {
UnsignedLong other = (UnsignedLong) obj;
return value == other.value;
}
return false;
}
/**
* Returns a string representation of the {@code UnsignedLong} value, in base 10.
*/
@Override
public String toString() {
return UnsignedLongs.toString(value);
}
/**
* Returns a string representation of the {@code UnsignedLong} value, in base {@code radix}. If
* {@code radix < Character.MIN_RADIX} or {@code radix > Character.MAX_RADIX}, the radix
* {@code 10} is used.
*/
public String toString(int radix) {
return UnsignedLongs.toString(value, radix);
}
}
| Java |
/*
* Copyright (C) 2012 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.
*/
/**
* Escapers
* for
* HTML.
*
* <p>This package is a part of the open-source
* <a href="http://guava-libraries.googlecode.com">Guava libraries</a>.
*/
@ParametersAreNonnullByDefault
package com.google.common.html;
import javax.annotation.ParametersAreNonnullByDefault;
| Java |
/*
* Copyright (C) 2009 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.html;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.escape.Escaper;
import com.google.common.escape.Escapers;
/**
* {@code Escaper} instances suitable for strings to be included in HTML
* attribute values and <em>most</em> elements' text contents. When possible,
* avoid manual escaping by using templating systems and high-level APIs that
* provide autoescaping.
*
* <p>HTML escaping is particularly tricky: For example, <a
* href="http://goo.gl/5TgZb">some elements' text contents must not be HTML
* escaped</a>. As a result, it is impossible to escape an HTML document
* correctly without domain-specific knowledge beyond what {@code HtmlEscapers}
* provides. We strongly encourage the use of HTML templating systems.
*
* @author Sven Mawson
* @author David Beaumont
* @since 15.0
*/
@Beta
@GwtCompatible
public final class HtmlEscapers {
private HtmlEscapers() {}
// For each xxxEscaper() method, please add links to external reference pages
// that are considered authoritative for the behavior of that escaper.
/**
* Returns an {@link Escaper} instance that escapes HTML metacharacters as
* specified by <a href="http://www.w3.org/TR/html4/">HTML 4.01</a>. The
* resulting strings can be used both in attribute values and in <em>most</em>
* elements' text contents, provided that the HTML document's character
* encoding can encode any non-ASCII code points in the input (as UTF-8 and
* other Unicode encodings can).
*
*
* <p><b>Note</b>: This escaper only performs minimal escaping to make content
* structurally compatible with HTML. Specifically, it does not perform entity
* replacement (symbolic or numeric), so it does not replace non-ASCII code
* points with character references. This escaper escapes only the following
* five ASCII characters: {@code '"&<>}.
*/
public static Escaper htmlEscaper() {
return HTML_ESCAPER;
}
private static final Escaper HTML_ESCAPER =
Escapers.builder()
.addEscape('"', """)
// Note: "'" is not defined in HTML 4.01.
.addEscape('\'', "'")
.addEscape('&', "&")
.addEscape('<', "<")
.addEscape('>', ">")
.build();
}
| Java |
/*
* Copyright (C) 2011 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.math;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.math.MathPreconditions.checkNonNegative;
import static com.google.common.math.MathPreconditions.checkPositive;
import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
import static java.math.RoundingMode.CEILING;
import static java.math.RoundingMode.FLOOR;
import static java.math.RoundingMode.HALF_EVEN;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
/**
* A class for arithmetic on values of type {@code BigInteger}.
*
* <p>The implementations of many methods in this class are based on material from Henry S. Warren,
* Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002).
*
* <p>Similar functionality for {@code int} and for {@code long} can be found in
* {@link IntMath} and {@link LongMath} respectively.
*
* @author Louis Wasserman
* @since 11.0
*/
@GwtCompatible(emulated = true)
public final class BigIntegerMath {
/**
* Returns {@code true} if {@code x} represents a power of two.
*/
public static boolean isPowerOfTwo(BigInteger x) {
checkNotNull(x);
return x.signum() > 0 && x.getLowestSetBit() == x.bitLength() - 1;
}
/**
* Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of two
*/
@SuppressWarnings("fallthrough")
// TODO(kevinb): remove after this warning is disabled globally
public static int log2(BigInteger x, RoundingMode mode) {
checkPositive("x", checkNotNull(x));
int logFloor = x.bitLength() - 1;
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(isPowerOfTwo(x)); // fall through
case DOWN:
case FLOOR:
return logFloor;
case UP:
case CEILING:
return isPowerOfTwo(x) ? logFloor : logFloor + 1;
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
if (logFloor < SQRT2_PRECOMPUTE_THRESHOLD) {
BigInteger halfPower = SQRT2_PRECOMPUTED_BITS.shiftRight(
SQRT2_PRECOMPUTE_THRESHOLD - logFloor);
if (x.compareTo(halfPower) <= 0) {
return logFloor;
} else {
return logFloor + 1;
}
}
/*
* Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
*
* To determine which side of logFloor.5 the logarithm is, we compare x^2 to 2^(2 *
* logFloor + 1).
*/
BigInteger x2 = x.pow(2);
int logX2Floor = x2.bitLength() - 1;
return (logX2Floor < 2 * logFloor + 1) ? logFloor : logFloor + 1;
default:
throw new AssertionError();
}
}
/*
* The maximum number of bits in a square root for which we'll precompute an explicit half power
* of two. This can be any value, but higher values incur more class load time and linearly
* increasing memory consumption.
*/
@VisibleForTesting static final int SQRT2_PRECOMPUTE_THRESHOLD = 256;
@VisibleForTesting static final BigInteger SQRT2_PRECOMPUTED_BITS =
new BigInteger("16a09e667f3bcc908b2fb1366ea957d3e3adec17512775099da2f590b0667322a", 16);
/**
* Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of ten
*/
@GwtIncompatible("TODO")
@SuppressWarnings("fallthrough")
public static int log10(BigInteger x, RoundingMode mode) {
checkPositive("x", x);
if (fitsInLong(x)) {
return LongMath.log10(x.longValue(), mode);
}
int approxLog10 = (int) (log2(x, FLOOR) * LN_2 / LN_10);
BigInteger approxPow = BigInteger.TEN.pow(approxLog10);
int approxCmp = approxPow.compareTo(x);
/*
* We adjust approxLog10 and approxPow until they're equal to floor(log10(x)) and
* 10^floor(log10(x)).
*/
if (approxCmp > 0) {
/*
* The code is written so that even completely incorrect approximations will still yield the
* correct answer eventually, but in practice this branch should almost never be entered,
* and even then the loop should not run more than once.
*/
do {
approxLog10--;
approxPow = approxPow.divide(BigInteger.TEN);
approxCmp = approxPow.compareTo(x);
} while (approxCmp > 0);
} else {
BigInteger nextPow = BigInteger.TEN.multiply(approxPow);
int nextCmp = nextPow.compareTo(x);
while (nextCmp <= 0) {
approxLog10++;
approxPow = nextPow;
approxCmp = nextCmp;
nextPow = BigInteger.TEN.multiply(approxPow);
nextCmp = nextPow.compareTo(x);
}
}
int floorLog = approxLog10;
BigInteger floorPow = approxPow;
int floorCmp = approxCmp;
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(floorCmp == 0);
// fall through
case FLOOR:
case DOWN:
return floorLog;
case CEILING:
case UP:
return floorPow.equals(x) ? floorLog : floorLog + 1;
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
// Since sqrt(10) is irrational, log10(x) - floorLog can never be exactly 0.5
BigInteger x2 = x.pow(2);
BigInteger halfPowerSquared = floorPow.pow(2).multiply(BigInteger.TEN);
return (x2.compareTo(halfPowerSquared) <= 0) ? floorLog : floorLog + 1;
default:
throw new AssertionError();
}
}
private static final double LN_10 = Math.log(10);
private static final double LN_2 = Math.log(2);
/**
* Returns the square root of {@code x}, rounded with the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x < 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and
* {@code sqrt(x)} is not an integer
*/
@GwtIncompatible("TODO")
@SuppressWarnings("fallthrough")
public static BigInteger sqrt(BigInteger x, RoundingMode mode) {
checkNonNegative("x", x);
if (fitsInLong(x)) {
return BigInteger.valueOf(LongMath.sqrt(x.longValue(), mode));
}
BigInteger sqrtFloor = sqrtFloor(x);
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(sqrtFloor.pow(2).equals(x)); // fall through
case FLOOR:
case DOWN:
return sqrtFloor;
case CEILING:
case UP:
return sqrtFloor.pow(2).equals(x) ? sqrtFloor : sqrtFloor.add(BigInteger.ONE);
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
BigInteger halfSquare = sqrtFloor.pow(2).add(sqrtFloor);
/*
* We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both
* x and halfSquare are integers, this is equivalent to testing whether or not x <=
* halfSquare.
*/
return (halfSquare.compareTo(x) >= 0) ? sqrtFloor : sqrtFloor.add(BigInteger.ONE);
default:
throw new AssertionError();
}
}
@GwtIncompatible("TODO")
private static BigInteger sqrtFloor(BigInteger x) {
/*
* Adapted from Hacker's Delight, Figure 11-1.
*
* Using DoubleUtils.bigToDouble, getting a double approximation of x is extremely fast, and
* then we can get a double approximation of the square root. Then, we iteratively improve this
* guess with an application of Newton's method, which sets guess := (guess + (x / guess)) / 2.
* This iteration has the following two properties:
*
* a) every iteration (except potentially the first) has guess >= floor(sqrt(x)). This is
* because guess' is the arithmetic mean of guess and x / guess, sqrt(x) is the geometric mean,
* and the arithmetic mean is always higher than the geometric mean.
*
* b) this iteration converges to floor(sqrt(x)). In fact, the number of correct digits doubles
* with each iteration, so this algorithm takes O(log(digits)) iterations.
*
* We start out with a double-precision approximation, which may be higher or lower than the
* true value. Therefore, we perform at least one Newton iteration to get a guess that's
* definitely >= floor(sqrt(x)), and then continue the iteration until we reach a fixed point.
*/
BigInteger sqrt0;
int log2 = log2(x, FLOOR);
if(log2 < Double.MAX_EXPONENT) {
sqrt0 = sqrtApproxWithDoubles(x);
} else {
int shift = (log2 - DoubleUtils.SIGNIFICAND_BITS) & ~1; // even!
/*
* We have that x / 2^shift < 2^54. Our initial approximation to sqrtFloor(x) will be
* 2^(shift/2) * sqrtApproxWithDoubles(x / 2^shift).
*/
sqrt0 = sqrtApproxWithDoubles(x.shiftRight(shift)).shiftLeft(shift >> 1);
}
BigInteger sqrt1 = sqrt0.add(x.divide(sqrt0)).shiftRight(1);
if (sqrt0.equals(sqrt1)) {
return sqrt0;
}
do {
sqrt0 = sqrt1;
sqrt1 = sqrt0.add(x.divide(sqrt0)).shiftRight(1);
} while (sqrt1.compareTo(sqrt0) < 0);
return sqrt0;
}
@GwtIncompatible("TODO")
private static BigInteger sqrtApproxWithDoubles(BigInteger x) {
return DoubleMath.roundToBigInteger(Math.sqrt(DoubleUtils.bigToDouble(x)), HALF_EVEN);
}
/**
* Returns the result of dividing {@code p} by {@code q}, rounding using the specified
* {@code RoundingMode}.
*
* @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
* is not an integer multiple of {@code b}
*/
@GwtIncompatible("TODO")
public static BigInteger divide(BigInteger p, BigInteger q, RoundingMode mode) {
BigDecimal pDec = new BigDecimal(p);
BigDecimal qDec = new BigDecimal(q);
return pDec.divide(qDec, 0, mode).toBigIntegerExact();
}
/**
* Returns {@code n!}, that is, the product of the first {@code n} positive
* integers, or {@code 1} if {@code n == 0}.
*
* <p><b>Warning</b>: the result takes <i>O(n log n)</i> space, so use cautiously.
*
* <p>This uses an efficient binary recursive algorithm to compute the factorial
* with balanced multiplies. It also removes all the 2s from the intermediate
* products (shifting them back in at the end).
*
* @throws IllegalArgumentException if {@code n < 0}
*/
public static BigInteger factorial(int n) {
checkNonNegative("n", n);
// If the factorial is small enough, just use LongMath to do it.
if (n < LongMath.factorials.length) {
return BigInteger.valueOf(LongMath.factorials[n]);
}
// Pre-allocate space for our list of intermediate BigIntegers.
int approxSize = IntMath.divide(n * IntMath.log2(n, CEILING), Long.SIZE, CEILING);
ArrayList<BigInteger> bignums = new ArrayList<BigInteger>(approxSize);
// Start from the pre-computed maximum long factorial.
int startingNumber = LongMath.factorials.length;
long product = LongMath.factorials[startingNumber - 1];
// Strip off 2s from this value.
int shift = Long.numberOfTrailingZeros(product);
product >>= shift;
// Use floor(log2(num)) + 1 to prevent overflow of multiplication.
int productBits = LongMath.log2(product, FLOOR) + 1;
int bits = LongMath.log2(startingNumber, FLOOR) + 1;
// Check for the next power of two boundary, to save us a CLZ operation.
int nextPowerOfTwo = 1 << (bits - 1);
// Iteratively multiply the longs as big as they can go.
for (long num = startingNumber; num <= n; num++) {
// Check to see if the floor(log2(num)) + 1 has changed.
if ((num & nextPowerOfTwo) != 0) {
nextPowerOfTwo <<= 1;
bits++;
}
// Get rid of the 2s in num.
int tz = Long.numberOfTrailingZeros(num);
long normalizedNum = num >> tz;
shift += tz;
// Adjust floor(log2(num)) + 1.
int normalizedBits = bits - tz;
// If it won't fit in a long, then we store off the intermediate product.
if (normalizedBits + productBits >= Long.SIZE) {
bignums.add(BigInteger.valueOf(product));
product = 1;
productBits = 0;
}
product *= normalizedNum;
productBits = LongMath.log2(product, FLOOR) + 1;
}
// Check for leftovers.
if (product > 1) {
bignums.add(BigInteger.valueOf(product));
}
// Efficiently multiply all the intermediate products together.
return listProduct(bignums).shiftLeft(shift);
}
static BigInteger listProduct(List<BigInteger> nums) {
return listProduct(nums, 0, nums.size());
}
static BigInteger listProduct(List<BigInteger> nums, int start, int end) {
switch (end - start) {
case 0:
return BigInteger.ONE;
case 1:
return nums.get(start);
case 2:
return nums.get(start).multiply(nums.get(start + 1));
case 3:
return nums.get(start).multiply(nums.get(start + 1)).multiply(nums.get(start + 2));
default:
// Otherwise, split the list in half and recursively do this.
int m = (end + start) >>> 1;
return listProduct(nums, start, m).multiply(listProduct(nums, m, end));
}
}
/**
* Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and
* {@code k}, that is, {@code n! / (k! (n - k)!)}.
*
* <p><b>Warning</b>: the result can take as much as <i>O(k log n)</i> space.
*
* @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n}
*/
public static BigInteger binomial(int n, int k) {
checkNonNegative("n", n);
checkNonNegative("k", k);
checkArgument(k <= n, "k (%s) > n (%s)", k, n);
if (k > (n >> 1)) {
k = n - k;
}
if (k < LongMath.biggestBinomials.length && n <= LongMath.biggestBinomials[k]) {
return BigInteger.valueOf(LongMath.binomial(n, k));
}
BigInteger accum = BigInteger.ONE;
long numeratorAccum = n;
long denominatorAccum = 1;
int bits = LongMath.log2(n, RoundingMode.CEILING);
int numeratorBits = bits;
for (int i = 1; i < k; i++) {
int p = n - i;
int q = i + 1;
// log2(p) >= bits - 1, because p >= n/2
if (numeratorBits + bits >= Long.SIZE - 1) {
// The numerator is as big as it can get without risking overflow.
// Multiply numeratorAccum / denominatorAccum into accum.
accum = accum
.multiply(BigInteger.valueOf(numeratorAccum))
.divide(BigInteger.valueOf(denominatorAccum));
numeratorAccum = p;
denominatorAccum = q;
numeratorBits = bits;
} else {
// We can definitely multiply into the long accumulators without overflowing them.
numeratorAccum *= p;
denominatorAccum *= q;
numeratorBits += bits;
}
}
return accum
.multiply(BigInteger.valueOf(numeratorAccum))
.divide(BigInteger.valueOf(denominatorAccum));
}
// Returns true if BigInteger.valueOf(x.longValue()).equals(x).
@GwtIncompatible("TODO")
static boolean fitsInLong(BigInteger x) {
return x.bitLength() <= Long.SIZE - 1;
}
private BigIntegerMath() {}
}
| Java |
/*
* Copyright (C) 2011 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.math;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.math.DoubleUtils.IMPLICIT_BIT;
import static com.google.common.math.DoubleUtils.SIGNIFICAND_BITS;
import static com.google.common.math.DoubleUtils.getSignificand;
import static com.google.common.math.DoubleUtils.isFinite;
import static com.google.common.math.DoubleUtils.isNormal;
import static com.google.common.math.DoubleUtils.scaleNormalize;
import static com.google.common.math.MathPreconditions.checkInRange;
import static com.google.common.math.MathPreconditions.checkNonNegative;
import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
import static java.lang.Math.abs;
import static java.lang.Math.copySign;
import static java.lang.Math.getExponent;
import static java.lang.Math.log;
import static java.lang.Math.rint;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Booleans;
import java.math.BigInteger;
import java.math.RoundingMode;
/**
* A class for arithmetic on doubles that is not covered by {@link java.lang.Math}.
*
* @author Louis Wasserman
* @since 11.0
*/
public final class DoubleMath {
/*
* This method returns a value y such that rounding y DOWN (towards zero) gives the same result
* as rounding x according to the specified mode.
*/
static double roundIntermediate(double x, RoundingMode mode) {
if (!isFinite(x)) {
throw new ArithmeticException("input is infinite or NaN");
}
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(isMathematicalInteger(x));
return x;
case FLOOR:
if (x >= 0.0 || isMathematicalInteger(x)) {
return x;
} else {
return x - 1.0;
}
case CEILING:
if (x <= 0.0 || isMathematicalInteger(x)) {
return x;
} else {
return x + 1.0;
}
case DOWN:
return x;
case UP:
if (isMathematicalInteger(x)) {
return x;
} else {
return x + Math.copySign(1.0, x);
}
case HALF_EVEN:
return rint(x);
case HALF_UP: {
double z = rint(x);
if (abs(x - z) == 0.5) {
return x + copySign(0.5, x);
} else {
return z;
}
}
case HALF_DOWN: {
double z = rint(x);
if (abs(x - z) == 0.5) {
return x;
} else {
return z;
}
}
default:
throw new AssertionError();
}
}
/**
* Returns the {@code int} value that is equal to {@code x} rounded with the specified rounding
* mode, if possible.
*
* @throws ArithmeticException if
* <ul>
* <li>{@code x} is infinite or NaN
* <li>{@code x}, after being rounded to a mathematical integer using the specified
* rounding mode, is either less than {@code Integer.MIN_VALUE} or greater than {@code
* Integer.MAX_VALUE}
* <li>{@code x} is not a mathematical integer and {@code mode} is
* {@link RoundingMode#UNNECESSARY}
* </ul>
*/
public static int roundToInt(double x, RoundingMode mode) {
double z = roundIntermediate(x, mode);
checkInRange(z > MIN_INT_AS_DOUBLE - 1.0 & z < MAX_INT_AS_DOUBLE + 1.0);
return (int) z;
}
private static final double MIN_INT_AS_DOUBLE = -0x1p31;
private static final double MAX_INT_AS_DOUBLE = 0x1p31 - 1.0;
/**
* Returns the {@code long} value that is equal to {@code x} rounded with the specified rounding
* mode, if possible.
*
* @throws ArithmeticException if
* <ul>
* <li>{@code x} is infinite or NaN
* <li>{@code x}, after being rounded to a mathematical integer using the specified
* rounding mode, is either less than {@code Long.MIN_VALUE} or greater than {@code
* Long.MAX_VALUE}
* <li>{@code x} is not a mathematical integer and {@code mode} is
* {@link RoundingMode#UNNECESSARY}
* </ul>
*/
public static long roundToLong(double x, RoundingMode mode) {
double z = roundIntermediate(x, mode);
checkInRange(MIN_LONG_AS_DOUBLE - z < 1.0 & z < MAX_LONG_AS_DOUBLE_PLUS_ONE);
return (long) z;
}
private static final double MIN_LONG_AS_DOUBLE = -0x1p63;
/*
* We cannot store Long.MAX_VALUE as a double without losing precision. Instead, we store
* Long.MAX_VALUE + 1 == -Long.MIN_VALUE, and then offset all comparisons by 1.
*/
private static final double MAX_LONG_AS_DOUBLE_PLUS_ONE = 0x1p63;
/**
* Returns the {@code BigInteger} value that is equal to {@code x} rounded with the specified
* rounding mode, if possible.
*
* @throws ArithmeticException if
* <ul>
* <li>{@code x} is infinite or NaN
* <li>{@code x} is not a mathematical integer and {@code mode} is
* {@link RoundingMode#UNNECESSARY}
* </ul>
*/
public static BigInteger roundToBigInteger(double x, RoundingMode mode) {
x = roundIntermediate(x, mode);
if (MIN_LONG_AS_DOUBLE - x < 1.0 & x < MAX_LONG_AS_DOUBLE_PLUS_ONE) {
return BigInteger.valueOf((long) x);
}
int exponent = getExponent(x);
long significand = getSignificand(x);
BigInteger result = BigInteger.valueOf(significand).shiftLeft(exponent - SIGNIFICAND_BITS);
return (x < 0) ? result.negate() : result;
}
/**
* Returns {@code true} if {@code x} is exactly equal to {@code 2^k} for some finite integer
* {@code k}.
*/
public static boolean isPowerOfTwo(double x) {
return x > 0.0 && isFinite(x) && LongMath.isPowerOfTwo(getSignificand(x));
}
/**
* Returns the base 2 logarithm of a double value.
*
* <p>Special cases:
* <ul>
* <li>If {@code x} is NaN or less than zero, the result is NaN.
* <li>If {@code x} is positive infinity, the result is positive infinity.
* <li>If {@code x} is positive or negative zero, the result is negative infinity.
* </ul>
*
* <p>The computed result is within 1 ulp of the exact result.
*
* <p>If the result of this method will be immediately rounded to an {@code int},
* {@link #log2(double, RoundingMode)} is faster.
*/
public static double log2(double x) {
return log(x) / LN_2; // surprisingly within 1 ulp according to tests
}
private static final double LN_2 = log(2);
/**
* Returns the base 2 logarithm of a double value, rounded with the specified rounding mode to an
* {@code int}.
*
* <p>Regardless of the rounding mode, this is faster than {@code (int) log2(x)}.
*
* @throws IllegalArgumentException if {@code x <= 0.0}, {@code x} is NaN, or {@code x} is
* infinite
*/
@SuppressWarnings("fallthrough")
public static int log2(double x, RoundingMode mode) {
checkArgument(x > 0.0 && isFinite(x), "x must be positive and finite");
int exponent = getExponent(x);
if (!isNormal(x)) {
return log2(x * IMPLICIT_BIT, mode) - SIGNIFICAND_BITS;
// Do the calculation on a normal value.
}
// x is positive, finite, and normal
boolean increment;
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(isPowerOfTwo(x));
// fall through
case FLOOR:
increment = false;
break;
case CEILING:
increment = !isPowerOfTwo(x);
break;
case DOWN:
increment = exponent < 0 & !isPowerOfTwo(x);
break;
case UP:
increment = exponent >= 0 & !isPowerOfTwo(x);
break;
case HALF_DOWN:
case HALF_EVEN:
case HALF_UP:
double xScaled = scaleNormalize(x);
// sqrt(2) is irrational, and the spec is relative to the "exact numerical result,"
// so log2(x) is never exactly exponent + 0.5.
increment = (xScaled * xScaled) > 2.0;
break;
default:
throw new AssertionError();
}
return increment ? exponent + 1 : exponent;
}
/**
* Returns {@code true} if {@code x} represents a mathematical integer.
*
* <p>This is equivalent to, but not necessarily implemented as, the expression {@code
* !Double.isNaN(x) && !Double.isInfinite(x) && x == Math.rint(x)}.
*/
public static boolean isMathematicalInteger(double x) {
return isFinite(x)
&& (x == 0.0 ||
SIGNIFICAND_BITS - Long.numberOfTrailingZeros(getSignificand(x)) <= getExponent(x));
}
/**
* Returns {@code n!}, that is, the product of the first {@code n} positive
* integers, {@code 1} if {@code n == 0}, or e n!}, or
* {@link Double#POSITIVE_INFINITY} if {@code n! > Double.MAX_VALUE}.
*
* <p>The result is within 1 ulp of the true value.
*
* @throws IllegalArgumentException if {@code n < 0}
*/
public static double factorial(int n) {
checkNonNegative("n", n);
if (n > MAX_FACTORIAL) {
return Double.POSITIVE_INFINITY;
} else {
// Multiplying the last (n & 0xf) values into their own accumulator gives a more accurate
// result than multiplying by everySixteenthFactorial[n >> 4] directly.
double accum = 1.0;
for (int i = 1 + (n & ~0xf); i <= n; i++) {
accum *= i;
}
return accum * everySixteenthFactorial[n >> 4];
}
}
@VisibleForTesting
static final int MAX_FACTORIAL = 170;
@VisibleForTesting
static final double[] everySixteenthFactorial = {
0x1.0p0,
0x1.30777758p44,
0x1.956ad0aae33a4p117,
0x1.ee69a78d72cb6p202,
0x1.fe478ee34844ap295,
0x1.c619094edabffp394,
0x1.3638dd7bd6347p498,
0x1.7cac197cfe503p605,
0x1.1e5dfc140e1e5p716,
0x1.8ce85fadb707ep829,
0x1.95d5f3d928edep945};
/**
* Returns {@code true} if {@code a} and {@code b} are within {@code tolerance} of each other.
*
* <p>Technically speaking, this is equivalent to
* {@code Math.abs(a - b) <= tolerance || Double.valueOf(a).equals(Double.valueOf(b))}.
*
* <p>Notable special cases include:
* <ul>
* <li>All NaNs are fuzzily equal.
* <li>If {@code a == b}, then {@code a} and {@code b} are always fuzzily equal.
* <li>Positive and negative zero are always fuzzily equal.
* <li>If {@code tolerance} is zero, and neither {@code a} nor {@code b} is NaN, then
* {@code a} and {@code b} are fuzzily equal if and only if {@code a == b}.
* <li>With {@link Double#POSITIVE_INFINITY} tolerance, all non-NaN values are fuzzily equal.
* <li>With finite tolerance, {@code Double.POSITIVE_INFINITY} and {@code
* Double.NEGATIVE_INFINITY} are fuzzily equal only to themselves.
* </li>
*
* <p>This is reflexive and symmetric, but <em>not</em> transitive, so it is <em>not</em> an
* equivalence relation and <em>not</em> suitable for use in {@link Object#equals}
* implementations.
*
* @throws IllegalArgumentException if {@code tolerance} is {@code < 0} or NaN
* @since 13.0
*/
public static boolean fuzzyEquals(double a, double b, double tolerance) {
MathPreconditions.checkNonNegative("tolerance", tolerance);
return
Math.copySign(a - b, 1.0) <= tolerance
// copySign(x, 1.0) is a branch-free version of abs(x), but with different NaN semantics
|| (a == b) // needed to ensure that infinities equal themselves
|| (Double.isNaN(a) && Double.isNaN(b));
}
/**
* Compares {@code a} and {@code b} "fuzzily," with a tolerance for nearly-equal values.
*
* <p>This method is equivalent to
* {@code fuzzyEquals(a, b, tolerance) ? 0 : Double.compare(a, b)}. In particular, like
* {@link Double#compare(double, double)}, it treats all NaN values as equal and greater than all
* other values (including {@link Double#POSITIVE_INFINITY}).
*
* <p>This is <em>not</em> a total ordering and is <em>not</em> suitable for use in
* {@link Comparable#compareTo} implementations. In particular, it is not transitive.
*
* @throws IllegalArgumentException if {@code tolerance} is {@code < 0} or NaN
* @since 13.0
*/
public static int fuzzyCompare(double a, double b, double tolerance) {
if (fuzzyEquals(a, b, tolerance)) {
return 0;
} else if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return Booleans.compare(Double.isNaN(a), Double.isNaN(b));
}
}
private DoubleMath() {}
}
| Java |
/*
* Copyright (C) 2011 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.
*/
/**
* Arithmetic functions operating on primitive values and {@link java.math.BigInteger} instances.
*
* <p>This package is a part of the open-source
* <a href="http://guava-libraries.googlecode.com">Guava libraries</a>.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/MathExplained">
* math utilities</a>.
*/
@ParametersAreNonnullByDefault
package com.google.common.math;
import javax.annotation.ParametersAreNonnullByDefault;
| Java |
/*
* Copyright (C) 2011 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.math;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.math.MathPreconditions.checkNoOverflow;
import static com.google.common.math.MathPreconditions.checkNonNegative;
import static com.google.common.math.MathPreconditions.checkPositive;
import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
import static java.lang.Math.abs;
import static java.lang.Math.min;
import static java.math.RoundingMode.HALF_EVEN;
import static java.math.RoundingMode.HALF_UP;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.math.BigInteger;
import java.math.RoundingMode;
/**
* A class for arithmetic on values of type {@code long}. Where possible, methods are defined and
* named analogously to their {@code BigInteger} counterparts.
*
* <p>The implementations of many methods in this class are based on material from Henry S. Warren,
* Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002).
*
* <p>Similar functionality for {@code int} and for {@link BigInteger} can be found in
* {@link IntMath} and {@link BigIntegerMath} respectively. For other common operations on
* {@code long} values, see {@link com.google.common.primitives.Longs}.
*
* @author Louis Wasserman
* @since 11.0
*/
@GwtCompatible(emulated = true)
public final class LongMath {
// NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
/**
* Returns {@code true} if {@code x} represents a power of two.
*
* <p>This differs from {@code Long.bitCount(x) == 1}, because
* {@code Long.bitCount(Long.MIN_VALUE) == 1}, but {@link Long#MIN_VALUE} is not a power of two.
*/
public static boolean isPowerOfTwo(long x) {
return x > 0 & (x & (x - 1)) == 0;
}
/**
* Returns 1 if {@code x < y} as unsigned longs, and 0 otherwise. Assumes that x - y fits into a
* signed long. The implementation is branch-free, and benchmarks suggest it is measurably
* faster than the straightforward ternary expression.
*/
@VisibleForTesting
static int lessThanBranchFree(long x, long y) {
// Returns the sign bit of x - y.
return (int) (~~(x - y) >>> (Long.SIZE - 1));
}
/**
* Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of two
*/
@SuppressWarnings("fallthrough")
// TODO(kevinb): remove after this warning is disabled globally
public static int log2(long x, RoundingMode mode) {
checkPositive("x", x);
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(isPowerOfTwo(x));
// fall through
case DOWN:
case FLOOR:
return (Long.SIZE - 1) - Long.numberOfLeadingZeros(x);
case UP:
case CEILING:
return Long.SIZE - Long.numberOfLeadingZeros(x - 1);
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
// Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
int leadingZeros = Long.numberOfLeadingZeros(x);
long cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros;
// floor(2^(logFloor + 0.5))
int logFloor = (Long.SIZE - 1) - leadingZeros;
return logFloor + lessThanBranchFree(cmp, x);
default:
throw new AssertionError("impossible");
}
}
/** The biggest half power of two that fits into an unsigned long */
@VisibleForTesting static final long MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333F9DE6484L;
/**
* Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of ten
*/
@GwtIncompatible("TODO")
@SuppressWarnings("fallthrough")
// TODO(kevinb): remove after this warning is disabled globally
public static int log10(long x, RoundingMode mode) {
checkPositive("x", x);
int logFloor = log10Floor(x);
long floorPow = powersOf10[logFloor];
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(x == floorPow);
// fall through
case FLOOR:
case DOWN:
return logFloor;
case CEILING:
case UP:
return logFloor + lessThanBranchFree(floorPow, x);
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
// sqrt(10) is irrational, so log10(x)-logFloor is never exactly 0.5
return logFloor + lessThanBranchFree(halfPowersOf10[logFloor], x);
default:
throw new AssertionError();
}
}
@GwtIncompatible("TODO")
static int log10Floor(long x) {
/*
* Based on Hacker's Delight Fig. 11-5, the two-table-lookup, branch-free implementation.
*
* The key idea is that based on the number of leading zeros (equivalently, floor(log2(x))),
* we can narrow the possible floor(log10(x)) values to two. For example, if floor(log2(x))
* is 6, then 64 <= x < 128, so floor(log10(x)) is either 1 or 2.
*/
int y = maxLog10ForLeadingZeros[Long.numberOfLeadingZeros(x)];
/*
* y is the higher of the two possible values of floor(log10(x)). If x < 10^y, then we want the
* lower of the two possible values, or y - 1, otherwise, we want y.
*/
return y - lessThanBranchFree(x, powersOf10[y]);
}
// maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i)))
@VisibleForTesting static final byte[] maxLog10ForLeadingZeros = {
19, 18, 18, 18, 18, 17, 17, 17, 16, 16, 16, 15, 15, 15, 15, 14, 14, 14, 13, 13, 13, 12, 12,
12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4,
3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0 };
@GwtIncompatible("TODO")
@VisibleForTesting
static final long[] powersOf10 = {
1L,
10L,
100L,
1000L,
10000L,
100000L,
1000000L,
10000000L,
100000000L,
1000000000L,
10000000000L,
100000000000L,
1000000000000L,
10000000000000L,
100000000000000L,
1000000000000000L,
10000000000000000L,
100000000000000000L,
1000000000000000000L
};
// halfPowersOf10[i] = largest long less than 10^(i + 0.5)
@GwtIncompatible("TODO")
@VisibleForTesting
static final long[] halfPowersOf10 = {
3L,
31L,
316L,
3162L,
31622L,
316227L,
3162277L,
31622776L,
316227766L,
3162277660L,
31622776601L,
316227766016L,
3162277660168L,
31622776601683L,
316227766016837L,
3162277660168379L,
31622776601683793L,
316227766016837933L,
3162277660168379331L
};
/**
* Returns {@code b} to the {@code k}th power. Even if the result overflows, it will be equal to
* {@code BigInteger.valueOf(b).pow(k).longValue()}. This implementation runs in {@code O(log k)}
* time.
*
* @throws IllegalArgumentException if {@code k < 0}
*/
@GwtIncompatible("TODO")
public static long pow(long b, int k) {
checkNonNegative("exponent", k);
if (-2 <= b && b <= 2) {
switch ((int) b) {
case 0:
return (k == 0) ? 1 : 0;
case 1:
return 1;
case (-1):
return ((k & 1) == 0) ? 1 : -1;
case 2:
return (k < Long.SIZE) ? 1L << k : 0;
case (-2):
if (k < Long.SIZE) {
return ((k & 1) == 0) ? 1L << k : -(1L << k);
} else {
return 0;
}
default:
throw new AssertionError();
}
}
for (long accum = 1;; k >>= 1) {
switch (k) {
case 0:
return accum;
case 1:
return accum * b;
default:
accum *= ((k & 1) == 0) ? 1 : b;
b *= b;
}
}
}
/**
* Returns the square root of {@code x}, rounded with the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x < 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and
* {@code sqrt(x)} is not an integer
*/
@GwtIncompatible("TODO")
@SuppressWarnings("fallthrough")
public static long sqrt(long x, RoundingMode mode) {
checkNonNegative("x", x);
if (fitsInInt(x)) {
return IntMath.sqrt((int) x, mode);
}
/*
* Let k be the true value of floor(sqrt(x)), so that
*
* k * k <= x < (k + 1) * (k + 1)
* (double) (k * k) <= (double) x <= (double) ((k + 1) * (k + 1))
* since casting to double is nondecreasing.
* Note that the right-hand inequality is no longer strict.
* Math.sqrt(k * k) <= Math.sqrt(x) <= Math.sqrt((k + 1) * (k + 1))
* since Math.sqrt is monotonic.
* (long) Math.sqrt(k * k) <= (long) Math.sqrt(x) <= (long) Math.sqrt((k + 1) * (k + 1))
* since casting to long is monotonic
* k <= (long) Math.sqrt(x) <= k + 1
* since (long) Math.sqrt(k * k) == k, as checked exhaustively in
* {@link LongMathTest#testSqrtOfPerfectSquareAsDoubleIsPerfect}
*/
long guess = (long) Math.sqrt(x);
// Note: guess is always <= FLOOR_SQRT_MAX_LONG.
long guessSquared = guess * guess;
// Note (2013-2-26): benchmarks indicate that, inscrutably enough, using if statements is
// faster here than using lessThanBranchFree.
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(guessSquared == x);
return guess;
case FLOOR:
case DOWN:
if (x < guessSquared) {
return guess - 1;
}
return guess;
case CEILING:
case UP:
if (x > guessSquared) {
return guess + 1;
}
return guess;
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
long sqrtFloor = guess - ((x < guessSquared) ? 1 : 0);
long halfSquare = sqrtFloor * sqrtFloor + sqrtFloor;
/*
* We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both
* x and halfSquare are integers, this is equivalent to testing whether or not x <=
* halfSquare. (We have to deal with overflow, though.)
*
* If we treat halfSquare as an unsigned long, we know that
* sqrtFloor^2 <= x < (sqrtFloor + 1)^2
* halfSquare - sqrtFloor <= x < halfSquare + sqrtFloor + 1
* so |x - halfSquare| <= sqrtFloor. Therefore, it's safe to treat x - halfSquare as a
* signed long, so lessThanBranchFree is safe for use.
*/
return sqrtFloor + lessThanBranchFree(halfSquare, x);
default:
throw new AssertionError();
}
}
/**
* Returns the result of dividing {@code p} by {@code q}, rounding using the specified
* {@code RoundingMode}.
*
* @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
* is not an integer multiple of {@code b}
*/
@GwtIncompatible("TODO")
@SuppressWarnings("fallthrough")
public static long divide(long p, long q, RoundingMode mode) {
checkNotNull(mode);
long div = p / q; // throws if q == 0
long rem = p - q * div; // equals p % q
if (rem == 0) {
return div;
}
/*
* Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. We just have to
* deal with the cases where rounding towards 0 is wrong, which typically depends on the sign of
* p / q.
*
* signum is 1 if p and q are both nonnegative or both negative, and -1 otherwise.
*/
int signum = 1 | (int) ((p ^ q) >> (Long.SIZE - 1));
boolean increment;
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(rem == 0);
// fall through
case DOWN:
increment = false;
break;
case UP:
increment = true;
break;
case CEILING:
increment = signum > 0;
break;
case FLOOR:
increment = signum < 0;
break;
case HALF_EVEN:
case HALF_DOWN:
case HALF_UP:
long absRem = abs(rem);
long cmpRemToHalfDivisor = absRem - (abs(q) - absRem);
// subtracting two nonnegative longs can't overflow
// cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2).
if (cmpRemToHalfDivisor == 0) { // exactly on the half mark
increment = (mode == HALF_UP | (mode == HALF_EVEN & (div & 1) != 0));
} else {
increment = cmpRemToHalfDivisor > 0; // closer to the UP value
}
break;
default:
throw new AssertionError();
}
return increment ? div + signum : div;
}
/**
* Returns {@code x mod m}. This differs from {@code x % m} in that it always returns a
* non-negative result.
*
* <p>For example:
*
* <pre> {@code
*
* mod(7, 4) == 3
* mod(-7, 4) == 1
* mod(-1, 4) == 3
* mod(-8, 4) == 0
* mod(8, 4) == 0}</pre>
*
* @throws ArithmeticException if {@code m <= 0}
*/
@GwtIncompatible("TODO")
public static int mod(long x, int m) {
// Cast is safe because the result is guaranteed in the range [0, m)
return (int) mod(x, (long) m);
}
/**
* Returns {@code x mod m}. This differs from {@code x % m} in that it always returns a
* non-negative result.
*
* <p>For example:
*
* <pre> {@code
*
* mod(7, 4) == 3
* mod(-7, 4) == 1
* mod(-1, 4) == 3
* mod(-8, 4) == 0
* mod(8, 4) == 0}</pre>
*
* @throws ArithmeticException if {@code m <= 0}
*/
@GwtIncompatible("TODO")
public static long mod(long x, long m) {
if (m <= 0) {
throw new ArithmeticException("Modulus must be positive");
}
long result = x % m;
return (result >= 0) ? result : result + m;
}
/**
* Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if
* {@code a == 0 && b == 0}.
*
* @throws IllegalArgumentException if {@code a < 0} or {@code b < 0}
*/
public static long gcd(long a, long b) {
/*
* The reason we require both arguments to be >= 0 is because otherwise, what do you return on
* gcd(0, Long.MIN_VALUE)? BigInteger.gcd would return positive 2^63, but positive 2^63 isn't
* an int.
*/
checkNonNegative("a", a);
checkNonNegative("b", b);
if (a == 0) {
// 0 % b == 0, so b divides a, but the converse doesn't hold.
// BigInteger.gcd is consistent with this decision.
return b;
} else if (b == 0) {
return a; // similar logic
}
/*
* Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm.
* This is >60% faster than the Euclidean algorithm in benchmarks.
*/
int aTwos = Long.numberOfTrailingZeros(a);
a >>= aTwos; // divide out all 2s
int bTwos = Long.numberOfTrailingZeros(b);
b >>= bTwos; // divide out all 2s
while (a != b) { // both a, b are odd
// The key to the binary GCD algorithm is as follows:
// Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b).
// But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two.
// We bend over backwards to avoid branching, adapting a technique from
// http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
long delta = a - b; // can't overflow, since a and b are nonnegative
long minDeltaOrZero = delta & (delta >> (Long.SIZE - 1));
// equivalent to Math.min(delta, 0)
a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b)
// a is now nonnegative and even
b += minDeltaOrZero; // sets b to min(old a, b)
a >>= Long.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b
}
return a << min(aTwos, bTwos);
}
/**
* Returns the sum of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a + b} overflows in signed {@code long} arithmetic
*/
@GwtIncompatible("TODO")
public static long checkedAdd(long a, long b) {
long result = a + b;
checkNoOverflow((a ^ b) < 0 | (a ^ result) >= 0);
return result;
}
/**
* Returns the difference of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a - b} overflows in signed {@code long} arithmetic
*/
@GwtIncompatible("TODO")
public static long checkedSubtract(long a, long b) {
long result = a - b;
checkNoOverflow((a ^ b) >= 0 | (a ^ result) >= 0);
return result;
}
/**
* Returns the product of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a * b} overflows in signed {@code long} arithmetic
*/
@GwtIncompatible("TODO")
public static long checkedMultiply(long a, long b) {
// Hacker's Delight, Section 2-12
int leadingZeros = Long.numberOfLeadingZeros(a) + Long.numberOfLeadingZeros(~a)
+ Long.numberOfLeadingZeros(b) + Long.numberOfLeadingZeros(~b);
/*
* If leadingZeros > Long.SIZE + 1 it's definitely fine, if it's < Long.SIZE it's definitely
* bad. We do the leadingZeros check to avoid the division below if at all possible.
*
* Otherwise, if b == Long.MIN_VALUE, then the only allowed values of a are 0 and 1. We take
* care of all a < 0 with their own check, because in particular, the case a == -1 will
* incorrectly pass the division check below.
*
* In all other cases, we check that either a is 0 or the result is consistent with division.
*/
if (leadingZeros > Long.SIZE + 1) {
return a * b;
}
checkNoOverflow(leadingZeros >= Long.SIZE);
checkNoOverflow(a >= 0 | b != Long.MIN_VALUE);
long result = a * b;
checkNoOverflow(a == 0 || result / a == b);
return result;
}
/**
* Returns the {@code b} to the {@code k}th power, provided it does not overflow.
*
* @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed
* {@code long} arithmetic
*/
@GwtIncompatible("TODO")
public static long checkedPow(long b, int k) {
checkNonNegative("exponent", k);
if (b >= -2 & b <= 2) {
switch ((int) b) {
case 0:
return (k == 0) ? 1 : 0;
case 1:
return 1;
case (-1):
return ((k & 1) == 0) ? 1 : -1;
case 2:
checkNoOverflow(k < Long.SIZE - 1);
return 1L << k;
case (-2):
checkNoOverflow(k < Long.SIZE);
return ((k & 1) == 0) ? (1L << k) : (-1L << k);
default:
throw new AssertionError();
}
}
long accum = 1;
while (true) {
switch (k) {
case 0:
return accum;
case 1:
return checkedMultiply(accum, b);
default:
if ((k & 1) != 0) {
accum = checkedMultiply(accum, b);
}
k >>= 1;
if (k > 0) {
checkNoOverflow(b <= FLOOR_SQRT_MAX_LONG);
b *= b;
}
}
}
}
@VisibleForTesting static final long FLOOR_SQRT_MAX_LONG = 3037000499L;
/**
* Returns {@code n!}, that is, the product of the first {@code n} positive
* integers, {@code 1} if {@code n == 0}, or {@link Long#MAX_VALUE} if the
* result does not fit in a {@code long}.
*
* @throws IllegalArgumentException if {@code n < 0}
*/
@GwtIncompatible("TODO")
public static long factorial(int n) {
checkNonNegative("n", n);
return (n < factorials.length) ? factorials[n] : Long.MAX_VALUE;
}
static final long[] factorials = {
1L,
1L,
1L * 2,
1L * 2 * 3,
1L * 2 * 3 * 4,
1L * 2 * 3 * 4 * 5,
1L * 2 * 3 * 4 * 5 * 6,
1L * 2 * 3 * 4 * 5 * 6 * 7,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20
};
/**
* Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and
* {@code k}, or {@link Long#MAX_VALUE} if the result does not fit in a {@code long}.
*
* @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n}
*/
public static long binomial(int n, int k) {
checkNonNegative("n", n);
checkNonNegative("k", k);
checkArgument(k <= n, "k (%s) > n (%s)", k, n);
if (k > (n >> 1)) {
k = n - k;
}
switch (k) {
case 0:
return 1;
case 1:
return n;
default:
if (n < factorials.length) {
return factorials[n] / (factorials[k] * factorials[n - k]);
} else if (k >= biggestBinomials.length || n > biggestBinomials[k]) {
return Long.MAX_VALUE;
} else if (k < biggestSimpleBinomials.length && n <= biggestSimpleBinomials[k]) {
// guaranteed not to overflow
long result = n--;
for (int i = 2; i <= k; n--, i++) {
result *= n;
result /= i;
}
return result;
} else {
int nBits = LongMath.log2(n, RoundingMode.CEILING);
long result = 1;
long numerator = n--;
long denominator = 1;
int numeratorBits = nBits;
// This is an upper bound on log2(numerator, ceiling).
/*
* We want to do this in long math for speed, but want to avoid overflow. We adapt the
* technique previously used by BigIntegerMath: maintain separate numerator and
* denominator accumulators, multiplying the fraction into result when near overflow.
*/
for (int i = 2; i <= k; i++, n--) {
if (numeratorBits + nBits < Long.SIZE - 1) {
// It's definitely safe to multiply into numerator and denominator.
numerator *= n;
denominator *= i;
numeratorBits += nBits;
} else {
// It might not be safe to multiply into numerator and denominator,
// so multiply (numerator / denominator) into result.
result = multiplyFraction(result, numerator, denominator);
numerator = n;
denominator = i;
numeratorBits = nBits;
}
}
return multiplyFraction(result, numerator, denominator);
}
}
}
/**
* Returns (x * numerator / denominator), which is assumed to come out to an integral value.
*/
static long multiplyFraction(long x, long numerator, long denominator) {
if (x == 1) {
return numerator / denominator;
}
long commonDivisor = gcd(x, denominator);
x /= commonDivisor;
denominator /= commonDivisor;
// We know gcd(x, denominator) = 1, and x * numerator / denominator is exact,
// so denominator must be a divisor of numerator.
return x * (numerator / denominator);
}
/*
* binomial(biggestBinomials[k], k) fits in a long, but not
* binomial(biggestBinomials[k] + 1, k).
*/
static final int[] biggestBinomials =
{Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 3810779, 121977, 16175, 4337, 1733,
887, 534, 361, 265, 206, 169, 143, 125, 111, 101, 94, 88, 83, 79, 76, 74, 72, 70, 69, 68,
67, 67, 66, 66, 66, 66};
/*
* binomial(biggestSimpleBinomials[k], k) doesn't need to use the slower GCD-based impl,
* but binomial(biggestSimpleBinomials[k] + 1, k) does.
*/
@VisibleForTesting static final int[] biggestSimpleBinomials =
{Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 2642246, 86251, 11724, 3218, 1313,
684, 419, 287, 214, 169, 139, 119, 105, 95, 87, 81, 76, 73, 70, 68, 66, 64, 63, 62, 62,
61, 61, 61};
// These values were generated by using checkedMultiply to see when the simple multiply/divide
// algorithm would lead to an overflow.
static boolean fitsInInt(long x) {
return (int) x == x;
}
/**
* Returns the arithmetic mean of {@code x} and {@code y}, rounded toward
* negative infinity. This method is resilient to overflow.
*
* @since 14.0
*/
public static long mean(long x, long y) {
// Efficient method for computing the arithmetic mean.
// The alternative (x + y) / 2 fails for large values.
// The alternative (x + y) >>> 1 fails for negative values.
return (x & y) + ((x ^ y) >> 1);
}
private LongMath() {}
}
| Java |
/*
* Copyright (C) 2011 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.math;
import com.google.common.annotations.GwtCompatible;
import java.math.BigInteger;
import javax.annotation.Nullable;
/**
* A collection of preconditions for math functions.
*
* @author Louis Wasserman
*/
@GwtCompatible
final class MathPreconditions {
static int checkPositive(@Nullable String role, int x) {
if (x <= 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be > 0");
}
return x;
}
static long checkPositive(@Nullable String role, long x) {
if (x <= 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be > 0");
}
return x;
}
static BigInteger checkPositive(@Nullable String role, BigInteger x) {
if (x.signum() <= 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be > 0");
}
return x;
}
static int checkNonNegative(@Nullable String role, int x) {
if (x < 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be >= 0");
}
return x;
}
static long checkNonNegative(@Nullable String role, long x) {
if (x < 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be >= 0");
}
return x;
}
static BigInteger checkNonNegative(@Nullable String role, BigInteger x) {
if (x.signum() < 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be >= 0");
}
return x;
}
static double checkNonNegative(@Nullable String role, double x) {
if (!(x >= 0)) { // not x < 0, to work with NaN.
throw new IllegalArgumentException(role + " (" + x + ") must be >= 0");
}
return x;
}
static void checkRoundingUnnecessary(boolean condition) {
if (!condition) {
throw new ArithmeticException("mode was UNNECESSARY, but rounding was necessary");
}
}
static void checkInRange(boolean condition) {
if (!condition) {
throw new ArithmeticException("not in range");
}
}
static void checkNoOverflow(boolean condition) {
if (!condition) {
throw new ArithmeticException("overflow");
}
}
private MathPreconditions() {}
}
| Java |
/*
* Copyright (C) 2011 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.math;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.Double.MAX_EXPONENT;
import static java.lang.Double.MIN_EXPONENT;
import static java.lang.Double.POSITIVE_INFINITY;
import static java.lang.Double.doubleToRawLongBits;
import static java.lang.Double.isNaN;
import static java.lang.Double.longBitsToDouble;
import static java.lang.Math.getExponent;
import java.math.BigInteger;
/**
* Utilities for {@code double} primitives.
*
* @author Louis Wasserman
*/
final class DoubleUtils {
private DoubleUtils() {
}
static double nextDown(double d) {
return -Math.nextUp(-d);
}
// The mask for the significand, according to the {@link
// Double#doubleToRawLongBits(double)} spec.
static final long SIGNIFICAND_MASK = 0x000fffffffffffffL;
// The mask for the exponent, according to the {@link
// Double#doubleToRawLongBits(double)} spec.
static final long EXPONENT_MASK = 0x7ff0000000000000L;
// The mask for the sign, according to the {@link
// Double#doubleToRawLongBits(double)} spec.
static final long SIGN_MASK = 0x8000000000000000L;
static final int SIGNIFICAND_BITS = 52;
static final int EXPONENT_BIAS = 1023;
/**
* The implicit 1 bit that is omitted in significands of normal doubles.
*/
static final long IMPLICIT_BIT = SIGNIFICAND_MASK + 1;
static long getSignificand(double d) {
checkArgument(isFinite(d), "not a normal value");
int exponent = getExponent(d);
long bits = doubleToRawLongBits(d);
bits &= SIGNIFICAND_MASK;
return (exponent == MIN_EXPONENT - 1)
? bits << 1
: bits | IMPLICIT_BIT;
}
static boolean isFinite(double d) {
return getExponent(d) <= MAX_EXPONENT;
}
static boolean isNormal(double d) {
return getExponent(d) >= MIN_EXPONENT;
}
/*
* Returns x scaled by a power of 2 such that it is in the range [1, 2). Assumes x is positive,
* normal, and finite.
*/
static double scaleNormalize(double x) {
long significand = doubleToRawLongBits(x) & SIGNIFICAND_MASK;
return longBitsToDouble(significand | ONE_BITS);
}
static double bigToDouble(BigInteger x) {
// This is an extremely fast implementation of BigInteger.doubleValue(). JDK patch pending.
BigInteger absX = x.abs();
int exponent = absX.bitLength() - 1;
// exponent == floor(log2(abs(x)))
if (exponent < Long.SIZE - 1) {
return x.longValue();
} else if (exponent > MAX_EXPONENT) {
return x.signum() * POSITIVE_INFINITY;
}
/*
* We need the top SIGNIFICAND_BITS + 1 bits, including the "implicit" one bit. To make
* rounding easier, we pick out the top SIGNIFICAND_BITS + 2 bits, so we have one to help us
* round up or down. twiceSignifFloor will contain the top SIGNIFICAND_BITS + 2 bits, and
* signifFloor the top SIGNIFICAND_BITS + 1.
*
* It helps to consider the real number signif = absX * 2^(SIGNIFICAND_BITS - exponent).
*/
int shift = exponent - SIGNIFICAND_BITS - 1;
long twiceSignifFloor = absX.shiftRight(shift).longValue();
long signifFloor = twiceSignifFloor >> 1;
signifFloor &= SIGNIFICAND_MASK; // remove the implied bit
/*
* We round up if either the fractional part of signif is strictly greater than 0.5 (which is
* true if the 0.5 bit is set and any lower bit is set), or if the fractional part of signif is
* >= 0.5 and signifFloor is odd (which is true if both the 0.5 bit and the 1 bit are set).
*/
boolean increment = (twiceSignifFloor & 1) != 0
&& ((signifFloor & 1) != 0 || absX.getLowestSetBit() < shift);
long signifRounded = increment ? signifFloor + 1 : signifFloor;
long bits = (long) ((exponent + EXPONENT_BIAS)) << SIGNIFICAND_BITS;
bits += signifRounded;
/*
* If signifRounded == 2^53, we'd need to set all of the significand bits to zero and add 1 to
* the exponent. This is exactly the behavior we get from just adding signifRounded to bits
* directly. If the exponent is MAX_DOUBLE_EXPONENT, we round up (correctly) to
* Double.POSITIVE_INFINITY.
*/
bits |= x.signum() & SIGN_MASK;
return longBitsToDouble(bits);
}
/**
* Returns its argument if it is non-negative, zero if it is negative.
*/
static double ensureNonNegative(double value) {
checkArgument(!isNaN(value));
if (value > 0.0) {
return value;
} else {
return 0.0;
}
}
private static final long ONE_BITS = doubleToRawLongBits(1.0);
}
| Java |
/*
* Copyright (C) 2011 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.math;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.math.MathPreconditions.checkNoOverflow;
import static com.google.common.math.MathPreconditions.checkNonNegative;
import static com.google.common.math.MathPreconditions.checkPositive;
import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
import static java.lang.Math.abs;
import static java.lang.Math.min;
import static java.math.RoundingMode.HALF_EVEN;
import static java.math.RoundingMode.HALF_UP;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.math.BigInteger;
import java.math.RoundingMode;
/**
* A class for arithmetic on values of type {@code int}. Where possible, methods are defined and
* named analogously to their {@code BigInteger} counterparts.
*
* <p>The implementations of many methods in this class are based on material from Henry S. Warren,
* Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002).
*
* <p>Similar functionality for {@code long} and for {@link BigInteger} can be found in
* {@link LongMath} and {@link BigIntegerMath} respectively. For other common operations on
* {@code int} values, see {@link com.google.common.primitives.Ints}.
*
* @author Louis Wasserman
* @since 11.0
*/
@GwtCompatible(emulated = true)
public final class IntMath {
// NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
/**
* Returns {@code true} if {@code x} represents a power of two.
*
* <p>This differs from {@code Integer.bitCount(x) == 1}, because
* {@code Integer.bitCount(Integer.MIN_VALUE) == 1}, but {@link Integer#MIN_VALUE} is not a power
* of two.
*/
public static boolean isPowerOfTwo(int x) {
return x > 0 & (x & (x - 1)) == 0;
}
/**
* Returns 1 if {@code x < y} as unsigned integers, and 0 otherwise. Assumes that x - y fits into
* a signed int. The implementation is branch-free, and benchmarks suggest it is measurably (if
* narrowly) faster than the straightforward ternary expression.
*/
@VisibleForTesting
static int lessThanBranchFree(int x, int y) {
// The double negation is optimized away by normal Java, but is necessary for GWT
// to make sure bit twiddling works as expected.
return ~~(x - y) >>> (Integer.SIZE - 1);
}
/**
* Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of two
*/
@SuppressWarnings("fallthrough")
// TODO(kevinb): remove after this warning is disabled globally
public static int log2(int x, RoundingMode mode) {
checkPositive("x", x);
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(isPowerOfTwo(x));
// fall through
case DOWN:
case FLOOR:
return (Integer.SIZE - 1) - Integer.numberOfLeadingZeros(x);
case UP:
case CEILING:
return Integer.SIZE - Integer.numberOfLeadingZeros(x - 1);
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
// Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
int leadingZeros = Integer.numberOfLeadingZeros(x);
int cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros;
// floor(2^(logFloor + 0.5))
int logFloor = (Integer.SIZE - 1) - leadingZeros;
return logFloor + lessThanBranchFree(cmp, x);
default:
throw new AssertionError();
}
}
/** The biggest half power of two that can fit in an unsigned int. */
@VisibleForTesting static final int MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333;
/**
* Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of ten
*/
@GwtIncompatible("need BigIntegerMath to adequately test")
@SuppressWarnings("fallthrough")
public static int log10(int x, RoundingMode mode) {
checkPositive("x", x);
int logFloor = log10Floor(x);
int floorPow = powersOf10[logFloor];
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(x == floorPow);
// fall through
case FLOOR:
case DOWN:
return logFloor;
case CEILING:
case UP:
return logFloor + lessThanBranchFree(floorPow, x);
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
// sqrt(10) is irrational, so log10(x) - logFloor is never exactly 0.5
return logFloor + lessThanBranchFree(halfPowersOf10[logFloor], x);
default:
throw new AssertionError();
}
}
private static int log10Floor(int x) {
/*
* Based on Hacker's Delight Fig. 11-5, the two-table-lookup, branch-free implementation.
*
* The key idea is that based on the number of leading zeros (equivalently, floor(log2(x))),
* we can narrow the possible floor(log10(x)) values to two. For example, if floor(log2(x))
* is 6, then 64 <= x < 128, so floor(log10(x)) is either 1 or 2.
*/
int y = maxLog10ForLeadingZeros[Integer.numberOfLeadingZeros(x)];
/*
* y is the higher of the two possible values of floor(log10(x)). If x < 10^y, then we want the
* lower of the two possible values, or y - 1, otherwise, we want y.
*/
return y - lessThanBranchFree(x, powersOf10[y]);
}
// maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i)))
@VisibleForTesting static final byte[] maxLog10ForLeadingZeros = {9, 9, 9, 8, 8, 8,
7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0};
@VisibleForTesting static final int[] powersOf10 = {1, 10, 100, 1000, 10000,
100000, 1000000, 10000000, 100000000, 1000000000};
// halfPowersOf10[i] = largest int less than 10^(i + 0.5)
@VisibleForTesting static final int[] halfPowersOf10 =
{3, 31, 316, 3162, 31622, 316227, 3162277, 31622776, 316227766, Integer.MAX_VALUE};
/**
* Returns {@code b} to the {@code k}th power. Even if the result overflows, it will be equal to
* {@code BigInteger.valueOf(b).pow(k).intValue()}. This implementation runs in {@code O(log k)}
* time.
*
* <p>Compare {@link #checkedPow}, which throws an {@link ArithmeticException} upon overflow.
*
* @throws IllegalArgumentException if {@code k < 0}
*/
@GwtIncompatible("failing tests")
public static int pow(int b, int k) {
checkNonNegative("exponent", k);
switch (b) {
case 0:
return (k == 0) ? 1 : 0;
case 1:
return 1;
case (-1):
return ((k & 1) == 0) ? 1 : -1;
case 2:
return (k < Integer.SIZE) ? (1 << k) : 0;
case (-2):
if (k < Integer.SIZE) {
return ((k & 1) == 0) ? (1 << k) : -(1 << k);
} else {
return 0;
}
default:
// continue below to handle the general case
}
for (int accum = 1;; k >>= 1) {
switch (k) {
case 0:
return accum;
case 1:
return b * accum;
default:
accum *= ((k & 1) == 0) ? 1 : b;
b *= b;
}
}
}
/**
* Returns the square root of {@code x}, rounded with the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x < 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and
* {@code sqrt(x)} is not an integer
*/
@GwtIncompatible("need BigIntegerMath to adequately test")
@SuppressWarnings("fallthrough")
public static int sqrt(int x, RoundingMode mode) {
checkNonNegative("x", x);
int sqrtFloor = sqrtFloor(x);
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(sqrtFloor * sqrtFloor == x); // fall through
case FLOOR:
case DOWN:
return sqrtFloor;
case CEILING:
case UP:
return sqrtFloor + lessThanBranchFree(sqrtFloor * sqrtFloor, x);
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
int halfSquare = sqrtFloor * sqrtFloor + sqrtFloor;
/*
* We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both
* x and halfSquare are integers, this is equivalent to testing whether or not x <=
* halfSquare. (We have to deal with overflow, though.)
*
* If we treat halfSquare as an unsigned int, we know that
* sqrtFloor^2 <= x < (sqrtFloor + 1)^2
* halfSquare - sqrtFloor <= x < halfSquare + sqrtFloor + 1
* so |x - halfSquare| <= sqrtFloor. Therefore, it's safe to treat x - halfSquare as a
* signed int, so lessThanBranchFree is safe for use.
*/
return sqrtFloor + lessThanBranchFree(halfSquare, x);
default:
throw new AssertionError();
}
}
private static int sqrtFloor(int x) {
// There is no loss of precision in converting an int to a double, according to
// http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2
return (int) Math.sqrt(x);
}
/**
* Returns the result of dividing {@code p} by {@code q}, rounding using the specified
* {@code RoundingMode}.
*
* @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
* is not an integer multiple of {@code b}
*/
@SuppressWarnings("fallthrough")
public static int divide(int p, int q, RoundingMode mode) {
checkNotNull(mode);
if (q == 0) {
throw new ArithmeticException("/ by zero"); // for GWT
}
int div = p / q;
int rem = p - q * div; // equal to p % q
if (rem == 0) {
return div;
}
/*
* Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. We just have to
* deal with the cases where rounding towards 0 is wrong, which typically depends on the sign of
* p / q.
*
* signum is 1 if p and q are both nonnegative or both negative, and -1 otherwise.
*/
int signum = 1 | ((p ^ q) >> (Integer.SIZE - 1));
boolean increment;
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(rem == 0);
// fall through
case DOWN:
increment = false;
break;
case UP:
increment = true;
break;
case CEILING:
increment = signum > 0;
break;
case FLOOR:
increment = signum < 0;
break;
case HALF_EVEN:
case HALF_DOWN:
case HALF_UP:
int absRem = abs(rem);
int cmpRemToHalfDivisor = absRem - (abs(q) - absRem);
// subtracting two nonnegative ints can't overflow
// cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2).
if (cmpRemToHalfDivisor == 0) { // exactly on the half mark
increment = (mode == HALF_UP || (mode == HALF_EVEN & (div & 1) != 0));
} else {
increment = cmpRemToHalfDivisor > 0; // closer to the UP value
}
break;
default:
throw new AssertionError();
}
return increment ? div + signum : div;
}
/**
* Returns {@code x mod m}. This differs from {@code x % m} in that it always returns a
* non-negative result.
*
* <p>For example:<pre> {@code
*
* mod(7, 4) == 3
* mod(-7, 4) == 1
* mod(-1, 4) == 3
* mod(-8, 4) == 0
* mod(8, 4) == 0}</pre>
*
* @throws ArithmeticException if {@code m <= 0}
*/
public static int mod(int x, int m) {
if (m <= 0) {
throw new ArithmeticException("Modulus " + m + " must be > 0");
}
int result = x % m;
return (result >= 0) ? result : result + m;
}
/**
* Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if
* {@code a == 0 && b == 0}.
*
* @throws IllegalArgumentException if {@code a < 0} or {@code b < 0}
*/
public static int gcd(int a, int b) {
/*
* The reason we require both arguments to be >= 0 is because otherwise, what do you return on
* gcd(0, Integer.MIN_VALUE)? BigInteger.gcd would return positive 2^31, but positive 2^31
* isn't an int.
*/
checkNonNegative("a", a);
checkNonNegative("b", b);
if (a == 0) {
// 0 % b == 0, so b divides a, but the converse doesn't hold.
// BigInteger.gcd is consistent with this decision.
return b;
} else if (b == 0) {
return a; // similar logic
}
/*
* Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm.
* This is >40% faster than the Euclidean algorithm in benchmarks.
*/
int aTwos = Integer.numberOfTrailingZeros(a);
a >>= aTwos; // divide out all 2s
int bTwos = Integer.numberOfTrailingZeros(b);
b >>= bTwos; // divide out all 2s
while (a != b) { // both a, b are odd
// The key to the binary GCD algorithm is as follows:
// Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b).
// But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two.
// We bend over backwards to avoid branching, adapting a technique from
// http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
int delta = a - b; // can't overflow, since a and b are nonnegative
int minDeltaOrZero = delta & (delta >> (Integer.SIZE - 1));
// equivalent to Math.min(delta, 0)
a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b)
// a is now nonnegative and even
b += minDeltaOrZero; // sets b to min(old a, b)
a >>= Integer.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b
}
return a << min(aTwos, bTwos);
}
/**
* Returns the sum of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a + b} overflows in signed {@code int} arithmetic
*/
public static int checkedAdd(int a, int b) {
long result = (long) a + b;
checkNoOverflow(result == (int) result);
return (int) result;
}
/**
* Returns the difference of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a - b} overflows in signed {@code int} arithmetic
*/
public static int checkedSubtract(int a, int b) {
long result = (long) a - b;
checkNoOverflow(result == (int) result);
return (int) result;
}
/**
* Returns the product of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a * b} overflows in signed {@code int} arithmetic
*/
public static int checkedMultiply(int a, int b) {
long result = (long) a * b;
checkNoOverflow(result == (int) result);
return (int) result;
}
/**
* Returns the {@code b} to the {@code k}th power, provided it does not overflow.
*
* <p>{@link #pow} may be faster, but does not check for overflow.
*
* @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed
* {@code int} arithmetic
*/
public static int checkedPow(int b, int k) {
checkNonNegative("exponent", k);
switch (b) {
case 0:
return (k == 0) ? 1 : 0;
case 1:
return 1;
case (-1):
return ((k & 1) == 0) ? 1 : -1;
case 2:
checkNoOverflow(k < Integer.SIZE - 1);
return 1 << k;
case (-2):
checkNoOverflow(k < Integer.SIZE);
return ((k & 1) == 0) ? 1 << k : -1 << k;
default:
// continue below to handle the general case
}
int accum = 1;
while (true) {
switch (k) {
case 0:
return accum;
case 1:
return checkedMultiply(accum, b);
default:
if ((k & 1) != 0) {
accum = checkedMultiply(accum, b);
}
k >>= 1;
if (k > 0) {
checkNoOverflow(-FLOOR_SQRT_MAX_INT <= b & b <= FLOOR_SQRT_MAX_INT);
b *= b;
}
}
}
}
@VisibleForTesting static final int FLOOR_SQRT_MAX_INT = 46340;
/**
* Returns {@code n!}, that is, the product of the first {@code n} positive
* integers, {@code 1} if {@code n == 0}, or {@link Integer#MAX_VALUE} if the
* result does not fit in a {@code int}.
*
* @throws IllegalArgumentException if {@code n < 0}
*/
public static int factorial(int n) {
checkNonNegative("n", n);
return (n < factorials.length) ? factorials[n] : Integer.MAX_VALUE;
}
private static final int[] factorials = {
1,
1,
1 * 2,
1 * 2 * 3,
1 * 2 * 3 * 4,
1 * 2 * 3 * 4 * 5,
1 * 2 * 3 * 4 * 5 * 6,
1 * 2 * 3 * 4 * 5 * 6 * 7,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12};
/**
* Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and
* {@code k}, or {@link Integer#MAX_VALUE} if the result does not fit in an {@code int}.
*
* @throws IllegalArgumentException if {@code n < 0}, {@code k < 0} or {@code k > n}
*/
@GwtIncompatible("need BigIntegerMath to adequately test")
public static int binomial(int n, int k) {
checkNonNegative("n", n);
checkNonNegative("k", k);
checkArgument(k <= n, "k (%s) > n (%s)", k, n);
if (k > (n >> 1)) {
k = n - k;
}
if (k >= biggestBinomials.length || n > biggestBinomials[k]) {
return Integer.MAX_VALUE;
}
switch (k) {
case 0:
return 1;
case 1:
return n;
default:
long result = 1;
for (int i = 0; i < k; i++) {
result *= n - i;
result /= i + 1;
}
return (int) result;
}
}
// binomial(biggestBinomials[k], k) fits in an int, but not binomial(biggestBinomials[k]+1,k).
@VisibleForTesting static int[] biggestBinomials = {
Integer.MAX_VALUE,
Integer.MAX_VALUE,
65536,
2345,
477,
193,
110,
75,
58,
49,
43,
39,
37,
35,
34,
34,
33
};
/**
* Returns the arithmetic mean of {@code x} and {@code y}, rounded towards
* negative infinity. This method is overflow resilient.
*
* @since 14.0
*/
public static int mean(int x, int y) {
// Efficient method for computing the arithmetic mean.
// The alternative (x + y) / 2 fails for large values.
// The alternative (x + y) >>> 1 fails for negative values.
return (x & y) + ((x ^ y) >> 1);
}
private IntMath() {}
}
| Java |
/*
* Copyright (C) 2009 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.xml;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.escape.Escaper;
import com.google.common.escape.Escapers;
/**
* {@code Escaper} instances suitable for strings to be included in XML
* attribute values and elements' text contents. When possible, avoid manual
* escaping by using templating systems and high-level APIs that provide
* autoescaping. For example, consider <a href="http://www.xom.nu/">XOM</a> or
* <a href="http://www.jdom.org/">JDOM</a>.
*
* <p><b>Note</b>: Currently the escapers provided by this class do not escape
* any characters outside the ASCII character range. Unlike HTML escaping the
* XML escapers will not escape non-ASCII characters to their numeric entity
* replacements. These XML escapers provide the minimal level of escaping to
* ensure that the output can be safely included in a Unicode XML document.
*
*
* <p>For details on the behavior of the escapers in this class, see sections
* <a href="http://www.w3.org/TR/2008/REC-xml-20081126/#charsets">2.2</a> and
* <a href="http://www.w3.org/TR/2008/REC-xml-20081126/#syntax">2.4</a> of the
* XML specification.
*
* @author Alex Matevossian
* @author David Beaumont
* @since 15.0
*/
@Beta
@GwtCompatible
public class XmlEscapers {
private XmlEscapers() {}
private static final char MIN_ASCII_CONTROL_CHAR = 0x00;
private static final char MAX_ASCII_CONTROL_CHAR = 0x1F;
// For each xxxEscaper() method, please add links to external reference pages
// that are considered authoritative for the behavior of that escaper.
// TODO(user): When this escaper strips \uFFFE & \uFFFF, add this doc.
// <p>This escaper also silently removes non-whitespace control characters and
// the character values {@code 0xFFFE} and {@code 0xFFFF} which are not
// permitted in XML. For more detail see section
// <a href="http://www.w3.org/TR/2008/REC-xml-20081126/#charsets">2.2</a> of
// the XML specification.
/**
* Returns an {@link Escaper} instance that escapes special characters in a
* string so it can safely be included in an XML document as element content.
* See section
* <a href="http://www.w3.org/TR/2008/REC-xml-20081126/#syntax">2.4</a> of the
* XML specification.
*
* <p><b>Note</b>: Double and single quotes are not escaped, so it is <b>not
* safe</b> to use this escaper to escape attribute values. Use
* {@link #xmlContentEscaper} if the output can appear in element content or
* {@link #xmlAttributeEscaper} in attribute values.
*
* <p>This escaper does not escape non-ASCII characters to their numeric
* character references (NCR). Any non-ASCII characters appearing in the input
* will be preserved in the output. Specifically "\r" (carriage return) is
* preserved in the output, which may result in it being silently converted to
* "\n" when the XML is parsed.
*
* <p>This escaper does not treat surrogate pairs specially and does not
* perform Unicode validation on its input.
*/
public static Escaper xmlContentEscaper() {
return XML_CONTENT_ESCAPER;
}
/**
* Returns an {@link Escaper} instance that escapes special characters in a
* string so it can safely be included in XML document as an attribute value.
* See section
* <a href="http://www.w3.org/TR/2008/REC-xml-20081126/#AVNormalize">3.3.3</a>
* of the XML specification.
*
* <p>This escaper does not escape non-ASCII characters to their numeric
* character references (NCR). However, horizontal tab {@code '\t'}, line feed
* {@code '\n'} and carriage return {@code '\r'} are escaped to a
* corresponding NCR {@code "	"}, {@code "
"}, and {@code "
"}
* respectively. Any other non-ASCII characters appearing in the input will
* be preserved in the output.
*
* <p>This escaper does not treat surrogate pairs specially and does not
* perform Unicode validation on its input.
*/
public static Escaper xmlAttributeEscaper() {
return XML_ATTRIBUTE_ESCAPER;
}
private static final Escaper XML_ESCAPER;
private static final Escaper XML_CONTENT_ESCAPER;
private static final Escaper XML_ATTRIBUTE_ESCAPER;
static {
Escapers.Builder builder = Escapers.builder();
// The char values \uFFFE and \uFFFF are explicitly not allowed in XML
// (Unicode code points above \uFFFF are represented via surrogate pairs
// which means they are treated as pairs of safe characters).
// TODO(user): When refactoring done change the \uFFFF below to \uFFFD
builder.setSafeRange(Character.MIN_VALUE, '\uFFFF');
// Unsafe characters are removed.
builder.setUnsafeReplacement("");
// Except for '\n', '\t' and '\r' we remove all ASCII control characters.
// An alternative to this would be to make a map that simply replaces the
// allowed ASCII whitespace characters with themselves and set the minimum
// safe character to 0x20. However this would slow down the escaping of
// simple strings that contain '\t','\n' or '\r'.
for (char c = MIN_ASCII_CONTROL_CHAR; c <= MAX_ASCII_CONTROL_CHAR; c++) {
if (c != '\t' && c != '\n' && c != '\r') {
builder.addEscape(c, "");
}
}
// Build the content escaper first and then add quote escaping for the
// general escaper.
builder.addEscape('&', "&");
builder.addEscape('<', "<");
builder.addEscape('>', ">");
XML_CONTENT_ESCAPER = builder.build();
builder.addEscape('\'', "'");
builder.addEscape('"', """);
XML_ESCAPER = builder.build();
builder.addEscape('\t', "	");
builder.addEscape('\n', "
");
builder.addEscape('\r', "
");
XML_ATTRIBUTE_ESCAPER = builder.build();
}
}
| Java |
/*
* Copyright (C) 2007 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.eventbus;
import com.google.common.collect.Multimap;
/**
* A method for finding event handler methods in objects, for use by
* {@link EventBus}.
*
* @author Cliff Biffle
*/
interface HandlerFindingStrategy {
/**
* Finds all suitable event handler methods in {@code source}, organizes them
* by the type of event they handle, and wraps them in {@link EventHandler} instances.
*
* @param source object whose handlers are desired.
* @return EventHandler objects for each handler method, organized by event
* type.
*
* @throws IllegalArgumentException if {@code source} is not appropriate for
* this strategy (in ways that this interface does not define).
*/
Multimap<Class<?>, EventHandler> findAllHandlers(Object source);
}
| Java |
/*
* Copyright (C) 2007 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.eventbus;
import com.google.common.annotations.Beta;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks an event handling method as being thread-safe. This annotation
* indicates that EventBus may invoke the event handler simultaneously from
* multiple threads.
*
* <p>This does not mark the method as an event handler, and so should be used
* in combination with {@link Subscribe}.
*
* @author Cliff Biffle
* @since 10.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Beta
public @interface AllowConcurrentEvents {
}
| Java |
/*
* Copyright (C) 2007 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.eventbus;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
/**
* Wraps an event that was posted, but which had no subscribers and thus could
* not be delivered.
*
* <p>Subscribing a DeadEvent handler is useful for debugging or logging, as it
* can detect misconfigurations in a system's event distribution.
*
* @author Cliff Biffle
* @since 10.0
*/
@Beta
public class DeadEvent {
private final Object source;
private final Object event;
/**
* Creates a new DeadEvent.
*
* @param source object broadcasting the DeadEvent (generally the
* {@link EventBus}).
* @param event the event that could not be delivered.
*/
public DeadEvent(Object source, Object event) {
this.source = checkNotNull(source);
this.event = checkNotNull(event);
}
/**
* Returns the object that originated this event (<em>not</em> the object that
* originated the wrapped event). This is generally an {@link EventBus}.
*
* @return the source of this event.
*/
public Object getSource() {
return source;
}
/**
* Returns the wrapped, 'dead' event, which the system was unable to deliver
* to any registered handler.
*
* @return the 'dead' event that could not be delivered.
*/
public Object getEvent() {
return event;
}
}
| Java |
/*
* Copyright (C) 2007 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.eventbus;
import com.google.common.base.Objects;
import com.google.common.base.Throwables;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.reflect.TypeToken;
import com.google.common.util.concurrent.UncheckedExecutionException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A {@link HandlerFindingStrategy} for collecting all event handler methods that are marked with
* the {@link Subscribe} annotation.
*
* @author Cliff Biffle
* @author Louis Wasserman
*/
class AnnotatedHandlerFinder implements HandlerFindingStrategy {
/**
* A thread-safe cache that contains the mapping from each class to all methods in that class and
* all super-classes, that are annotated with {@code @Subscribe}. The cache is shared across all
* instances of this class; this greatly improves performance if multiple EventBus instances are
* created and objects of the same class are registered on all of them.
*/
private static final LoadingCache<Class<?>, ImmutableList<Method>> handlerMethodsCache =
CacheBuilder.newBuilder()
.weakKeys()
.build(new CacheLoader<Class<?>, ImmutableList<Method>>() {
@Override
public ImmutableList<Method> load(Class<?> concreteClass) throws Exception {
return getAnnotatedMethodsInternal(concreteClass);
}
});
/**
* {@inheritDoc}
*
* This implementation finds all methods marked with a {@link Subscribe} annotation.
*/
@Override
public Multimap<Class<?>, EventHandler> findAllHandlers(Object listener) {
Multimap<Class<?>, EventHandler> methodsInListener = HashMultimap.create();
Class<?> clazz = listener.getClass();
for (Method method : getAnnotatedMethods(clazz)) {
Class<?>[] parameterTypes = method.getParameterTypes();
Class<?> eventType = parameterTypes[0];
EventHandler handler = makeHandler(listener, method);
methodsInListener.put(eventType, handler);
}
return methodsInListener;
}
private static ImmutableList<Method> getAnnotatedMethods(Class<?> clazz) {
try {
return handlerMethodsCache.getUnchecked(clazz);
} catch (UncheckedExecutionException e) {
throw Throwables.propagate(e.getCause());
}
}
private static final class MethodIdentifier {
private final String name;
private final List<Class<?>> parameterTypes;
MethodIdentifier(Method method) {
this.name = method.getName();
this.parameterTypes = Arrays.asList(method.getParameterTypes());
}
@Override
public int hashCode() {
return Objects.hashCode(name, parameterTypes);
}
@Override
public boolean equals(@Nullable Object o) {
if (o instanceof MethodIdentifier) {
MethodIdentifier ident = (MethodIdentifier) o;
return name.equals(ident.name) && parameterTypes.equals(ident.parameterTypes);
}
return false;
}
}
private static ImmutableList<Method> getAnnotatedMethodsInternal(Class<?> clazz) {
Set<? extends Class<?>> supers = TypeToken.of(clazz).getTypes().rawTypes();
Map<MethodIdentifier, Method> identifiers = Maps.newHashMap();
for (Class<?> superClazz : supers) {
for (Method superClazzMethod : superClazz.getMethods()) {
if (superClazzMethod.isAnnotationPresent(Subscribe.class)) {
Class<?>[] parameterTypes = superClazzMethod.getParameterTypes();
if (parameterTypes.length != 1) {
throw new IllegalArgumentException("Method " + superClazzMethod
+ " has @Subscribe annotation, but requires " + parameterTypes.length
+ " arguments. Event handler methods must require a single argument.");
}
MethodIdentifier ident = new MethodIdentifier(superClazzMethod);
if (!identifiers.containsKey(ident)) {
identifiers.put(ident, superClazzMethod);
}
}
}
}
return ImmutableList.copyOf(identifiers.values());
}
/**
* Creates an {@code EventHandler} for subsequently calling {@code method} on
* {@code listener}.
* Selects an EventHandler implementation based on the annotations on
* {@code method}.
*
* @param listener object bearing the event handler method.
* @param method the event handler method to wrap in an EventHandler.
* @return an EventHandler that will call {@code method} on {@code listener}
* when invoked.
*/
private static EventHandler makeHandler(Object listener, Method method) {
EventHandler wrapper;
if (methodIsDeclaredThreadSafe(method)) {
wrapper = new EventHandler(listener, method);
} else {
wrapper = new SynchronizedEventHandler(listener, method);
}
return wrapper;
}
/**
* Checks whether {@code method} is thread-safe, as indicated by the
* {@link AllowConcurrentEvents} annotation.
*
* @param method handler method to check.
* @return {@code true} if {@code handler} is marked as thread-safe,
* {@code false} otherwise.
*/
private static boolean methodIsDeclaredThreadSafe(Method method) {
return method.getAnnotation(AllowConcurrentEvents.class) != null;
}
}
| Java |
/*
* Copyright (C) 2007 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.eventbus;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.SetMultimap;
import com.google.common.reflect.TypeToken;
import com.google.common.util.concurrent.UncheckedExecutionException;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Dispatches events to listeners, and provides ways for listeners to register
* themselves.
*
* <p>The EventBus allows publish-subscribe-style communication between
* components without requiring the components to explicitly register with one
* another (and thus be aware of each other). It is designed exclusively to
* replace traditional Java in-process event distribution using explicit
* registration. It is <em>not</em> a general-purpose publish-subscribe system,
* nor is it intended for interprocess communication.
*
* <h2>Receiving Events</h2>
* <p>To receive events, an object should:<ol>
* <li>Expose a public method, known as the <i>event handler</i>, which accepts
* a single argument of the type of event desired;</li>
* <li>Mark it with a {@link Subscribe} annotation;</li>
* <li>Pass itself to an EventBus instance's {@link #register(Object)} method.
* </li>
* </ol>
*
* <h2>Posting Events</h2>
* <p>To post an event, simply provide the event object to the
* {@link #post(Object)} method. The EventBus instance will determine the type
* of event and route it to all registered listeners.
*
* <p>Events are routed based on their type — an event will be delivered
* to any handler for any type to which the event is <em>assignable.</em> This
* includes implemented interfaces, all superclasses, and all interfaces
* implemented by superclasses.
*
* <p>When {@code post} is called, all registered handlers for an event are run
* in sequence, so handlers should be reasonably quick. If an event may trigger
* an extended process (such as a database load), spawn a thread or queue it for
* later. (For a convenient way to do this, use an {@link AsyncEventBus}.)
*
* <h2>Handler Methods</h2>
* <p>Event handler methods must accept only one argument: the event.
*
* <p>Handlers should not, in general, throw. If they do, the EventBus will
* catch and log the exception. This is rarely the right solution for error
* handling and should not be relied upon; it is intended solely to help find
* problems during development.
*
* <p>The EventBus guarantees that it will not call a handler method from
* multiple threads simultaneously, unless the method explicitly allows it by
* bearing the {@link AllowConcurrentEvents} annotation. If this annotation is
* not present, handler methods need not worry about being reentrant, unless
* also called from outside the EventBus.
*
* <h2>Dead Events</h2>
* <p>If an event is posted, but no registered handlers can accept it, it is
* considered "dead." To give the system a second chance to handle dead events,
* they are wrapped in an instance of {@link DeadEvent} and reposted.
*
* <p>If a handler for a supertype of all events (such as Object) is registered,
* no event will ever be considered dead, and no DeadEvents will be generated.
* Accordingly, while DeadEvent extends {@link Object}, a handler registered to
* receive any Object will never receive a DeadEvent.
*
* <p>This class is safe for concurrent use.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/EventBusExplained">
* {@code EventBus}</a>.
*
* @author Cliff Biffle
* @since 10.0
*/
@Beta
public class EventBus {
/**
* A thread-safe cache for flattenHierarchy(). The Class class is immutable. This cache is shared
* across all EventBus instances, which greatly improves performance if multiple such instances
* are created and objects of the same class are posted on all of them.
*/
private static final LoadingCache<Class<?>, Set<Class<?>>> flattenHierarchyCache =
CacheBuilder.newBuilder()
.weakKeys()
.build(new CacheLoader<Class<?>, Set<Class<?>>>() {
@SuppressWarnings({"unchecked", "rawtypes"}) // safe cast
@Override
public Set<Class<?>> load(Class<?> concreteClass) {
return (Set) TypeToken.of(concreteClass).getTypes().rawTypes();
}
});
/**
* All registered event handlers, indexed by event type.
*
* <p>This SetMultimap is NOT safe for concurrent use; all access should be
* made after acquiring a read or write lock via {@link #handlersByTypeLock}.
*/
private final SetMultimap<Class<?>, EventHandler> handlersByType =
HashMultimap.create();
private final ReadWriteLock handlersByTypeLock = new ReentrantReadWriteLock();
/**
* Logger for event dispatch failures. Named by the fully-qualified name of
* this class, followed by the identifier provided at construction.
*/
private final Logger logger;
/**
* Strategy for finding handler methods in registered objects. Currently,
* only the {@link AnnotatedHandlerFinder} is supported, but this is
* encapsulated for future expansion.
*/
private final HandlerFindingStrategy finder = new AnnotatedHandlerFinder();
/** queues of events for the current thread to dispatch */
private final ThreadLocal<Queue<EventWithHandler>> eventsToDispatch =
new ThreadLocal<Queue<EventWithHandler>>() {
@Override protected Queue<EventWithHandler> initialValue() {
return new LinkedList<EventWithHandler>();
}
};
/** true if the current thread is currently dispatching an event */
private final ThreadLocal<Boolean> isDispatching =
new ThreadLocal<Boolean>() {
@Override protected Boolean initialValue() {
return false;
}
};
/**
* Creates a new EventBus named "default".
*/
public EventBus() {
this("default");
}
/**
* Creates a new EventBus with the given {@code identifier}.
*
* @param identifier a brief name for this bus, for logging purposes. Should
* be a valid Java identifier.
*/
public EventBus(String identifier) {
logger = Logger.getLogger(EventBus.class.getName() + "." + checkNotNull(identifier));
}
/**
* Registers all handler methods on {@code object} to receive events.
* Handler methods are selected and classified using this EventBus's
* {@link HandlerFindingStrategy}; the default strategy is the
* {@link AnnotatedHandlerFinder}.
*
* @param object object whose handler methods should be registered.
*/
public void register(Object object) {
Multimap<Class<?>, EventHandler> methodsInListener =
finder.findAllHandlers(object);
handlersByTypeLock.writeLock().lock();
try {
handlersByType.putAll(methodsInListener);
} finally {
handlersByTypeLock.writeLock().unlock();
}
}
/**
* Unregisters all handler methods on a registered {@code object}.
*
* @param object object whose handler methods should be unregistered.
* @throws IllegalArgumentException if the object was not previously registered.
*/
public void unregister(Object object) {
Multimap<Class<?>, EventHandler> methodsInListener = finder.findAllHandlers(object);
for (Entry<Class<?>, Collection<EventHandler>> entry : methodsInListener.asMap().entrySet()) {
Class<?> eventType = entry.getKey();
Collection<EventHandler> eventMethodsInListener = entry.getValue();
handlersByTypeLock.writeLock().lock();
try {
Set<EventHandler> currentHandlers = handlersByType.get(eventType);
if (!currentHandlers.containsAll(eventMethodsInListener)) {
throw new IllegalArgumentException(
"missing event handler for an annotated method. Is " + object + " registered?");
}
currentHandlers.removeAll(eventMethodsInListener);
} finally {
handlersByTypeLock.writeLock().unlock();
}
}
}
/**
* Posts an event to all registered handlers. This method will return
* successfully after the event has been posted to all handlers, and
* regardless of any exceptions thrown by handlers.
*
* <p>If no handlers have been subscribed for {@code event}'s class, and
* {@code event} is not already a {@link DeadEvent}, it will be wrapped in a
* DeadEvent and reposted.
*
* @param event event to post.
*/
public void post(Object event) {
Set<Class<?>> dispatchTypes = flattenHierarchy(event.getClass());
boolean dispatched = false;
for (Class<?> eventType : dispatchTypes) {
handlersByTypeLock.readLock().lock();
try {
Set<EventHandler> wrappers = handlersByType.get(eventType);
if (!wrappers.isEmpty()) {
dispatched = true;
for (EventHandler wrapper : wrappers) {
enqueueEvent(event, wrapper);
}
}
} finally {
handlersByTypeLock.readLock().unlock();
}
}
if (!dispatched && !(event instanceof DeadEvent)) {
post(new DeadEvent(this, event));
}
dispatchQueuedEvents();
}
/**
* Queue the {@code event} for dispatch during
* {@link #dispatchQueuedEvents()}. Events are queued in-order of occurrence
* so they can be dispatched in the same order.
*/
void enqueueEvent(Object event, EventHandler handler) {
eventsToDispatch.get().offer(new EventWithHandler(event, handler));
}
/**
* Drain the queue of events to be dispatched. As the queue is being drained,
* new events may be posted to the end of the queue.
*/
void dispatchQueuedEvents() {
// don't dispatch if we're already dispatching, that would allow reentrancy
// and out-of-order events. Instead, leave the events to be dispatched
// after the in-progress dispatch is complete.
if (isDispatching.get()) {
return;
}
isDispatching.set(true);
try {
Queue<EventWithHandler> events = eventsToDispatch.get();
EventWithHandler eventWithHandler;
while ((eventWithHandler = events.poll()) != null) {
dispatch(eventWithHandler.event, eventWithHandler.handler);
}
} finally {
isDispatching.remove();
eventsToDispatch.remove();
}
}
/**
* Dispatches {@code event} to the handler in {@code wrapper}. This method
* is an appropriate override point for subclasses that wish to make
* event delivery asynchronous.
*
* @param event event to dispatch.
* @param wrapper wrapper that will call the handler.
*/
void dispatch(Object event, EventHandler wrapper) {
try {
wrapper.handleEvent(event);
} catch (InvocationTargetException e) {
logger.log(Level.SEVERE,
"Could not dispatch event: " + event + " to handler " + wrapper, e);
}
}
/**
* Flattens a class's type hierarchy into a set of Class objects. The set
* will include all superclasses (transitively), and all interfaces
* implemented by these superclasses.
*
* @param concreteClass class whose type hierarchy will be retrieved.
* @return {@code clazz}'s complete type hierarchy, flattened and uniqued.
*/
@VisibleForTesting
Set<Class<?>> flattenHierarchy(Class<?> concreteClass) {
try {
return flattenHierarchyCache.getUnchecked(concreteClass);
} catch (UncheckedExecutionException e) {
throw Throwables.propagate(e.getCause());
}
}
/** simple struct representing an event and it's handler */
static class EventWithHandler {
final Object event;
final EventHandler handler;
public EventWithHandler(Object event, EventHandler handler) {
this.event = checkNotNull(event);
this.handler = checkNotNull(handler);
}
}
}
| Java |
/*
* Copyright (C) 2007 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.eventbus;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Preconditions;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.annotation.Nullable;
/**
* Wraps a single-argument 'handler' method on a specific object.
*
* <p>This class only verifies the suitability of the method and event type if
* something fails. Callers are expected to verify their uses of this class.
*
* <p>Two EventHandlers are equivalent when they refer to the same method on the
* same object (not class). This property is used to ensure that no handler
* method is registered more than once.
*
* @author Cliff Biffle
*/
class EventHandler {
/** Object sporting the handler method. */
private final Object target;
/** Handler method. */
private final Method method;
/**
* Creates a new EventHandler to wrap {@code method} on @{code target}.
*
* @param target object to which the method applies.
* @param method handler method.
*/
EventHandler(Object target, Method method) {
Preconditions.checkNotNull(target,
"EventHandler target cannot be null.");
Preconditions.checkNotNull(method, "EventHandler method cannot be null.");
this.target = target;
this.method = method;
method.setAccessible(true);
}
/**
* Invokes the wrapped handler method to handle {@code event}.
*
* @param event event to handle
* @throws InvocationTargetException if the wrapped method throws any
* {@link Throwable} that is not an {@link Error} ({@code Error} instances are
* propagated as-is).
*/
public void handleEvent(Object event) throws InvocationTargetException {
checkNotNull(event);
try {
method.invoke(target, new Object[] { event });
} catch (IllegalArgumentException e) {
throw new Error("Method rejected target/argument: " + event, e);
} catch (IllegalAccessException e) {
throw new Error("Method became inaccessible: " + event, e);
} catch (InvocationTargetException e) {
if (e.getCause() instanceof Error) {
throw (Error) e.getCause();
}
throw e;
}
}
@Override public String toString() {
return "[wrapper " + method + "]";
}
@Override public int hashCode() {
final int PRIME = 31;
return (PRIME + method.hashCode()) * PRIME
+ System.identityHashCode(target);
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof EventHandler) {
EventHandler that = (EventHandler) obj;
// Use == so that different equal instances will still receive events.
// We only guard against the case that the same object is registered
// multiple times
return target == that.target && method.equals(that.method);
}
return false;
}
}
| Java |
/*
* Copyright (C) 2007 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.
*/
/**
* The EventBus allows publish-subscribe-style communication between components
* without requiring the components to explicitly register with one another
* (and thus be aware of each other). It is designed exclusively to replace
* traditional Java in-process event distribution using explicit registration.
* It is <em>not</em> a general-purpose publish-subscribe system, nor is it
* intended for interprocess communication.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/EventBusExplained">
* {@code EventBus}</a>.
*
* <h2>One-Minute Guide</h2>
*
* <p>Converting an existing EventListener-based system to use the EventBus is
* easy.
*
* <h3>For Listeners</h3>
* <p>To listen for a specific flavor of event (say, a CustomerChangeEvent)...
* <ul>
* <li><strong>...in traditional Java events:</strong> implement an interface
* defined with the event — such as CustomerChangeEventListener.</li>
* <li><strong>...with EventBus:</strong> create a method that accepts
* CustomerChangeEvent as its sole argument, and mark it with the
* {@link com.google.common.eventbus.Subscribe} annotation.</li>
* </ul>
*
* <p>To register your listener methods with the event producers...
* <ul>
* <li><strong>...in traditional Java events:</strong> pass your object to each
* producer's {@code registerCustomerChangeEventListener} method. These
* methods are rarely defined in common interfaces, so in addition to
* knowing every possible producer, you must also know its type.</li>
* <li><strong>...with EventBus:</strong> pass your object to the
* {@link com.google.common.eventbus.EventBus#register(Object)} method on an
* EventBus. You'll need to
* make sure that your object shares an EventBus instance with the event
* producers.</li>
* </ul>
*
* <p>To listen for a common event supertype (such as EventObject or Object)...
* <ul>
* <li><strong>...in traditional Java events:</strong> not easy.</li>
* <li><strong>...with EventBus:</strong> events are automatically dispatched to
* listeners of any supertype, allowing listeners for interface types
* or "wildcard listeners" for Object.</li>
* </ul>
*
* <p>To listen for and detect events that were dispatched without listeners...
* <ul>
* <li><strong>...in traditional Java events:</strong> add code to each
* event-dispatching method (perhaps using AOP).</li>
* <li><strong>...with EventBus:</strong> subscribe to {@link
* com.google.common.eventbus.DeadEvent}. The
* EventBus will notify you of any events that were posted but not
* delivered. (Handy for debugging.)</li>
* </ul>
*
* <h3>For Producers</h3>
* <p>To keep track of listeners to your events...
* <ul>
* <li><strong>...in traditional Java events:</strong> write code to manage
* a list of listeners to your object, including synchronization, or use a
* utility class like EventListenerList.</li>
* <li><strong>...with EventBus:</strong> EventBus does this for you.</li>
* </ul>
*
* <p>To dispatch an event to listeners...
* <ul>
* <li><strong>...in traditional Java events:</strong> write a method to
* dispatch events to each event listener, including error isolation and
* (if desired) asynchronicity.</li>
* <li><strong>...with EventBus:</strong> pass the event object to an EventBus's
* {@link com.google.common.eventbus.EventBus#post(Object)} method.</li>
* </ul>
*
* <h2>Glossary</h2>
*
* <p>The EventBus system and code use the following terms to discuss event
* distribution:
* <dl>
* <dt>Event</dt><dd>Any object that may be <em>posted</em> to a bus.</dd>
* <dt>Subscribing</dt><dd>The act of registering a <em>listener</em> with an
* EventBus, so that its <em>handler methods</em> will receive events.</dd>
* <dt>Listener</dt><dd>An object that wishes to receive events, by exposing
* <em>handler methods</em>.</dt>
* <dt>Handler method</dt><dd>A public method that the EventBus should use to
* deliver <em>posted</em> events. Handler methods are marked by the
* {@link com.google.common.eventbus.Subscribe} annotation.</dd>
* <dt>Posting an event</dt><dd>Making the event available to any
* <em>listeners</em> through the EventBus.</dt>
* </dl>
*
* <h2>FAQ</h2>
* <h3>Why must I create my own Event Bus, rather than using a singleton?</h3>
*
* <p>The Event Bus doesn't specify how you use it; there's nothing stopping your
* application from having separate EventBus instances for each component, or
* using separate instances to separate events by context or topic. This also
* makes it trivial to set up and tear down EventBus objects in your tests.
*
* <p>Of course, if you'd like to have a process-wide EventBus singleton,
* there's nothing stopping you from doing it that way. Simply have your
* container (such as Guice) create the EventBus as a singleton at global scope
* (or stash it in a static field, if you're into that sort of thing).
*
* <p>In short, the EventBus is not a singleton because we'd rather not make
* that decision for you. Use it how you like.
*
* <h3>Why use an annotation to mark handler methods, rather than requiring the
* listener to implement an interface?</h3>
* <p>We feel that the Event Bus's {@code @Subscribe} annotation conveys your
* intentions just as explicitly as implementing an interface (or perhaps more
* so), while leaving you free to place event handler methods wherever you wish
* and give them intention-revealing names.
*
* <p>Traditional Java Events use a listener interface which typically sports
* only a handful of methods -- typically one. This has a number of
* disadvantages:
* <ul>
* <li>Any one class can only implement a single response to a given event.
* <li>Listener interface methods may conflict.
* <li>The method must be named after the event (e.g. {@code
* handleChangeEvent}), rather than its purpose (e.g. {@code
* recordChangeInJournal}).
* <li>Each event usually has its own interface, without a common parent
* interface for a family of events (e.g. all UI events).
* </ul>
*
* <p>The difficulties in implementing this cleanly has given rise to a pattern,
* particularly common in Swing apps, of using tiny anonymous classes to
* implement event listener interfaces.
*
* <p>Compare these two cases: <pre>
* class ChangeRecorder {
* void setCustomer(Customer cust) {
* cust.addChangeListener(new ChangeListener() {
* void customerChanged(ChangeEvent e) {
* recordChange(e.getChange());
* }
* };
* }
* }
*
* // Class is typically registered by the container.
* class EventBusChangeRecorder {
* @Subscribe void recordCustomerChange(ChangeEvent e) {
* recordChange(e.getChange());
* }
* }</pre>
*
* <p>The intent is actually clearer in the second case: there's less noise code,
* and the event handler has a clear and meaningful name.
*
* <h3>What about a generic {@code Handler<T>} interface?</h3>
* <p>Some have proposed a generic {@code Handler<T>} interface for EventBus
* listeners. This runs into issues with Java's use of type erasure, not to
* mention problems in usability.
*
* <p>Let's say the interface looked something like the following: <pre> {@code
* interface Handler<T> {
* void handleEvent(T event);
* }}</pre>
*
* <p>Due to erasure, no single class can implement a generic interface more than
* once with different type parameters. This is a giant step backwards from
* traditional Java Events, where even if {@code actionPerformed} and {@code
* keyPressed} aren't very meaningful names, at least you can implement both
* methods!
*
* <h3>Doesn't EventBus destroy static typing and eliminate automated
* refactoring support?</h3>
* <p>Some have freaked out about EventBus's {@code register(Object)} and {@code
* post(Object)} methods' use of the {@code Object} type.
*
* <p>{@code Object} is used here for a good reason: the Event Bus library
* places no restrictions on the types of either your event listeners (as in
* {@code register(Object)}) or the events themselves (in {@code post(Object)}).
*
* <p>Event handler methods, on the other hand, must explicitly declare their
* argument type -- the type of event desired (or one of its supertypes). Thus,
* searching for references to an event class will instantly find all handler
* methods for that event, and renaming the type will affect all handler methods
* within view of your IDE (and any code that creates the event).
*
* <p>It's true that you can rename your {@code @Subscribed} event handler
* methods at will; Event Bus will not stop this or do anything to propagate the
* rename because, to Event Bus, the names of your handler methods are
* irrelevant. Test code that calls the methods directly, of course, will be
* affected by your renaming -- but that's what your refactoring tools are for.
*
* <h3>What happens if I {@code register} a listener without any handler
* methods?</h3>
* <p>Nothing at all.
*
* <p>The Event Bus was designed to integrate with containers and module
* systems, with Guice as the prototypical example. In these cases, it's
* convenient to have the container/factory/environment pass <i>every</i>
* created object to an EventBus's {@code register(Object)} method.
*
* <p>This way, any object created by the container/factory/environment can
* hook into the system's event model simply by exposing handler methods.
*
* <h3>What Event Bus problems can be detected at compile time?</h3>
* <p>Any problem that can be unambiguously detected by Java's type system. For
* example, defining a handler method for a nonexistent event type.
*
* <h3>What Event Bus problems can be detected immediately at registration?</h3>
* <p>Immediately upon invoking {@code register(Object)} , the listener being
* registered is checked for the <i>well-formedness</i> of its handler methods.
* Specifically, any methods marked with {@code @Subscribe} must take only a
* single argument.
*
* <p>Any violations of this rule will cause an {@code IllegalArgumentException}
* to be thrown.
*
* <p>(This check could be moved to compile-time using APT, a solution we're
* researching.)
*
* <h3>What Event Bus problems may only be detected later, at runtime?</h3>
* <p>If a component posts events with no registered listeners, it <i>may</i>
* indicate an error (typically an indication that you missed a
* {@code @Subscribe} annotation, or that the listening component is not loaded).
*
* <p>(Note that this is <i>not necessarily</i> indicative of a problem. There
* are many cases where an application will deliberately ignore a posted event,
* particularly if the event is coming from code you don't control.)
*
* <p>To handle such events, register a handler method for the {@code DeadEvent}
* class. Whenever EventBus receives an event with no registered handlers, it
* will turn it into a {@code DeadEvent} and pass it your way -- allowing you to
* log it or otherwise recover.
*
* <h3>How do I test event listeners and their handler methods?</h3>
* <p>Because handler methods on your listener classes are normal methods, you can
* simply call them from your test code to simulate the EventBus.
*/
package com.google.common.eventbus;
| Java |
/*
* Copyright (C) 2007 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.eventbus;
import com.google.common.annotations.Beta;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks a method as an event handler, as used by
* {@link AnnotatedHandlerFinder} and {@link EventBus}.
*
* <p>The type of event will be indicated by the method's first (and only)
* parameter. If this annotation is applied to methods with zero parameters,
* or more than one parameter, the object containing the method will not be able
* to register for event delivery from the {@link EventBus}.
*
* <p>Unless also annotated with @{@link AllowConcurrentEvents}, event handler
* methods will be invoked serially by each event bus that they are registered
* with.
*
* @author Cliff Biffle
* @since 10.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Beta
public @interface Subscribe {
}
| Java |
/*
* Copyright (C) 2007 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.eventbus;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Wraps a single-argument 'handler' method on a specific object, and ensures
* that only one thread may enter the method at a time.
*
* <p>Beyond synchronization, this class behaves identically to
* {@link EventHandler}.
*
* @author Cliff Biffle
*/
final class SynchronizedEventHandler extends EventHandler {
/**
* Creates a new SynchronizedEventHandler to wrap {@code method} on
* {@code target}.
*
* @param target object to which the method applies.
* @param method handler method.
*/
public SynchronizedEventHandler(Object target, Method method) {
super(target, method);
}
@Override
public void handleEvent(Object event) throws InvocationTargetException {
// https://code.google.com/p/guava-libraries/issues/detail?id=1403
synchronized (this) {
super.handleEvent(event);
}
}
}
| Java |
/*
* Copyright (C) 2007 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.eventbus;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
/**
* An {@link EventBus} that takes the Executor of your choice and uses it to
* dispatch events, allowing dispatch to occur asynchronously.
*
* @author Cliff Biffle
* @since 10.0
*/
@Beta
public class AsyncEventBus extends EventBus {
private final Executor executor;
/** the queue of events is shared across all threads */
private final ConcurrentLinkedQueue<EventWithHandler> eventsToDispatch =
new ConcurrentLinkedQueue<EventWithHandler>();
/**
* Creates a new AsyncEventBus that will use {@code executor} to dispatch
* events. Assigns {@code identifier} as the bus's name for logging purposes.
*
* @param identifier short name for the bus, for logging purposes.
* @param executor Executor to use to dispatch events. It is the caller's
* responsibility to shut down the executor after the last event has
* been posted to this event bus.
*/
public AsyncEventBus(String identifier, Executor executor) {
super(identifier);
this.executor = checkNotNull(executor);
}
/**
* Creates a new AsyncEventBus that will use {@code executor} to dispatch
* events.
*
* @param executor Executor to use to dispatch events. It is the caller's
* responsibility to shut down the executor after the last event has
* been posted to this event bus.
*/
public AsyncEventBus(Executor executor) {
this.executor = checkNotNull(executor);
}
@Override
void enqueueEvent(Object event, EventHandler handler) {
eventsToDispatch.offer(new EventWithHandler(event, handler));
}
/**
* Dispatch {@code events} in the order they were posted, regardless of
* the posting thread.
*/
@SuppressWarnings("deprecation") // only deprecated for external subclasses
@Override
protected void dispatchQueuedEvents() {
while (true) {
EventWithHandler eventWithHandler = eventsToDispatch.poll();
if (eventWithHandler == null) {
break;
}
dispatch(eventWithHandler.event, eventWithHandler.handler);
}
}
/**
* Calls the {@link #executor} to dispatch {@code event} to {@code handler}.
*/
@Override
void dispatch(final Object event, final EventHandler handler) {
checkNotNull(event);
checkNotNull(handler);
executor.execute(
new Runnable() {
@Override
public void run() {
AsyncEventBus.super.dispatch(event, handler);
}
});
}
}
| Java |
/*
* Copyright (C) 2009 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.escape;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Map;
/**
* A {@link CharEscaper} that uses an array to quickly look up replacement
* characters for a given {@code char} value. An additional safe range is
* provided that determines whether {@code char} values without specific
* replacements are to be considered safe and left unescaped or should be
* escaped in a general way.
*
* <p>A good example of usage of this class is for Java source code escaping
* where the replacement array contains information about special ASCII
* characters such as {@code \\t} and {@code \\n} while {@link #escapeUnsafe}
* is overridden to handle general escaping of the form {@code \\uxxxx}.
*
* <p>The size of the data structure used by {@link ArrayBasedCharEscaper} is
* proportional to the highest valued character that requires escaping.
* For example a replacement map containing the single character
* '{@code \}{@code u1000}' will require approximately 16K of memory. If you
* need to create multiple escaper instances that have the same character
* replacement mapping consider using {@link ArrayBasedEscaperMap}.
*
* @author Sven Mawson
* @author David Beaumont
* @since 15.0
*/
@Beta
@GwtCompatible
public abstract class ArrayBasedCharEscaper extends CharEscaper {
// The replacement array (see ArrayBasedEscaperMap).
private final char[][] replacements;
// The number of elements in the replacement array.
private final int replacementsLength;
// The first character in the safe range.
private final char safeMin;
// The last character in the safe range.
private final char safeMax;
/**
* Creates a new ArrayBasedCharEscaper instance with the given replacement map
* and specified safe range. If {@code safeMax < safeMin} then no characters
* are considered safe.
*
* <p>If a character has no mapped replacement then it is checked against the
* safe range. If it lies outside that, then {@link #escapeUnsafe} is
* called, otherwise no escaping is performed.
*
* @param replacementMap a map of characters to their escaped representations
* @param safeMin the lowest character value in the safe range
* @param safeMax the highest character value in the safe range
*/
protected ArrayBasedCharEscaper(Map<Character, String> replacementMap,
char safeMin, char safeMax) {
this(ArrayBasedEscaperMap.create(replacementMap), safeMin, safeMax);
}
/**
* Creates a new ArrayBasedCharEscaper instance with the given replacement map
* and specified safe range. If {@code safeMax < safeMin} then no characters
* are considered safe. This initializer is useful when explicit instances of
* ArrayBasedEscaperMap are used to allow the sharing of large replacement
* mappings.
*
* <p>If a character has no mapped replacement then it is checked against the
* safe range. If it lies outside that, then {@link #escapeUnsafe} is
* called, otherwise no escaping is performed.
*
* @param escaperMap the mapping of characters to be escaped
* @param safeMin the lowest character value in the safe range
* @param safeMax the highest character value in the safe range
*/
protected ArrayBasedCharEscaper(ArrayBasedEscaperMap escaperMap,
char safeMin, char safeMax) {
checkNotNull(escaperMap); // GWT specific check (do not optimize)
this.replacements = escaperMap.getReplacementArray();
this.replacementsLength = replacements.length;
if (safeMax < safeMin) {
// If the safe range is empty, set the range limits to opposite extremes
// to ensure the first test of either value will (almost certainly) fail.
safeMax = Character.MIN_VALUE;
safeMin = Character.MAX_VALUE;
}
this.safeMin = safeMin;
this.safeMax = safeMax;
}
/*
* This is overridden to improve performance. Rough benchmarking shows that
* this almost doubles the speed when processing strings that do not require
* any escaping.
*/
@Override
public final String escape(String s) {
checkNotNull(s); // GWT specific check (do not optimize).
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ((c < replacementsLength && replacements[c] != null) ||
c > safeMax || c < safeMin) {
return escapeSlow(s, i);
}
}
return s;
}
/**
* Escapes a single character using the replacement array and safe range
* values. If the given character does not have an explicit replacement and
* lies outside the safe range then {@link #escapeUnsafe} is called.
*/
@Override protected final char[] escape(char c) {
if (c < replacementsLength) {
char[] chars = replacements[c];
if (chars != null) {
return chars;
}
}
if (c >= safeMin && c <= safeMax) {
return null;
}
return escapeUnsafe(c);
}
/**
* Escapes a {@code char} value that has no direct explicit value in the
* replacement array and lies outside the stated safe range. Subclasses should
* override this method to provide generalized escaping for characters.
*
* <p>Note that arrays returned by this method must not be modified once they
* have been returned. However it is acceptable to return the same array
* multiple times (even for different input characters).
*
* @param c the character to escape
* @return the replacement characters, or {@code null} if no escaping was
* required
*/
// TODO(user,cpovirk): Rename this something better once refactoring done
protected abstract char[] escapeUnsafe(char c);
}
| Java |
/*
* 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.escape;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
/**
* An {@link Escaper} that converts literal text into a format safe for
* inclusion in a particular context (such as an XML document). Typically (but
* not always), the inverse process of "unescaping" the text is performed
* automatically by the relevant parser.
*
* <p>For example, an XML escaper would convert the literal string {@code
* "Foo<Bar>"} into {@code "Foo<Bar>"} to prevent {@code "<Bar>"} from
* being confused with an XML tag. When the resulting XML document is parsed,
* the parser API will return this text as the original literal string {@code
* "Foo<Bar>"}.
*
* <p><b>Note:</b> This class is similar to {@link CharEscaper} but with one
* very important difference. A CharEscaper can only process Java
* <a href="http://en.wikipedia.org/wiki/UTF-16">UTF16</a> characters in
* isolation and may not cope when it encounters surrogate pairs. This class
* facilitates the correct escaping of all Unicode characters.
*
* <p>As there are important reasons, including potential security issues, to
* handle Unicode correctly if you are considering implementing a new escaper
* you should favor using UnicodeEscaper wherever possible.
*
* <p>A {@code UnicodeEscaper} instance is required to be stateless, and safe
* when used concurrently by multiple threads.
*
* <p>Several popular escapers are defined as constants in classes like {@link
* com.google.common.html.HtmlEscapers}, {@link
* com.google.common.xml.XmlEscapers}, and {@link SourceCodeEscapers}. To create
* your own escapers extend this class and implement the {@link #escape(int)}
* method.
*
* @author David Beaumont
* @since 15.0
*/
@Beta
@GwtCompatible
public abstract class UnicodeEscaper extends Escaper {
/** The amount of padding (chars) to use when growing the escape buffer. */
private static final int DEST_PAD = 32;
/** Constructor for use by subclasses. */
protected UnicodeEscaper() {}
/**
* Returns the escaped form of the given Unicode code point, or {@code null}
* if this code point does not need to be escaped. When called as part of an
* escaping operation, the given code point is guaranteed to be in the range
* {@code 0 <= cp <= Character#MAX_CODE_POINT}.
*
* <p>If an empty array is returned, this effectively strips the input
* character from the resulting text.
*
* <p>If the character does not need to be escaped, this method should return
* {@code null}, rather than an array containing the character representation
* of the code point. This enables the escaping algorithm to perform more
* efficiently.
*
* <p>If the implementation of this method cannot correctly handle a
* particular code point then it should either throw an appropriate runtime
* exception or return a suitable replacement character. It must never
* silently discard invalid input as this may constitute a security risk.
*
* @param cp the Unicode code point to escape if necessary
* @return the replacement characters, or {@code null} if no escaping was
* needed
*/
protected abstract char[] escape(int cp);
/**
* Scans a sub-sequence of characters from a given {@link CharSequence},
* returning the index of the next character that requires escaping.
*
* <p><b>Note:</b> When implementing an escaper, it is a good idea to override
* this method for efficiency. The base class implementation determines
* successive Unicode code points and invokes {@link #escape(int)} for each of
* them. If the semantics of your escaper are such that code points in the
* supplementary range are either all escaped or all unescaped, this method
* can be implemented more efficiently using {@link CharSequence#charAt(int)}.
*
* <p>Note however that if your escaper does not escape characters in the
* supplementary range, you should either continue to validate the correctness
* of any surrogate characters encountered or provide a clear warning to users
* that your escaper does not validate its input.
*
* <p>See {@link com.google.common.net.PercentEscaper} for an example.
*
* @param csq a sequence of characters
* @param start the index of the first character to be scanned
* @param end the index immediately after the last character to be scanned
* @throws IllegalArgumentException if the scanned sub-sequence of {@code csq}
* contains invalid surrogate pairs
*/
protected int nextEscapeIndex(CharSequence csq, int start, int end) {
int index = start;
while (index < end) {
int cp = codePointAt(csq, index, end);
if (cp < 0 || escape(cp) != null) {
break;
}
index += Character.isSupplementaryCodePoint(cp) ? 2 : 1;
}
return index;
}
/**
* Returns the escaped form of a given literal string.
*
* <p>If you are escaping input in arbitrary successive chunks, then it is not
* generally safe to use this method. If an input string ends with an
* unmatched high surrogate character, then this method will throw
* {@link IllegalArgumentException}. You should ensure your input is valid <a
* href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> before calling this
* method.
*
* <p><b>Note:</b> When implementing an escaper it is a good idea to override
* this method for efficiency by inlining the implementation of
* {@link #nextEscapeIndex(CharSequence, int, int)} directly. Doing this for
* {@link com.google.common.net.PercentEscaper} more than doubled the
* performance for unescaped strings (as measured by {@link
* CharEscapersBenchmark}).
*
* @param string the literal string to be escaped
* @return the escaped form of {@code string}
* @throws NullPointerException if {@code string} is null
* @throws IllegalArgumentException if invalid surrogate characters are
* encountered
*/
@Override
public String escape(String string) {
checkNotNull(string);
int end = string.length();
int index = nextEscapeIndex(string, 0, end);
return index == end ? string : escapeSlow(string, index);
}
/**
* Returns the escaped form of a given literal string, starting at the given
* index. This method is called by the {@link #escape(String)} method when it
* discovers that escaping is required. It is protected to allow subclasses
* to override the fastpath escaping function to inline their escaping test.
* See {@link CharEscaperBuilder} for an example usage.
*
* <p>This method is not reentrant and may only be invoked by the top level
* {@link #escape(String)} method.
*
* @param s the literal string to be escaped
* @param index the index to start escaping from
* @return the escaped form of {@code string}
* @throws NullPointerException if {@code string} is null
* @throws IllegalArgumentException if invalid surrogate characters are
* encountered
*/
protected final String escapeSlow(String s, int index) {
int end = s.length();
// Get a destination buffer and setup some loop variables.
char[] dest = Platform.charBufferFromThreadLocal();
int destIndex = 0;
int unescapedChunkStart = 0;
while (index < end) {
int cp = codePointAt(s, index, end);
if (cp < 0) {
throw new IllegalArgumentException(
"Trailing high surrogate at end of input");
}
// It is possible for this to return null because nextEscapeIndex() may
// (for performance reasons) yield some false positives but it must never
// give false negatives.
char[] escaped = escape(cp);
int nextIndex = index + (Character.isSupplementaryCodePoint(cp) ? 2 : 1);
if (escaped != null) {
int charsSkipped = index - unescapedChunkStart;
// This is the size needed to add the replacement, not the full
// size needed by the string. We only regrow when we absolutely must.
int sizeNeeded = destIndex + charsSkipped + escaped.length;
if (dest.length < sizeNeeded) {
int destLength = sizeNeeded + (end - index) + DEST_PAD;
dest = growBuffer(dest, destIndex, destLength);
}
// If we have skipped any characters, we need to copy them now.
if (charsSkipped > 0) {
s.getChars(unescapedChunkStart, index, dest, destIndex);
destIndex += charsSkipped;
}
if (escaped.length > 0) {
System.arraycopy(escaped, 0, dest, destIndex, escaped.length);
destIndex += escaped.length;
}
// If we dealt with an escaped character, reset the unescaped range.
unescapedChunkStart = nextIndex;
}
index = nextEscapeIndex(s, nextIndex, end);
}
// Process trailing unescaped characters - no need to account for escaped
// length or padding the allocation.
int charsSkipped = end - unescapedChunkStart;
if (charsSkipped > 0) {
int endIndex = destIndex + charsSkipped;
if (dest.length < endIndex) {
dest = growBuffer(dest, destIndex, endIndex);
}
s.getChars(unescapedChunkStart, end, dest, destIndex);
destIndex = endIndex;
}
return new String(dest, 0, destIndex);
}
/**
* Returns the Unicode code point of the character at the given index.
*
* <p>Unlike {@link Character#codePointAt(CharSequence, int)} or
* {@link String#codePointAt(int)} this method will never fail silently when
* encountering an invalid surrogate pair.
*
* <p>The behaviour of this method is as follows:
* <ol>
* <li>If {@code index >= end}, {@link IndexOutOfBoundsException} is thrown.
* <li><b>If the character at the specified index is not a surrogate, it is
* returned.</b>
* <li>If the first character was a high surrogate value, then an attempt is
* made to read the next character.
* <ol>
* <li><b>If the end of the sequence was reached, the negated value of
* the trailing high surrogate is returned.</b>
* <li><b>If the next character was a valid low surrogate, the code point
* value of the high/low surrogate pair is returned.</b>
* <li>If the next character was not a low surrogate value, then
* {@link IllegalArgumentException} is thrown.
* </ol>
* <li>If the first character was a low surrogate value,
* {@link IllegalArgumentException} is thrown.
* </ol>
*
* @param seq the sequence of characters from which to decode the code point
* @param index the index of the first character to decode
* @param end the index beyond the last valid character to decode
* @return the Unicode code point for the given index or the negated value of
* the trailing high surrogate character at the end of the sequence
*/
protected static int codePointAt(CharSequence seq, int index, int end) {
checkNotNull(seq);
if (index < end) {
char c1 = seq.charAt(index++);
if (c1 < Character.MIN_HIGH_SURROGATE ||
c1 > Character.MAX_LOW_SURROGATE) {
// Fast path (first test is probably all we need to do)
return c1;
} else if (c1 <= Character.MAX_HIGH_SURROGATE) {
// If the high surrogate was the last character, return its inverse
if (index == end) {
return -c1;
}
// Otherwise look for the low surrogate following it
char c2 = seq.charAt(index);
if (Character.isLowSurrogate(c2)) {
return Character.toCodePoint(c1, c2);
}
throw new IllegalArgumentException(
"Expected low surrogate but got char '" + c2 +
"' with value " + (int) c2 + " at index " + index +
" in '" + seq + "'");
} else {
throw new IllegalArgumentException(
"Unexpected low surrogate character '" + c1 +
"' with value " + (int) c1 + " at index " + (index - 1) +
" in '" + seq + "'");
}
}
throw new IndexOutOfBoundsException("Index exceeds specified range");
}
/**
* Helper method to grow the character buffer as needed, this only happens
* once in a while so it's ok if it's in a method call. If the index passed
* in is 0 then no copying will be done.
*/
private static char[] growBuffer(char[] dest, int index, int size) {
char[] copy = new char[size];
if (index > 0) {
System.arraycopy(dest, 0, copy, 0, index);
}
return copy;
}
}
| Java |
/*
* Copyright (C) 2009 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.escape;
import com.google.common.annotations.GwtCompatible;
/**
* Methods factored out so that they can be emulated differently in GWT.
*
* @author Jesse Wilson
*/
@GwtCompatible(emulated = true)
final class Platform {
private Platform() {}
/** Returns a thread-local 1024-char array. */
static char[] charBufferFromThreadLocal() {
return DEST_TL.get();
}
/**
* A thread-local destination buffer to keep us from creating new buffers.
* The starting size is 1024 characters. If we grow past this we don't
* put it back in the threadlocal, we just keep going and grow as needed.
*/
private static final ThreadLocal<char[]> DEST_TL = new ThreadLocal<char[]>() {
@Override
protected char[] initialValue() {
return new char[1024];
}
};
}
| Java |
/*
* Copyright (C) 2012 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.
*/
/**
* Interfaces, utilities, and simple implementations of escapers and encoders. The primary type is
* {@link com.google.common.escape.Escaper}.
*
* <p>Additional escapers implementations are found in the applicable packages: {@link
* com.google.common.html.HtmlEscapers} in {@code com.google.common.html}, {@link
* com.google.common.xml.XmlEscapers} in {@code com.google.common.xml}, and {@link
* com.google.common.net.UrlEscapers} in {@code com.google.common.net}.
*
* <p>This package is a part of the open-source
* <a href="http://guava-libraries.googlecode.com">Guava libraries</a>.
*/
@ParametersAreNonnullByDefault
package com.google.common.escape;
import javax.annotation.ParametersAreNonnullByDefault;
| Java |
/*
* Copyright (C) 2006 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.escape;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.HashMap;
import java.util.Map;
/**
* Simple helper class to build a "sparse" array of objects based on the indexes that were added to
* it. The array will be from 0 to the maximum index given. All non-set indexes will contain null
* (so it's not really a sparse array, just a pseudo sparse array). The builder can also return a
* CharEscaper based on the generated array.
*
* @author Sven Mawson
* @since 15.0
*/
@Beta
@GwtCompatible
public final class CharEscaperBuilder {
/**
* Simple decorator that turns an array of replacement char[]s into a CharEscaper, this results in
* a very fast escape method.
*/
private static class CharArrayDecorator extends CharEscaper {
private final char[][] replacements;
private final int replaceLength;
CharArrayDecorator(char[][] replacements) {
this.replacements = replacements;
this.replaceLength = replacements.length;
}
/*
* Overriding escape method to be slightly faster for this decorator. We test the replacements
* array directly, saving a method call.
*/
@Override public String escape(String s) {
int slen = s.length();
for (int index = 0; index < slen; index++) {
char c = s.charAt(index);
if (c < replacements.length && replacements[c] != null) {
return escapeSlow(s, index);
}
}
return s;
}
@Override protected char[] escape(char c) {
return c < replaceLength ? replacements[c] : null;
}
}
// Replacement mappings.
private final Map<Character, String> map;
// The highest index we've seen so far.
private int max = -1;
/**
* Construct a new sparse array builder.
*/
public CharEscaperBuilder() {
this.map = new HashMap<Character, String>();
}
/**
* Add a new mapping from an index to an object to the escaping.
*/
public CharEscaperBuilder addEscape(char c, String r) {
map.put(c, checkNotNull(r));
if (c > max) {
max = c;
}
return this;
}
/**
* Add multiple mappings at once for a particular index.
*/
public CharEscaperBuilder addEscapes(char[] cs, String r) {
checkNotNull(r);
for (char c : cs) {
addEscape(c, r);
}
return this;
}
/**
* Convert this builder into an array of char[]s where the maximum index is the value of the
* highest character that has been seen. The array will be sparse in the sense that any unseen
* index will default to null.
*
* @return a "sparse" array that holds the replacement mappings.
*/
public char[][] toArray() {
char[][] result = new char[max + 1][];
for (Map.Entry<Character, String> entry : map.entrySet()) {
result[entry.getKey()] = entry.getValue().toCharArray();
}
return result;
}
/**
* Convert this builder into a char escaper which is just a decorator around the underlying array
* of replacement char[]s.
*
* @return an escaper that escapes based on the underlying array.
*/
public Escaper toEscaper() {
return new CharArrayDecorator(toArray());
}
}
| Java |
/*
* Copyright (C) 2006 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.escape;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
/**
* An object that converts literal text into a format safe for inclusion in a particular context
* (such as an XML document). Typically (but not always), the inverse process of "unescaping" the
* text is performed automatically by the relevant parser.
*
* <p>For example, an XML escaper would convert the literal string {@code "Foo<Bar>"} into {@code
* "Foo<Bar>"} to prevent {@code "<Bar>"} from being confused with an XML tag. When the
* resulting XML document is parsed, the parser API will return this text as the original literal
* string {@code "Foo<Bar>"}.
*
* <p>A {@code CharEscaper} instance is required to be stateless, and safe when used concurrently by
* multiple threads.
*
* <p>Several popular escapers are defined as constants in classes like {@link
* com.google.common.html.HtmlEscapers}, {@link com.google.common.xml.XmlEscapers}, and {@link
* SourceCodeEscapers}. To create your own escapers extend this class and implement the {@link
* #escape(char)} method.
*
* @author Sven Mawson
* @since 15.0
*/
@Beta
@GwtCompatible
public abstract class CharEscaper extends Escaper {
/** Constructor for use by subclasses. */
protected CharEscaper() {}
/**
* Returns the escaped form of a given literal string.
*
* @param string the literal string to be escaped
* @return the escaped form of {@code string}
* @throws NullPointerException if {@code string} is null
*/
@Override public String escape(String string) {
checkNotNull(string); // GWT specific check (do not optimize)
// Inlineable fast-path loop which hands off to escapeSlow() only if needed
int length = string.length();
for (int index = 0; index < length; index++) {
if (escape(string.charAt(index)) != null) {
return escapeSlow(string, index);
}
}
return string;
}
/**
* Returns the escaped form of a given literal string, starting at the given index. This method is
* called by the {@link #escape(String)} method when it discovers that escaping is required. It is
* protected to allow subclasses to override the fastpath escaping function to inline their
* escaping test. See {@link CharEscaperBuilder} for an example usage.
*
* @param s the literal string to be escaped
* @param index the index to start escaping from
* @return the escaped form of {@code string}
* @throws NullPointerException if {@code string} is null
*/
protected final String escapeSlow(String s, int index) {
int slen = s.length();
// Get a destination buffer and setup some loop variables.
char[] dest = Platform.charBufferFromThreadLocal();
int destSize = dest.length;
int destIndex = 0;
int lastEscape = 0;
// Loop through the rest of the string, replacing when needed into the
// destination buffer, which gets grown as needed as well.
for (; index < slen; index++) {
// Get a replacement for the current character.
char[] r = escape(s.charAt(index));
// If no replacement is needed, just continue.
if (r == null) continue;
int rlen = r.length;
int charsSkipped = index - lastEscape;
// This is the size needed to add the replacement, not the full size
// needed by the string. We only regrow when we absolutely must.
int sizeNeeded = destIndex + charsSkipped + rlen;
if (destSize < sizeNeeded) {
destSize = sizeNeeded + (slen - index) + DEST_PAD;
dest = growBuffer(dest, destIndex, destSize);
}
// If we have skipped any characters, we need to copy them now.
if (charsSkipped > 0) {
s.getChars(lastEscape, index, dest, destIndex);
destIndex += charsSkipped;
}
// Copy the replacement string into the dest buffer as needed.
if (rlen > 0) {
System.arraycopy(r, 0, dest, destIndex, rlen);
destIndex += rlen;
}
lastEscape = index + 1;
}
// Copy leftover characters if there are any.
int charsLeft = slen - lastEscape;
if (charsLeft > 0) {
int sizeNeeded = destIndex + charsLeft;
if (destSize < sizeNeeded) {
// Regrow and copy, expensive! No padding as this is the final copy.
dest = growBuffer(dest, destIndex, sizeNeeded);
}
s.getChars(lastEscape, slen, dest, destIndex);
destIndex = sizeNeeded;
}
return new String(dest, 0, destIndex);
}
/**
* Returns the escaped form of the given character, or {@code null} if this character does not
* need to be escaped. If an empty array is returned, this effectively strips the input character
* from the resulting text.
*
* <p>If the character does not need to be escaped, this method should return {@code null}, rather
* than a one-character array containing the character itself. This enables the escaping algorithm
* to perform more efficiently.
*
* <p>An escaper is expected to be able to deal with any {@code char} value, so this method should
* not throw any exceptions.
*
* @param c the character to escape if necessary
* @return the replacement characters, or {@code null} if no escaping was needed
*/
protected abstract char[] escape(char c);
/**
* Helper method to grow the character buffer as needed, this only happens once in a while so it's
* ok if it's in a method call. If the index passed in is 0 then no copying will be done.
*/
private static char[] growBuffer(char[] dest, int index, int size) {
char[] copy = new char[size];
if (index > 0) {
System.arraycopy(dest, 0, copy, 0, index);
}
return copy;
}
/**
* The amount of padding to use when growing the escape buffer.
*/
private static final int DEST_PAD = 32;
}
| Java |
/*
* Copyright (C) 2009 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.escape;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import java.util.Collections;
import java.util.Map;
/**
* An implementation-specific parameter class suitable for initializing
* {@link ArrayBasedCharEscaper} or {@link ArrayBasedUnicodeEscaper} instances.
* This class should be used when more than one escaper is created using the
* same character replacement mapping to allow the underlying (implementation
* specific) data structures to be shared.
*
* <p>The size of the data structure used by ArrayBasedCharEscaper and
* ArrayBasedUnicodeEscaper is proportional to the highest valued character that
* has a replacement. For example a replacement map containing the single
* character '{@literal \}u1000' will require approximately 16K of memory.
* As such sharing this data structure between escaper instances is the primary
* goal of this class.
*
* @author David Beaumont
* @since 15.0
*/
@Beta
@GwtCompatible
public final class ArrayBasedEscaperMap {
/**
* Returns a new ArrayBasedEscaperMap for creating ArrayBasedCharEscaper or
* ArrayBasedUnicodeEscaper instances.
*
* @param replacements a map of characters to their escaped representations
*/
public static ArrayBasedEscaperMap create(
Map<Character, String> replacements) {
return new ArrayBasedEscaperMap(createReplacementArray(replacements));
}
// The underlying replacement array we can share between multiple escaper
// instances.
private final char[][] replacementArray;
private ArrayBasedEscaperMap(char[][] replacementArray) {
this.replacementArray = replacementArray;
}
// Returns the non-null array of replacements for fast lookup.
char[][] getReplacementArray() {
return replacementArray;
}
// Creates a replacement array from the given map. The returned array is a
// linear lookup table of replacement character sequences indexed by the
// original character value.
@VisibleForTesting
static char[][] createReplacementArray(Map<Character, String> map) {
checkNotNull(map); // GWT specific check (do not optimize)
if (map.isEmpty()) {
return EMPTY_REPLACEMENT_ARRAY;
}
char max = Collections.max(map.keySet());
char[][] replacements = new char[max + 1][];
for (char c : map.keySet()) {
replacements[c] = map.get(c).toCharArray();
}
return replacements;
}
// Immutable empty array for when there are no replacements.
private static final char[][] EMPTY_REPLACEMENT_ARRAY = new char[0][0];
}
| Java |
/*
* 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.escape;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
/**
* An object that converts literal text into a format safe for inclusion in a particular context
* (such as an XML document). Typically (but not always), the inverse process of "unescaping" the
* text is performed automatically by the relevant parser.
*
* <p>For example, an XML escaper would convert the literal string {@code "Foo<Bar>"} into {@code
* "Foo<Bar>"} to prevent {@code "<Bar>"} from being confused with an XML tag. When the
* resulting XML document is parsed, the parser API will return this text as the original literal
* string {@code "Foo<Bar>"}.
*
* <p>An {@code Escaper} instance is required to be stateless, and safe when used concurrently by
* multiple threads.
*
* <p>Because, in general, escaping operates on the code points of a string and not on its
* individual {@code char} values, it is not safe to assume that {@code escape(s)} is equivalent to
* {@code escape(s.substring(0, n)) + escape(s.substing(n))} for arbitrary {@code n}. This is
* because of the possibility of splitting a surrogate pair. The only case in which it is safe to
* escape strings and concatenate the results is if you can rule out this possibility, either by
* splitting an existing long string into short strings adaptively around {@linkplain
* Character#isHighSurrogate surrogate} {@linkplain Character#isLowSurrogate pairs}, or by starting
* with short strings already known to be free of unpaired surrogates.
*
* <p>The two primary implementations of this interface are {@link CharEscaper} and {@link
* UnicodeEscaper}. They are heavily optimized for performance and greatly simplify the task of
* implementing new escapers. It is strongly recommended that when implementing a new escaper you
* extend one of these classes. If you find that you are unable to achieve the desired behavior
* using either of these classes, please contact the Java libraries team for advice.
*
* <p>Several popular escapers are defined as constants in classes like {@link
* com.google.common.html.HtmlEscapers}, {@link com.google.common.xml.XmlEscapers}, and {@link
* SourceCodeEscapers}. To create your own escapers, use {@link CharEscaperBuilder}, or extend
* {@code CharEscaper} or {@code UnicodeEscaper}.
*
* @author David Beaumont
* @since 15.0
*/
@Beta
@GwtCompatible
public abstract class Escaper {
// TODO(user): evaluate custom implementations, considering package private constructor.
/** Constructor for use by subclasses. */
protected Escaper() {}
/**
* Returns the escaped form of a given literal string.
*
* <p>Note that this method may treat input characters differently depending on the specific
* escaper implementation.
*
* <ul>
* <li>{@link UnicodeEscaper} handles <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a>
* correctly, including surrogate character pairs. If the input is badly formed the escaper
* should throw {@link IllegalArgumentException}.
* <li>{@link CharEscaper} handles Java characters independently and does not verify the input for
* well formed characters. A {@code CharEscaper} should not be used in situations where input
* is not guaranteed to be restricted to the Basic Multilingual Plane (BMP).
* </ul>
*
* @param string the literal string to be escaped
* @return the escaped form of {@code string}
* @throws NullPointerException if {@code string} is null
* @throws IllegalArgumentException if {@code string} contains badly formed UTF-16 or cannot be
* escaped for any other reason
*/
public abstract String escape(String string);
private final Function<String, String> asFunction =
new Function<String, String>() {
@Override
public String apply(String from) {
return escape(from);
}
};
/**
* Returns a {@link Function} that invokes {@link #escape(String)} on this escaper.
*/
public final Function<String, String> asFunction() {
return asFunction;
}
}
| Java |
/*
* Copyright (C) 2009 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.escape;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A {@link UnicodeEscaper} that uses an array to quickly look up replacement
* characters for a given code point. An additional safe range is provided that
* determines whether code points without specific replacements are to be
* considered safe and left unescaped or should be escaped in a general way.
*
* <p>A good example of usage of this class is for HTML escaping where the
* replacement array contains information about the named HTML entities
* such as {@code &} and {@code "} while {@link #escapeUnsafe} is
* overridden to handle general escaping of the form {@code &#NNNNN;}.
*
* <p>The size of the data structure used by {@link ArrayBasedUnicodeEscaper} is
* proportional to the highest valued code point that requires escaping.
* For example a replacement map containing the single character
* '{@code \}{@code u1000}' will require approximately 16K of memory. If you
* need to create multiple escaper instances that have the same character
* replacement mapping consider using {@link ArrayBasedEscaperMap}.
*
* @author David Beaumont
* @since 15.0
*/
@Beta
@GwtCompatible
public abstract class ArrayBasedUnicodeEscaper extends UnicodeEscaper {
// The replacement array (see ArrayBasedEscaperMap).
private final char[][] replacements;
// The number of elements in the replacement array.
private final int replacementsLength;
// The first code point in the safe range.
private final int safeMin;
// The last code point in the safe range.
private final int safeMax;
// Cropped values used in the fast path range checks.
private final char safeMinChar;
private final char safeMaxChar;
/**
* Creates a new ArrayBasedUnicodeEscaper instance with the given replacement
* map and specified safe range. If {@code safeMax < safeMin} then no code
* points are considered safe.
*
* <p>If a code point has no mapped replacement then it is checked against the
* safe range. If it lies outside that, then {@link #escapeUnsafe} is
* called, otherwise no escaping is performed.
*
* @param replacementMap a map of characters to their escaped representations
* @param safeMin the lowest character value in the safe range
* @param safeMax the highest character value in the safe range
* @param unsafeReplacement the default replacement for unsafe characters or
* null if no default replacement is required
*/
protected ArrayBasedUnicodeEscaper(Map<Character, String> replacementMap,
int safeMin, int safeMax, @Nullable String unsafeReplacement) {
this(ArrayBasedEscaperMap.create(replacementMap), safeMin, safeMax,
unsafeReplacement);
}
/**
* Creates a new ArrayBasedUnicodeEscaper instance with the given replacement
* map and specified safe range. If {@code safeMax < safeMin} then no code
* points are considered safe. This initializer is useful when explicit
* instances of ArrayBasedEscaperMap are used to allow the sharing of large
* replacement mappings.
*
* <p>If a code point has no mapped replacement then it is checked against the
* safe range. If it lies outside that, then {@link #escapeUnsafe} is
* called, otherwise no escaping is performed.
*
* @param escaperMap the map of replacements
* @param safeMin the lowest character value in the safe range
* @param safeMax the highest character value in the safe range
* @param unsafeReplacement the default replacement for unsafe characters or
* null if no default replacement is required
*/
protected ArrayBasedUnicodeEscaper(ArrayBasedEscaperMap escaperMap,
int safeMin, int safeMax, @Nullable String unsafeReplacement) {
checkNotNull(escaperMap); // GWT specific check (do not optimize)
this.replacements = escaperMap.getReplacementArray();
this.replacementsLength = replacements.length;
if (safeMax < safeMin) {
// If the safe range is empty, set the range limits to opposite extremes
// to ensure the first test of either value will fail.
safeMax = -1;
safeMin = Integer.MAX_VALUE;
}
this.safeMin = safeMin;
this.safeMax = safeMax;
// This is a bit of a hack but lets us do quicker per-character checks in
// the fast path code. The safe min/max values are very unlikely to extend
// into the range of surrogate characters, but if they do we must not test
// any values in that range. To see why, consider the case where:
// safeMin <= {hi,lo} <= safeMax
// where {hi,lo} are characters forming a surrogate pair such that:
// codePointOf(hi, lo) > safeMax
// which would result in the surrogate pair being (wrongly) considered safe.
// If we clip the safe range used during the per-character tests so it is
// below the values of characters in surrogate pairs, this cannot occur.
// This approach does mean that we break out of the fast path code in cases
// where we don't strictly need to, but this situation will almost never
// occur in practice.
if (safeMin >= Character.MIN_HIGH_SURROGATE) {
// The safe range is empty or the all safe code points lie in or above the
// surrogate range. Either way the character range is empty.
this.safeMinChar = Character.MAX_VALUE;
this.safeMaxChar = 0;
} else {
// The safe range is non empty and contains values below the surrogate
// range but may extend above it. We may need to clip the maximum value.
this.safeMinChar = (char) safeMin;
this.safeMaxChar = (char) Math.min(safeMax,
Character.MIN_HIGH_SURROGATE - 1);
}
}
/*
* This is overridden to improve performance. Rough benchmarking shows that
* this almost doubles the speed when processing strings that do not require
* any escaping.
*/
@Override
public final String escape(String s) {
checkNotNull(s); // GWT specific check (do not optimize)
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ((c < replacementsLength && replacements[c] != null) ||
c > safeMaxChar || c < safeMinChar) {
return escapeSlow(s, i);
}
}
return s;
}
/* Overridden for performance. */
@Override
protected final int nextEscapeIndex(CharSequence csq, int index, int end) {
while (index < end) {
char c = csq.charAt(index);
if ((c < replacementsLength && replacements[c] != null) ||
c > safeMaxChar || c < safeMinChar) {
break;
}
index++;
}
return index;
}
/**
* Escapes a single Unicode code point using the replacement array and safe
* range values. If the given character does not have an explicit replacement
* and lies outside the safe range then {@link #escapeUnsafe} is called.
*/
@Override
protected final char[] escape(int cp) {
if (cp < replacementsLength) {
char[] chars = replacements[cp];
if (chars != null) {
return chars;
}
}
if (cp >= safeMin && cp <= safeMax) {
return null;
}
return escapeUnsafe(cp);
}
/**
* Escapes a code point that has no direct explicit value in the replacement
* array and lies outside the stated safe range. Subclasses should override
* this method to provide generalized escaping for code points if required.
*
* <p>Note that arrays returned by this method must not be modified once they
* have been returned. However it is acceptable to return the same array
* multiple times (even for different input characters).
*
* @param cp the Unicode code point to escape
* @return the replacement characters, or {@code null} if no escaping was
* required
*/
protected abstract char[] escapeUnsafe(int cp);
}
| Java |
/*
* Copyright (C) 2009 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.escape;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to {@link Escaper} instances.
*
* @author Sven Mawson
* @author David Beaumont
* @since 15.0
*/
@Beta
@GwtCompatible
public final class Escapers {
private Escapers() {}
/**
* Returns an {@link Escaper} that does no escaping, passing all character
* data through unchanged.
*/
public static Escaper nullEscaper() {
return NULL_ESCAPER;
}
// An Escaper that efficiently performs no escaping.
// Extending CharEscaper (instead of Escaper) makes Escapers.compose() easier.
private static final Escaper NULL_ESCAPER = new CharEscaper() {
@Override public String escape(String string) {
return checkNotNull(string);
}
@Override protected char[] escape(char c) {
// TODO: Fix tests not to call this directly and make it throw an error.
return null;
}
};
/**
* Returns a builder for creating simple, fast escapers. A builder instance
* can be reused and each escaper that is created will be a snapshot of the
* current builder state. Builders are not thread safe.
*
* <p>The initial state of the builder is such that:
* <ul>
* <li>There are no replacement mappings<li>
* <li>{@code safeMin == Character.MIN_VALUE}</li>
* <li>{@code safeMax == Character.MAX_VALUE}</li>
* <li>{@code unsafeReplacement == null}</li>
* </ul>
* <p>For performance reasons escapers created by this builder are not
* Unicode aware and will not validate the well-formedness of their input.
*/
public static Builder builder() {
return new Builder();
}
/**
* A builder for simple, fast escapers.
*
* <p>Typically an escaper needs to deal with the escaping of high valued
* characters or code points. In these cases it is necessary to extend either
* {@link ArrayBasedCharEscaper} or {@link ArrayBasedUnicodeEscaper} to
* provide the desired behavior. However this builder is suitable for creating
* escapers that replace a relative small set of characters.
*
* @author David Beaumont
* @since 15.0
*/
@Beta
public static final class Builder {
private final Map<Character, String> replacementMap =
new HashMap<Character, String>();
private char safeMin = Character.MIN_VALUE;
private char safeMax = Character.MAX_VALUE;
private String unsafeReplacement = null;
// The constructor is exposed via the builder() method above.
private Builder() {}
/**
* Sets the safe range of characters for the escaper. Characters in this
* range that have no explicit replacement are considered 'safe' and remain
* unescaped in the output. If {@code safeMax < safeMin} then the safe range
* is empty.
*
* @param safeMin the lowest 'safe' character
* @param safeMax the highest 'safe' character
* @return the builder instance
*/
public Builder setSafeRange(char safeMin, char safeMax) {
this.safeMin = safeMin;
this.safeMax = safeMax;
return this;
}
/**
* Sets the replacement string for any characters outside the 'safe' range
* that have no explicit replacement. If {@code unsafeReplacement} is
* {@code null} then no replacement will occur, if it is {@code ""} then
* the unsafe characters are removed from the output.
*
* @param unsafeReplacement the string to replace unsafe chracters
* @return the builder instance
*/
public Builder setUnsafeReplacement(@Nullable String unsafeReplacement) {
this.unsafeReplacement = unsafeReplacement;
return this;
}
/**
* Adds a replacement string for the given input character. The specified
* character will be replaced by the given string whenever it occurs in the
* input, irrespective of whether it lies inside or outside the 'safe'
* range.
*
* @param c the character to be replaced
* @param replacement the string to replace the given character
* @return the builder instance
* @throws NullPointerException if {@code replacement} is null
*/
public Builder addEscape(char c, String replacement) {
checkNotNull(replacement);
// This can replace an existing character (the builder is re-usable).
replacementMap.put(c, replacement);
return this;
}
/**
* Returns a new escaper based on the current state of the builder.
*/
public Escaper build() {
return new ArrayBasedCharEscaper(replacementMap, safeMin, safeMax) {
private final char[] replacementChars =
unsafeReplacement != null ? unsafeReplacement.toCharArray() : null;
@Override protected char[] escapeUnsafe(char c) {
return replacementChars;
}
};
}
}
/**
* Returns a {@link UnicodeEscaper} equivalent to the given escaper instance.
* If the escaper is already a UnicodeEscaper then it is simply returned,
* otherwise it is wrapped in a UnicodeEscaper.
*
* <p>When a {@link CharEscaper} escaper is wrapped by this method it acquires
* extra behavior with respect to the well-formedness of Unicode character
* sequences and will throw {@link IllegalArgumentException} when given bad
* input.
*
* @param escaper the instance to be wrapped
* @return a UnicodeEscaper with the same behavior as the given instance
* @throws NullPointerException if escaper is null
* @throws IllegalArgumentException if escaper is not a UnicodeEscaper or a
* CharEscaper
*/
static UnicodeEscaper asUnicodeEscaper(Escaper escaper) {
checkNotNull(escaper);
if (escaper instanceof UnicodeEscaper) {
return (UnicodeEscaper) escaper;
} else if (escaper instanceof CharEscaper) {
return wrap((CharEscaper) escaper);
}
// In practice this shouldn't happen because it would be very odd not to
// extend either CharEscaper or UnicodeEscaper for non trivial cases.
throw new IllegalArgumentException("Cannot create a UnicodeEscaper from: " +
escaper.getClass().getName());
}
/**
* Returns a string that would replace the given character in the specified
* escaper, or {@code null} if no replacement should be made. This method is
* intended for use in tests through the {@code EscaperAsserts} class;
* production users of {@link CharEscaper} should limit themselves to its
* public interface.
*
* @param c the character to escape if necessary
* @return the replacement string, or {@code null} if no escaping was needed
*/
public static String computeReplacement(CharEscaper escaper, char c) {
return stringOrNull(escaper.escape(c));
}
/**
* Returns a string that would replace the given character in the specified
* escaper, or {@code null} if no replacement should be made. This method is
* intended for use in tests through the {@code EscaperAsserts} class;
* production users of {@link UnicodeEscaper} should limit themselves to its
* public interface.
*
* @param cp the Unicode code point to escape if necessary
* @return the replacement string, or {@code null} if no escaping was needed
*/
public static String computeReplacement(UnicodeEscaper escaper, int cp) {
return stringOrNull(escaper.escape(cp));
}
private static String stringOrNull(char[] in) {
return (in == null) ? null : new String(in);
}
/** Private helper to wrap a CharEscaper as a UnicodeEscaper. */
private static UnicodeEscaper wrap(final CharEscaper escaper) {
return new UnicodeEscaper() {
@Override protected char[] escape(int cp) {
// If a code point maps to a single character, just escape that.
if (cp < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
return escaper.escape((char) cp);
}
// Convert the code point to a surrogate pair and escape them both.
// Note: This code path is horribly slow and typically allocates 4 new
// char[] each time it is invoked. However this avoids any
// synchronization issues and makes the escaper thread safe.
char[] surrogateChars = new char[2];
Character.toChars(cp, surrogateChars, 0);
char[] hiChars = escaper.escape(surrogateChars[0]);
char[] loChars = escaper.escape(surrogateChars[1]);
// If either hiChars or lowChars are non-null, the CharEscaper is trying
// to escape the characters of a surrogate pair separately. This is
// uncommon and applies only to escapers that assume UCS-2 rather than
// UTF-16. See: http://en.wikipedia.org/wiki/UTF-16/UCS-2
if (hiChars == null && loChars == null) {
// We expect this to be the common code path for most escapers.
return null;
}
// Combine the characters and/or escaped sequences into a single array.
int hiCount = hiChars != null ? hiChars.length : 1;
int loCount = loChars != null ? loChars.length : 1;
char[] output = new char[hiCount + loCount];
if (hiChars != null) {
// TODO: Is this faster than System.arraycopy() for small arrays?
for (int n = 0; n < hiChars.length; ++n) {
output[n] = hiChars[n];
}
} else {
output[0] = surrogateChars[0];
}
if (loChars != null) {
for (int n = 0; n < loChars.length; ++n) {
output[hiCount + n] = loChars[n];
}
} else {
output[hiCount] = surrogateChars[1];
}
return output;
}
};
}
}
| Java |
/*
* 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.net;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import java.util.List;
/**
* Parser for a set of reversed domain names stored as a serialized radix tree.
*/
@GwtCompatible
class TrieParser {
private static final Joiner PREFIX_JOINER = Joiner.on("");
/**
* Parses a serialized trie representation of a set of reversed TLDs into an immutable set
* of TLDs.
*/
static ImmutableSet<String> parseTrie(CharSequence encoded) {
ImmutableSet.Builder<String> builder = ImmutableSet.builder();
int encodedLen = encoded.length();
int idx = 0;
while (idx < encodedLen) {
idx += doParseTrieToBuilder(
Lists.<CharSequence>newLinkedList(),
encoded.subSequence(idx, encodedLen),
builder);
}
return builder.build();
}
/**
* Parses a trie node and returns the number of characters consumed.
*
* @param stack The prefixes that preceed the characters represented by this node. Each entry
* of the stack is in reverse order.
* @param encoded The serialized trie.
* @param builder A set builder to which all entries will be added.
* @return The number of characters consumed from {@code encoded}.
*/
private static int doParseTrieToBuilder(
List<CharSequence> stack,
CharSequence encoded,
ImmutableSet.Builder<String> builder) {
int encodedLen = encoded.length();
int idx = 0;
char c = '\0';
// Read all of the characters for this node.
for ( ; idx < encodedLen; idx++) {
c = encoded.charAt(idx);
if (c == '&' || c == '?' || c == '!') {
break;
}
}
stack.add(0, reverse(encoded.subSequence(0, idx)));
if (c == '!' || c == '?') {
// '!' represents an interior node that represents an entry in the set.
// '?' represents a leaf node, which always represents an entry in set.
String domain = PREFIX_JOINER.join(stack);
if (domain.length() > 0) {
builder.add(domain);
}
}
idx++;
if (c != '?') {
while (idx < encodedLen) {
// Read all the children
idx += doParseTrieToBuilder(stack, encoded.subSequence(idx, encodedLen), builder);
if (encoded.charAt(idx) == '?') {
// An extra '?' after a child node indicates the end of all children of this node.
idx++;
break;
}
}
}
stack.remove(0);
return idx;
}
/**
* Reverses a character sequence. This is borrowed from
* https://code.google.com/p/google-web-toolkit/source/detail?r=11591#
* and can be replaced with a simple {@code StringBuffer#reverse} once GWT 2.6 is available.
*/
private static CharSequence reverse(CharSequence s) {
int length = s.length();
if (length <= 1) {
return s;
}
char[] buffer = new char[length];
buffer[0] = s.charAt(length - 1);
for (int i = 1; i < length; i++) {
buffer[i] = s.charAt(length - 1 - i);
if (Character.isSurrogatePair(buffer[i], buffer[i - 1])) {
swap(buffer, i - 1, i);
}
}
return new String(buffer);
}
private static void swap(char[] buffer, int f, int s) {
char tmp = buffer[f];
buffer[f] = buffer[s];
buffer[s] = tmp;
}
}
| Java |
/*
* 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.net;
import com.google.common.annotations.Beta;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.hash.Hashing;
import com.google.common.io.ByteStreams;
import com.google.common.primitives.Ints;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to {@link InetAddress} instances.
*
* <p><b>Important note:</b> Unlike {@code InetAddress.getByName()}, the
* methods of this class never cause DNS services to be accessed. For
* this reason, you should prefer these methods as much as possible over
* their JDK equivalents whenever you are expecting to handle only
* IP address string literals -- there is no blocking DNS penalty for a
* malformed string.
*
* <p>When dealing with {@link Inet4Address} and {@link Inet6Address}
* objects as byte arrays (vis. {@code InetAddress.getAddress()}) they
* are 4 and 16 bytes in length, respectively, and represent the address
* in network byte order.
*
* <p>Examples of IP addresses and their byte representations:
* <ul>
* <li>The IPv4 loopback address, {@code "127.0.0.1"}.<br/>
* {@code 7f 00 00 01}
*
* <li>The IPv6 loopback address, {@code "::1"}.<br/>
* {@code 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01}
*
* <li>From the IPv6 reserved documentation prefix ({@code 2001:db8::/32}),
* {@code "2001:db8::1"}.<br/>
* {@code 20 01 0d b8 00 00 00 00 00 00 00 00 00 00 00 01}
*
* <li>An IPv6 "IPv4 compatible" (or "compat") address,
* {@code "::192.168.0.1"}.<br/>
* {@code 00 00 00 00 00 00 00 00 00 00 00 00 c0 a8 00 01}
*
* <li>An IPv6 "IPv4 mapped" address, {@code "::ffff:192.168.0.1"}.<br/>
* {@code 00 00 00 00 00 00 00 00 00 00 ff ff c0 a8 00 01}
* </ul>
*
* <p>A few notes about IPv6 "IPv4 mapped" addresses and their observed
* use in Java.
* <br><br>
* "IPv4 mapped" addresses were originally a representation of IPv4
* addresses for use on an IPv6 socket that could receive both IPv4
* and IPv6 connections (by disabling the {@code IPV6_V6ONLY} socket
* option on an IPv6 socket). Yes, it's confusing. Nevertheless,
* these "mapped" addresses were never supposed to be seen on the
* wire. That assumption was dropped, some say mistakenly, in later
* RFCs with the apparent aim of making IPv4-to-IPv6 transition simpler.
*
* <p>Technically one <i>can</i> create a 128bit IPv6 address with the wire
* format of a "mapped" address, as shown above, and transmit it in an
* IPv6 packet header. However, Java's InetAddress creation methods
* appear to adhere doggedly to the original intent of the "mapped"
* address: all "mapped" addresses return {@link Inet4Address} objects.
*
* <p>For added safety, it is common for IPv6 network operators to filter
* all packets where either the source or destination address appears to
* be a "compat" or "mapped" address. Filtering suggestions usually
* recommend discarding any packets with source or destination addresses
* in the invalid range {@code ::/3}, which includes both of these bizarre
* address formats. For more information on "bogons", including lists
* of IPv6 bogon space, see:
*
* <ul>
* <li><a target="_parent"
* href="http://en.wikipedia.org/wiki/Bogon_filtering"
* >http://en.wikipedia.org/wiki/Bogon_filtering</a>
* <li><a target="_parent"
* href="http://www.cymru.com/Bogons/ipv6.txt"
* >http://www.cymru.com/Bogons/ipv6.txt</a>
* <li><a target="_parent"
* href="http://www.cymru.com/Bogons/v6bogon.html"
* >http://www.cymru.com/Bogons/v6bogon.html</a>
* <li><a target="_parent"
* href="http://www.space.net/~gert/RIPE/ipv6-filters.html"
* >http://www.space.net/~gert/RIPE/ipv6-filters.html</a>
* </ul>
*
* @author Erik Kline
* @since 5.0
*/
@Beta
public final class InetAddresses {
private static final int IPV4_PART_COUNT = 4;
private static final int IPV6_PART_COUNT = 8;
private static final Inet4Address LOOPBACK4 = (Inet4Address) forString("127.0.0.1");
private static final Inet4Address ANY4 = (Inet4Address) forString("0.0.0.0");
private InetAddresses() {}
/**
* Returns an {@link Inet4Address}, given a byte array representation of the IPv4 address.
*
* @param bytes byte array representing an IPv4 address (should be of length 4)
* @return {@link Inet4Address} corresponding to the supplied byte array
* @throws IllegalArgumentException if a valid {@link Inet4Address} can not be created
*/
private static Inet4Address getInet4Address(byte[] bytes) {
Preconditions.checkArgument(bytes.length == 4,
"Byte array has invalid length for an IPv4 address: %s != 4.",
bytes.length);
// Given a 4-byte array, this cast should always succeed.
return (Inet4Address) bytesToInetAddress(bytes);
}
/**
* Returns the {@link InetAddress} having the given string representation.
*
* <p>This deliberately avoids all nameservice lookups (e.g. no DNS).
*
* @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g.
* {@code "192.168.0.1"} or {@code "2001:db8::1"}
* @return {@link InetAddress} representing the argument
* @throws IllegalArgumentException if the argument is not a valid IP string literal
*/
public static InetAddress forString(String ipString) {
byte[] addr = ipStringToBytes(ipString);
// The argument was malformed, i.e. not an IP string literal.
if (addr == null) {
throw new IllegalArgumentException(
String.format("'%s' is not an IP string literal.", ipString));
}
return bytesToInetAddress(addr);
}
/**
* Returns {@code true} if the supplied string is a valid IP string
* literal, {@code false} otherwise.
*
* @param ipString {@code String} to evaluated as an IP string literal
* @return {@code true} if the argument is a valid IP string literal
*/
public static boolean isInetAddress(String ipString) {
return ipStringToBytes(ipString) != null;
}
private static byte[] ipStringToBytes(String ipString) {
// Make a first pass to categorize the characters in this string.
boolean hasColon = false;
boolean hasDot = false;
for (int i = 0; i < ipString.length(); i++) {
char c = ipString.charAt(i);
if (c == '.') {
hasDot = true;
} else if (c == ':') {
if (hasDot) {
return null; // Colons must not appear after dots.
}
hasColon = true;
} else if (Character.digit(c, 16) == -1) {
return null; // Everything else must be a decimal or hex digit.
}
}
// Now decide which address family to parse.
if (hasColon) {
if (hasDot) {
ipString = convertDottedQuadToHex(ipString);
if (ipString == null) {
return null;
}
}
return textToNumericFormatV6(ipString);
} else if (hasDot) {
return textToNumericFormatV4(ipString);
}
return null;
}
private static byte[] textToNumericFormatV4(String ipString) {
String[] address = ipString.split("\\.", IPV4_PART_COUNT + 1);
if (address.length != IPV4_PART_COUNT) {
return null;
}
byte[] bytes = new byte[IPV4_PART_COUNT];
try {
for (int i = 0; i < bytes.length; i++) {
bytes[i] = parseOctet(address[i]);
}
} catch (NumberFormatException ex) {
return null;
}
return bytes;
}
private static byte[] textToNumericFormatV6(String ipString) {
// An address can have [2..8] colons, and N colons make N+1 parts.
String[] parts = ipString.split(":", IPV6_PART_COUNT + 2);
if (parts.length < 3 || parts.length > IPV6_PART_COUNT + 1) {
return null;
}
// Disregarding the endpoints, find "::" with nothing in between.
// This indicates that a run of zeroes has been skipped.
int skipIndex = -1;
for (int i = 1; i < parts.length - 1; i++) {
if (parts[i].length() == 0) {
if (skipIndex >= 0) {
return null; // Can't have more than one ::
}
skipIndex = i;
}
}
int partsHi; // Number of parts to copy from above/before the "::"
int partsLo; // Number of parts to copy from below/after the "::"
if (skipIndex >= 0) {
// If we found a "::", then check if it also covers the endpoints.
partsHi = skipIndex;
partsLo = parts.length - skipIndex - 1;
if (parts[0].length() == 0 && --partsHi != 0) {
return null; // ^: requires ^::
}
if (parts[parts.length - 1].length() == 0 && --partsLo != 0) {
return null; // :$ requires ::$
}
} else {
// Otherwise, allocate the entire address to partsHi. The endpoints
// could still be empty, but parseHextet() will check for that.
partsHi = parts.length;
partsLo = 0;
}
// If we found a ::, then we must have skipped at least one part.
// Otherwise, we must have exactly the right number of parts.
int partsSkipped = IPV6_PART_COUNT - (partsHi + partsLo);
if (!(skipIndex >= 0 ? partsSkipped >= 1 : partsSkipped == 0)) {
return null;
}
// Now parse the hextets into a byte array.
ByteBuffer rawBytes = ByteBuffer.allocate(2 * IPV6_PART_COUNT);
try {
for (int i = 0; i < partsHi; i++) {
rawBytes.putShort(parseHextet(parts[i]));
}
for (int i = 0; i < partsSkipped; i++) {
rawBytes.putShort((short) 0);
}
for (int i = partsLo; i > 0; i--) {
rawBytes.putShort(parseHextet(parts[parts.length - i]));
}
} catch (NumberFormatException ex) {
return null;
}
return rawBytes.array();
}
private static String convertDottedQuadToHex(String ipString) {
int lastColon = ipString.lastIndexOf(':');
String initialPart = ipString.substring(0, lastColon + 1);
String dottedQuad = ipString.substring(lastColon + 1);
byte[] quad = textToNumericFormatV4(dottedQuad);
if (quad == null) {
return null;
}
String penultimate = Integer.toHexString(((quad[0] & 0xff) << 8) | (quad[1] & 0xff));
String ultimate = Integer.toHexString(((quad[2] & 0xff) << 8) | (quad[3] & 0xff));
return initialPart + penultimate + ":" + ultimate;
}
private static byte parseOctet(String ipPart) {
// Note: we already verified that this string contains only hex digits.
int octet = Integer.parseInt(ipPart);
// Disallow leading zeroes, because no clear standard exists on
// whether these should be interpreted as decimal or octal.
if (octet > 255 || (ipPart.startsWith("0") && ipPart.length() > 1)) {
throw new NumberFormatException();
}
return (byte) octet;
}
private static short parseHextet(String ipPart) {
// Note: we already verified that this string contains only hex digits.
int hextet = Integer.parseInt(ipPart, 16);
if (hextet > 0xffff) {
throw new NumberFormatException();
}
return (short) hextet;
}
/**
* Convert a byte array into an InetAddress.
*
* {@link InetAddress#getByAddress} is documented as throwing a checked
* exception "if IP address if of illegal length." We replace it with
* an unchecked exception, for use by callers who already know that addr
* is an array of length 4 or 16.
*
* @param addr the raw 4-byte or 16-byte IP address in big-endian order
* @return an InetAddress object created from the raw IP address
*/
private static InetAddress bytesToInetAddress(byte[] addr) {
try {
return InetAddress.getByAddress(addr);
} catch (UnknownHostException e) {
throw new AssertionError(e);
}
}
/**
* Returns the string representation of an {@link InetAddress}.
*
* <p>For IPv4 addresses, this is identical to
* {@link InetAddress#getHostAddress()}, but for IPv6 addresses, the output
* follows <a href="http://tools.ietf.org/html/rfc5952">RFC 5952</a>
* section 4. The main difference is that this method uses "::" for zero
* compression, while Java's version uses the uncompressed form.
*
* <p>This method uses hexadecimal for all IPv6 addresses, including
* IPv4-mapped IPv6 addresses such as "::c000:201". The output does not
* include a Scope ID.
*
* @param ip {@link InetAddress} to be converted to an address string
* @return {@code String} containing the text-formatted IP address
* @since 10.0
*/
public static String toAddrString(InetAddress ip) {
Preconditions.checkNotNull(ip);
if (ip instanceof Inet4Address) {
// For IPv4, Java's formatting is good enough.
return ip.getHostAddress();
}
Preconditions.checkArgument(ip instanceof Inet6Address);
byte[] bytes = ip.getAddress();
int[] hextets = new int[IPV6_PART_COUNT];
for (int i = 0; i < hextets.length; i++) {
hextets[i] = Ints.fromBytes(
(byte) 0, (byte) 0, bytes[2 * i], bytes[2 * i + 1]);
}
compressLongestRunOfZeroes(hextets);
return hextetsToIPv6String(hextets);
}
/**
* Identify and mark the longest run of zeroes in an IPv6 address.
*
* <p>Only runs of two or more hextets are considered. In case of a tie, the
* leftmost run wins. If a qualifying run is found, its hextets are replaced
* by the sentinel value -1.
*
* @param hextets {@code int[]} mutable array of eight 16-bit hextets
*/
private static void compressLongestRunOfZeroes(int[] hextets) {
int bestRunStart = -1;
int bestRunLength = -1;
int runStart = -1;
for (int i = 0; i < hextets.length + 1; i++) {
if (i < hextets.length && hextets[i] == 0) {
if (runStart < 0) {
runStart = i;
}
} else if (runStart >= 0) {
int runLength = i - runStart;
if (runLength > bestRunLength) {
bestRunStart = runStart;
bestRunLength = runLength;
}
runStart = -1;
}
}
if (bestRunLength >= 2) {
Arrays.fill(hextets, bestRunStart, bestRunStart + bestRunLength, -1);
}
}
/**
* Convert a list of hextets into a human-readable IPv6 address.
*
* <p>In order for "::" compression to work, the input should contain negative
* sentinel values in place of the elided zeroes.
*
* @param hextets {@code int[]} array of eight 16-bit hextets, or -1s
*/
private static String hextetsToIPv6String(int[] hextets) {
/*
* While scanning the array, handle these state transitions:
* start->num => "num" start->gap => "::"
* num->num => ":num" num->gap => "::"
* gap->num => "num" gap->gap => ""
*/
StringBuilder buf = new StringBuilder(39);
boolean lastWasNumber = false;
for (int i = 0; i < hextets.length; i++) {
boolean thisIsNumber = hextets[i] >= 0;
if (thisIsNumber) {
if (lastWasNumber) {
buf.append(':');
}
buf.append(Integer.toHexString(hextets[i]));
} else {
if (i == 0 || lastWasNumber) {
buf.append("::");
}
}
lastWasNumber = thisIsNumber;
}
return buf.toString();
}
/**
* Returns the string representation of an {@link InetAddress} suitable
* for inclusion in a URI.
*
* <p>For IPv4 addresses, this is identical to
* {@link InetAddress#getHostAddress()}, but for IPv6 addresses it
* compresses zeroes and surrounds the text with square brackets; for example
* {@code "[2001:db8::1]"}.
*
* <p>Per section 3.2.2 of
* <a target="_parent"
* href="http://tools.ietf.org/html/rfc3986#section-3.2.2"
* >http://tools.ietf.org/html/rfc3986</a>,
* a URI containing an IPv6 string literal is of the form
* {@code "http://[2001:db8::1]:8888/index.html"}.
*
* <p>Use of either {@link InetAddresses#toAddrString},
* {@link InetAddress#getHostAddress()}, or this method is recommended over
* {@link InetAddress#toString()} when an IP address string literal is
* desired. This is because {@link InetAddress#toString()} prints the
* hostname and the IP address string joined by a "/".
*
* @param ip {@link InetAddress} to be converted to URI string literal
* @return {@code String} containing URI-safe string literal
*/
public static String toUriString(InetAddress ip) {
if (ip instanceof Inet6Address) {
return "[" + toAddrString(ip) + "]";
}
return toAddrString(ip);
}
/**
* Returns an InetAddress representing the literal IPv4 or IPv6 host
* portion of a URL, encoded in the format specified by RFC 3986 section 3.2.2.
*
* <p>This function is similar to {@link InetAddresses#forString(String)},
* however, it requires that IPv6 addresses are surrounded by square brackets.
*
* <p>This function is the inverse of
* {@link InetAddresses#toUriString(java.net.InetAddress)}.
*
* @param hostAddr A RFC 3986 section 3.2.2 encoded IPv4 or IPv6 address
* @return an InetAddress representing the address in {@code hostAddr}
* @throws IllegalArgumentException if {@code hostAddr} is not a valid
* IPv4 address, or IPv6 address surrounded by square brackets
*/
public static InetAddress forUriString(String hostAddr) {
Preconditions.checkNotNull(hostAddr);
// Decide if this should be an IPv6 or IPv4 address.
String ipString;
int expectBytes;
if (hostAddr.startsWith("[") && hostAddr.endsWith("]")) {
ipString = hostAddr.substring(1, hostAddr.length() - 1);
expectBytes = 16;
} else {
ipString = hostAddr;
expectBytes = 4;
}
// Parse the address, and make sure the length/version is correct.
byte[] addr = ipStringToBytes(ipString);
if (addr == null || addr.length != expectBytes) {
throw new IllegalArgumentException(
String.format("Not a valid URI IP literal: '%s'", hostAddr));
}
return bytesToInetAddress(addr);
}
/**
* Returns {@code true} if the supplied string is a valid URI IP string
* literal, {@code false} otherwise.
*
* @param ipString {@code String} to evaluated as an IP URI host string literal
* @return {@code true} if the argument is a valid IP URI host
*/
public static boolean isUriInetAddress(String ipString) {
try {
forUriString(ipString);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
/**
* Evaluates whether the argument is an IPv6 "compat" address.
*
* <p>An "IPv4 compatible", or "compat", address is one with 96 leading
* bits of zero, with the remaining 32 bits interpreted as an
* IPv4 address. These are conventionally represented in string
* literals as {@code "::192.168.0.1"}, though {@code "::c0a8:1"} is
* also considered an IPv4 compatible address (and equivalent to
* {@code "::192.168.0.1"}).
*
* <p>For more on IPv4 compatible addresses see section 2.5.5.1 of
* <a target="_parent"
* href="http://tools.ietf.org/html/rfc4291#section-2.5.5.1"
* >http://tools.ietf.org/html/rfc4291</a>
*
* <p>NOTE: This method is different from
* {@link Inet6Address#isIPv4CompatibleAddress} in that it more
* correctly classifies {@code "::"} and {@code "::1"} as
* proper IPv6 addresses (which they are), NOT IPv4 compatible
* addresses (which they are generally NOT considered to be).
*
* @param ip {@link Inet6Address} to be examined for embedded IPv4 compatible address format
* @return {@code true} if the argument is a valid "compat" address
*/
public static boolean isCompatIPv4Address(Inet6Address ip) {
if (!ip.isIPv4CompatibleAddress()) {
return false;
}
byte[] bytes = ip.getAddress();
if ((bytes[12] == 0) && (bytes[13] == 0) && (bytes[14] == 0)
&& ((bytes[15] == 0) || (bytes[15] == 1))) {
return false;
}
return true;
}
/**
* Returns the IPv4 address embedded in an IPv4 compatible address.
*
* @param ip {@link Inet6Address} to be examined for an embedded IPv4 address
* @return {@link Inet4Address} of the embedded IPv4 address
* @throws IllegalArgumentException if the argument is not a valid IPv4 compatible address
*/
public static Inet4Address getCompatIPv4Address(Inet6Address ip) {
Preconditions.checkArgument(isCompatIPv4Address(ip),
"Address '%s' is not IPv4-compatible.", toAddrString(ip));
return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16));
}
/**
* Evaluates whether the argument is a 6to4 address.
*
* <p>6to4 addresses begin with the {@code "2002::/16"} prefix.
* The next 32 bits are the IPv4 address of the host to which
* IPv6-in-IPv4 tunneled packets should be routed.
*
* <p>For more on 6to4 addresses see section 2 of
* <a target="_parent" href="http://tools.ietf.org/html/rfc3056#section-2"
* >http://tools.ietf.org/html/rfc3056</a>
*
* @param ip {@link Inet6Address} to be examined for 6to4 address format
* @return {@code true} if the argument is a 6to4 address
*/
public static boolean is6to4Address(Inet6Address ip) {
byte[] bytes = ip.getAddress();
return (bytes[0] == (byte) 0x20) && (bytes[1] == (byte) 0x02);
}
/**
* Returns the IPv4 address embedded in a 6to4 address.
*
* @param ip {@link Inet6Address} to be examined for embedded IPv4 in 6to4 address
* @return {@link Inet4Address} of embedded IPv4 in 6to4 address
* @throws IllegalArgumentException if the argument is not a valid IPv6 6to4 address
*/
public static Inet4Address get6to4IPv4Address(Inet6Address ip) {
Preconditions.checkArgument(is6to4Address(ip),
"Address '%s' is not a 6to4 address.", toAddrString(ip));
return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 2, 6));
}
/**
* A simple immutable data class to encapsulate the information to be found in a
* Teredo address.
*
* <p>All of the fields in this class are encoded in various portions
* of the IPv6 address as part of the protocol. More protocols details
* can be found at:
* <a target="_parent" href="http://en.wikipedia.org/wiki/Teredo_tunneling"
* >http://en.wikipedia.org/wiki/Teredo_tunneling</a>.
*
* <p>The RFC can be found here:
* <a target="_parent" href="http://tools.ietf.org/html/rfc4380"
* >http://tools.ietf.org/html/rfc4380</a>.
*
* @since 5.0
*/
@Beta
public static final class TeredoInfo {
private final Inet4Address server;
private final Inet4Address client;
private final int port;
private final int flags;
/**
* Constructs a TeredoInfo instance.
*
* <p>Both server and client can be {@code null}, in which case the
* value {@code "0.0.0.0"} will be assumed.
*
* @throws IllegalArgumentException if either of the {@code port} or the {@code flags}
* arguments are out of range of an unsigned short
*/
// TODO: why is this public?
public TeredoInfo(
@Nullable Inet4Address server, @Nullable Inet4Address client, int port, int flags) {
Preconditions.checkArgument((port >= 0) && (port <= 0xffff),
"port '%s' is out of range (0 <= port <= 0xffff)", port);
Preconditions.checkArgument((flags >= 0) && (flags <= 0xffff),
"flags '%s' is out of range (0 <= flags <= 0xffff)", flags);
this.server = Objects.firstNonNull(server, ANY4);
this.client = Objects.firstNonNull(client, ANY4);
this.port = port;
this.flags = flags;
}
public Inet4Address getServer() {
return server;
}
public Inet4Address getClient() {
return client;
}
public int getPort() {
return port;
}
public int getFlags() {
return flags;
}
}
/**
* Evaluates whether the argument is a Teredo address.
*
* <p>Teredo addresses begin with the {@code "2001::/32"} prefix.
*
* @param ip {@link Inet6Address} to be examined for Teredo address format
* @return {@code true} if the argument is a Teredo address
*/
public static boolean isTeredoAddress(Inet6Address ip) {
byte[] bytes = ip.getAddress();
return (bytes[0] == (byte) 0x20) && (bytes[1] == (byte) 0x01)
&& (bytes[2] == 0) && (bytes[3] == 0);
}
/**
* Returns the Teredo information embedded in a Teredo address.
*
* @param ip {@link Inet6Address} to be examined for embedded Teredo information
* @return extracted {@code TeredoInfo}
* @throws IllegalArgumentException if the argument is not a valid IPv6 Teredo address
*/
public static TeredoInfo getTeredoInfo(Inet6Address ip) {
Preconditions.checkArgument(isTeredoAddress(ip),
"Address '%s' is not a Teredo address.", toAddrString(ip));
byte[] bytes = ip.getAddress();
Inet4Address server = getInet4Address(Arrays.copyOfRange(bytes, 4, 8));
int flags = ByteStreams.newDataInput(bytes, 8).readShort() & 0xffff;
// Teredo obfuscates the mapped client port, per section 4 of the RFC.
int port = ~ByteStreams.newDataInput(bytes, 10).readShort() & 0xffff;
byte[] clientBytes = Arrays.copyOfRange(bytes, 12, 16);
for (int i = 0; i < clientBytes.length; i++) {
// Teredo obfuscates the mapped client IP, per section 4 of the RFC.
clientBytes[i] = (byte) ~clientBytes[i];
}
Inet4Address client = getInet4Address(clientBytes);
return new TeredoInfo(server, client, port, flags);
}
/**
* Evaluates whether the argument is an ISATAP address.
*
* <p>From RFC 5214: "ISATAP interface identifiers are constructed in
* Modified EUI-64 format [...] by concatenating the 24-bit IANA OUI
* (00-00-5E), the 8-bit hexadecimal value 0xFE, and a 32-bit IPv4
* address in network byte order [...]"
*
* <p>For more on ISATAP addresses see section 6.1 of
* <a target="_parent" href="http://tools.ietf.org/html/rfc5214#section-6.1"
* >http://tools.ietf.org/html/rfc5214</a>
*
* @param ip {@link Inet6Address} to be examined for ISATAP address format
* @return {@code true} if the argument is an ISATAP address
*/
public static boolean isIsatapAddress(Inet6Address ip) {
// If it's a Teredo address with the right port (41217, or 0xa101)
// which would be encoded as 0x5efe then it can't be an ISATAP address.
if (isTeredoAddress(ip)) {
return false;
}
byte[] bytes = ip.getAddress();
if ((bytes[8] | (byte) 0x03) != (byte) 0x03) {
// Verify that high byte of the 64 bit identifier is zero, modulo
// the U/L and G bits, with which we are not concerned.
return false;
}
return (bytes[9] == (byte) 0x00) && (bytes[10] == (byte) 0x5e)
&& (bytes[11] == (byte) 0xfe);
}
/**
* Returns the IPv4 address embedded in an ISATAP address.
*
* @param ip {@link Inet6Address} to be examined for embedded IPv4 in ISATAP address
* @return {@link Inet4Address} of embedded IPv4 in an ISATAP address
* @throws IllegalArgumentException if the argument is not a valid IPv6 ISATAP address
*/
public static Inet4Address getIsatapIPv4Address(Inet6Address ip) {
Preconditions.checkArgument(isIsatapAddress(ip),
"Address '%s' is not an ISATAP address.", toAddrString(ip));
return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16));
}
/**
* Examines the Inet6Address to determine if it is an IPv6 address of one
* of the specified address types that contain an embedded IPv4 address.
*
* <p>NOTE: ISATAP addresses are explicitly excluded from this method
* due to their trivial spoofability. With other transition addresses
* spoofing involves (at least) infection of one's BGP routing table.
*
* @param ip {@link Inet6Address} to be examined for embedded IPv4 client address
* @return {@code true} if there is an embedded IPv4 client address
* @since 7.0
*/
public static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip) {
return isCompatIPv4Address(ip) || is6to4Address(ip) || isTeredoAddress(ip);
}
/**
* Examines the Inet6Address to extract the embedded IPv4 client address
* if the InetAddress is an IPv6 address of one of the specified address
* types that contain an embedded IPv4 address.
*
* <p>NOTE: ISATAP addresses are explicitly excluded from this method
* due to their trivial spoofability. With other transition addresses
* spoofing involves (at least) infection of one's BGP routing table.
*
* @param ip {@link Inet6Address} to be examined for embedded IPv4 client address
* @return {@link Inet4Address} of embedded IPv4 client address
* @throws IllegalArgumentException if the argument does not have a valid embedded IPv4 address
*/
public static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip) {
if (isCompatIPv4Address(ip)) {
return getCompatIPv4Address(ip);
}
if (is6to4Address(ip)) {
return get6to4IPv4Address(ip);
}
if (isTeredoAddress(ip)) {
return getTeredoInfo(ip).getClient();
}
throw new IllegalArgumentException(
String.format("'%s' has no embedded IPv4 address.", toAddrString(ip)));
}
/**
* Evaluates whether the argument is an "IPv4 mapped" IPv6 address.
*
* <p>An "IPv4 mapped" address is anything in the range ::ffff:0:0/96
* (sometimes written as ::ffff:0.0.0.0/96), with the last 32 bits
* interpreted as an IPv4 address.
*
* <p>For more on IPv4 mapped addresses see section 2.5.5.2 of
* <a target="_parent"
* href="http://tools.ietf.org/html/rfc4291#section-2.5.5.2"
* >http://tools.ietf.org/html/rfc4291</a>
*
* <p>Note: This method takes a {@code String} argument because
* {@link InetAddress} automatically collapses mapped addresses to IPv4.
* (It is actually possible to avoid this using one of the obscure
* {@link Inet6Address} methods, but it would be unwise to depend on such
* a poorly-documented feature.)
*
* @param ipString {@code String} to be examined for embedded IPv4-mapped IPv6 address format
* @return {@code true} if the argument is a valid "mapped" address
* @since 10.0
*/
public static boolean isMappedIPv4Address(String ipString) {
byte[] bytes = ipStringToBytes(ipString);
if (bytes != null && bytes.length == 16) {
for (int i = 0; i < 10; i++) {
if (bytes[i] != 0) {
return false;
}
}
for (int i = 10; i < 12; i++) {
if (bytes[i] != (byte) 0xff) {
return false;
}
}
return true;
}
return false;
}
/**
* Coerces an IPv6 address into an IPv4 address.
*
* <p>HACK: As long as applications continue to use IPv4 addresses for
* indexing into tables, accounting, et cetera, it may be necessary to
* <b>coerce</b> IPv6 addresses into IPv4 addresses. This function does
* so by hashing the upper 64 bits into {@code 224.0.0.0/3}
* (64 bits into 29 bits).
*
* <p>A "coerced" IPv4 address is equivalent to itself.
*
* <p>NOTE: This function is failsafe for security purposes: ALL IPv6
* addresses (except localhost (::1)) are hashed to avoid the security
* risk associated with extracting an embedded IPv4 address that might
* permit elevated privileges.
*
* @param ip {@link InetAddress} to "coerce"
* @return {@link Inet4Address} represented "coerced" address
* @since 7.0
*/
public static Inet4Address getCoercedIPv4Address(InetAddress ip) {
if (ip instanceof Inet4Address) {
return (Inet4Address) ip;
}
// Special cases:
byte[] bytes = ip.getAddress();
boolean leadingBytesOfZero = true;
for (int i = 0; i < 15; ++i) {
if (bytes[i] != 0) {
leadingBytesOfZero = false;
break;
}
}
if (leadingBytesOfZero && (bytes[15] == 1)) {
return LOOPBACK4; // ::1
} else if (leadingBytesOfZero && (bytes[15] == 0)) {
return ANY4; // ::0
}
Inet6Address ip6 = (Inet6Address) ip;
long addressAsLong = 0;
if (hasEmbeddedIPv4ClientAddress(ip6)) {
addressAsLong = getEmbeddedIPv4ClientAddress(ip6).hashCode();
} else {
// Just extract the high 64 bits (assuming the rest is user-modifiable).
addressAsLong = ByteBuffer.wrap(ip6.getAddress(), 0, 8).getLong();
}
// Many strategies for hashing are possible. This might suffice for now.
int coercedHash = Hashing.murmur3_32().hashLong(addressAsLong).asInt();
// Squash into 224/4 Multicast and 240/4 Reserved space (i.e. 224/3).
coercedHash |= 0xe0000000;
// Fixup to avoid some "illegal" values. Currently the only potential
// illegal value is 255.255.255.255.
if (coercedHash == 0xffffffff) {
coercedHash = 0xfffffffe;
}
return getInet4Address(Ints.toByteArray(coercedHash));
}
/**
* Returns an integer representing an IPv4 address regardless of
* whether the supplied argument is an IPv4 address or not.
*
* <p>IPv6 addresses are <b>coerced</b> to IPv4 addresses before being
* converted to integers.
*
* <p>As long as there are applications that assume that all IP addresses
* are IPv4 addresses and can therefore be converted safely to integers
* (for whatever purpose) this function can be used to handle IPv6
* addresses as well until the application is suitably fixed.
*
* <p>NOTE: an IPv6 address coerced to an IPv4 address can only be used
* for such purposes as rudimentary identification or indexing into a
* collection of real {@link InetAddress}es. They cannot be used as
* real addresses for the purposes of network communication.
*
* @param ip {@link InetAddress} to convert
* @return {@code int}, "coerced" if ip is not an IPv4 address
* @since 7.0
*/
public static int coerceToInteger(InetAddress ip) {
return ByteStreams.newDataInput(getCoercedIPv4Address(ip).getAddress()).readInt();
}
/**
* Returns an Inet4Address having the integer value specified by
* the argument.
*
* @param address {@code int}, the 32bit integer address to be converted
* @return {@link Inet4Address} equivalent of the argument
*/
public static Inet4Address fromInteger(int address) {
return getInet4Address(Ints.toByteArray(address));
}
/**
* Returns an address from a <b>little-endian ordered</b> byte array
* (the opposite of what {@link InetAddress#getByAddress} expects).
*
* <p>IPv4 address byte array must be 4 bytes long and IPv6 byte array
* must be 16 bytes long.
*
* @param addr the raw IP address in little-endian byte order
* @return an InetAddress object created from the raw IP address
* @throws UnknownHostException if IP address is of illegal length
*/
public static InetAddress fromLittleEndianByteArray(byte[] addr) throws UnknownHostException {
byte[] reversed = new byte[addr.length];
for (int i = 0; i < addr.length; i++) {
reversed[i] = addr[addr.length - i - 1];
}
return InetAddress.getByAddress(reversed);
}
/**
* Returns a new InetAddress that is one more than the passed in address.
* This method works for both IPv4 and IPv6 addresses.
*
* @param address the InetAddress to increment
* @return a new InetAddress that is one more than the passed in address
* @throws IllegalArgumentException if InetAddress is at the end of its range
* @since 10.0
*/
public static InetAddress increment(InetAddress address) {
byte[] addr = address.getAddress();
int i = addr.length - 1;
while (i >= 0 && addr[i] == (byte) 0xff) {
addr[i] = 0;
i--;
}
Preconditions.checkArgument(i >= 0, "Incrementing %s would wrap.", address);
addr[i]++;
return bytesToInetAddress(addr);
}
/**
* Returns true if the InetAddress is either 255.255.255.255 for IPv4 or
* ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff for IPv6.
*
* @return true if the InetAddress is either 255.255.255.255 for IPv4 or
* ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff for IPv6
* @since 10.0
*/
public static boolean isMaximum(InetAddress address) {
byte[] addr = address.getAddress();
for (int i = 0; i < addr.length; i++) {
if (addr[i] != (byte) 0xff) {
return false;
}
}
return true;
}
}
| Java |
/*
* Copyright (C) 2009 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.net;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import java.net.InetAddress;
import java.text.ParseException;
import javax.annotation.Nullable;
/**
* A syntactically valid host specifier, suitable for use in a URI.
* This may be either a numeric IP address in IPv4 or IPv6 notation, or a
* domain name.
*
* <p>Because this class is intended to represent host specifiers which can
* reasonably be used in a URI, the domain name case is further restricted to
* include only those domain names which end in a recognized public suffix; see
* {@link InternetDomainName#isPublicSuffix()} for details.
*
* <p>Note that no network lookups are performed by any {@code HostSpecifier}
* methods. No attempt is made to verify that a provided specifier corresponds
* to a real or accessible host. Only syntactic and pattern-based checks are
* performed.
*
* <p>If you know that a given string represents a numeric IP address, use
* {@link InetAddresses} to obtain and manipulate a
* {@link java.net.InetAddress} instance from it rather than using this class.
* Similarly, if you know that a given string represents a domain name, use
* {@link InternetDomainName} rather than this class.
*
* @author Craig Berry
* @since 5.0
*/
@Beta
public final class HostSpecifier {
private final String canonicalForm;
private HostSpecifier(String canonicalForm) {
this.canonicalForm = canonicalForm;
}
/**
* Returns a {@code HostSpecifier} built from the provided {@code specifier},
* which is already known to be valid. If the {@code specifier} might be
* invalid, use {@link #from(String)} instead.
*
* <p>The specifier must be in one of these formats:
* <ul>
* <li>A domain name, like {@code google.com}
* <li>A IPv4 address string, like {@code 127.0.0.1}
* <li>An IPv6 address string with or without brackets, like
* {@code [2001:db8::1]} or {@code 2001:db8::1}
* </ul>
*
* @throws IllegalArgumentException if the specifier is not valid.
*/
public static HostSpecifier fromValid(String specifier) {
// Verify that no port was specified, and strip optional brackets from
// IPv6 literals.
final HostAndPort parsedHost = HostAndPort.fromString(specifier);
Preconditions.checkArgument(!parsedHost.hasPort());
final String host = parsedHost.getHostText();
// Try to interpret the specifier as an IP address. Note we build
// the address rather than using the .is* methods because we want to
// use InetAddresses.toUriString to convert the result to a string in
// canonical form.
InetAddress addr = null;
try {
addr = InetAddresses.forString(host);
} catch (IllegalArgumentException e) {
// It is not an IPv4 or IPv6 literal
}
if (addr != null) {
return new HostSpecifier(InetAddresses.toUriString(addr));
}
// It is not any kind of IP address; must be a domain name or invalid.
// TODO(user): different versions of this for different factories?
final InternetDomainName domain = InternetDomainName.from(host);
if (domain.hasPublicSuffix()) {
return new HostSpecifier(domain.name());
}
throw new IllegalArgumentException(
"Domain name does not have a recognized public suffix: " + host);
}
/**
* Attempts to return a {@code HostSpecifier} for the given string, throwing
* an exception if parsing fails. Always use this method in preference to
* {@link #fromValid(String)} for a specifier that is not already known to be
* valid.
*
* @throws ParseException if the specifier is not valid.
*/
public static HostSpecifier from(String specifier)
throws ParseException {
try {
return fromValid(specifier);
} catch (IllegalArgumentException e) {
// Since the IAE can originate at several different points inside
// fromValid(), we implement this method in terms of that one rather
// than the reverse.
ParseException parseException =
new ParseException("Invalid host specifier: " + specifier, 0);
parseException.initCause(e);
throw parseException;
}
}
/**
* Determines whether {@code specifier} represents a valid
* {@link HostSpecifier} as described in the documentation for
* {@link #fromValid(String)}.
*/
public static boolean isValid(String specifier) {
try {
fromValid(specifier);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
@Override
public boolean equals(@Nullable Object other) {
if (this == other) {
return true;
}
if (other instanceof HostSpecifier) {
final HostSpecifier that = (HostSpecifier) other;
return this.canonicalForm.equals(that.canonicalForm);
}
return false;
}
@Override
public int hashCode() {
return canonicalForm.hashCode();
}
/**
* Returns a string representation of the host specifier suitable for
* inclusion in a URI. If the host specifier is a domain name, the
* string will be normalized to all lower case. If the specifier was
* an IPv6 address without brackets, brackets are added so that the
* result will be usable in the host part of a URI.
*/
@Override
public String toString() {
return canonicalForm;
}
}
| Java |
/*
* Copyright (C) 2010 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.
*/
/**
* This package contains utility methods and classes for working with net
* addresses (numeric IP and domain names).
*
* <p>This package is a part of the open-source
* <a href="http://guava-libraries.googlecode.com">Guava libraries</a>.
*
* @author Craig Berry
*/
@ParametersAreNonnullByDefault
package com.google.common.net;
import javax.annotation.ParametersAreNonnullByDefault;
| Java |
/*
* Copyright (C) 2011 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.net;
import static com.google.common.base.CharMatcher.ASCII;
import static com.google.common.base.CharMatcher.JAVA_ISO_CONTROL;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Ascii;
import com.google.common.base.CharMatcher;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Joiner.MapJoiner;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
/**
* Represents an <a href="http://en.wikipedia.org/wiki/Internet_media_type">Internet Media Type</a>
* (also known as a MIME Type or Content Type). This class also supports the concept of media ranges
* <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1">defined by HTTP/1.1</a>.
* As such, the {@code *} character is treated as a wildcard and is used to represent any acceptable
* type or subtype value. A media type may not have wildcard type with a declared subtype. The
* {@code *} character has no special meaning as part of a parameter. All values for type, subtype,
* parameter attributes or parameter values must be valid according to RFCs
* <a href="http://www.ietf.org/rfc/rfc2045.txt">2045</a> and
* <a href="http://www.ietf.org/rfc/rfc2046.txt">2046</a>.
*
* <p>All portions of the media type that are case-insensitive (type, subtype, parameter attributes)
* are normalized to lowercase. The value of the {@code charset} parameter is normalized to
* lowercase, but all others are left as-is.
*
* <p>Note that this specifically does <strong>not</strong> represent the value of the MIME
* {@code Content-Type} header and as such has no support for header-specific considerations such as
* line folding and comments.
*
* <p>For media types that take a charset the predefined constants default to UTF-8 and have a
* "_UTF_8" suffix. To get a version without a character set, use {@link #withoutParameters}.
*
* @since 12.0
*
* @author Gregory Kick
*/
@Beta
@GwtCompatible
@Immutable
public final class MediaType {
private static final String CHARSET_ATTRIBUTE = "charset";
private static final ImmutableListMultimap<String, String> UTF_8_CONSTANT_PARAMETERS =
ImmutableListMultimap.of(CHARSET_ATTRIBUTE, Ascii.toLowerCase(UTF_8.name()));
/** Matcher for type, subtype and attributes. */
private static final CharMatcher TOKEN_MATCHER = ASCII.and(JAVA_ISO_CONTROL.negate())
.and(CharMatcher.isNot(' '))
.and(CharMatcher.noneOf("()<>@,;:\\\"/[]?="));
private static final CharMatcher QUOTED_TEXT_MATCHER = ASCII
.and(CharMatcher.noneOf("\"\\\r"));
/*
* This matches the same characters as linear-white-space from RFC 822, but we make no effort to
* enforce any particular rules with regards to line folding as stated in the class docs.
*/
private static final CharMatcher LINEAR_WHITE_SPACE = CharMatcher.anyOf(" \t\r\n");
// TODO(gak): make these public?
private static final String APPLICATION_TYPE = "application";
private static final String AUDIO_TYPE = "audio";
private static final String IMAGE_TYPE = "image";
private static final String TEXT_TYPE = "text";
private static final String VIDEO_TYPE = "video";
private static final String WILDCARD = "*";
private static final Map<MediaType, MediaType> KNOWN_TYPES = Maps.newHashMap();
private static MediaType createConstant(String type, String subtype) {
return addKnownType(new MediaType(type, subtype, ImmutableListMultimap.<String, String>of()));
}
private static MediaType createConstantUtf8(String type, String subtype) {
return addKnownType(new MediaType(type, subtype, UTF_8_CONSTANT_PARAMETERS));
}
private static MediaType addKnownType(MediaType mediaType) {
KNOWN_TYPES.put(mediaType, mediaType);
return mediaType;
}
/*
* The following constants are grouped by their type and ordered alphabetically by the constant
* name within that type. The constant name should be a sensible identifier that is closest to the
* "common name" of the media. This is often, but not necessarily the same as the subtype.
*
* Be sure to declare all constants with the type and subtype in all lowercase. For types that
* take a charset (e.g. all text/* types), default to UTF-8 and suffix the constant name with
* "_UTF_8".
*/
public static final MediaType ANY_TYPE = createConstant(WILDCARD, WILDCARD);
public static final MediaType ANY_TEXT_TYPE = createConstant(TEXT_TYPE, WILDCARD);
public static final MediaType ANY_IMAGE_TYPE = createConstant(IMAGE_TYPE, WILDCARD);
public static final MediaType ANY_AUDIO_TYPE = createConstant(AUDIO_TYPE, WILDCARD);
public static final MediaType ANY_VIDEO_TYPE = createConstant(VIDEO_TYPE, WILDCARD);
public static final MediaType ANY_APPLICATION_TYPE = createConstant(APPLICATION_TYPE, WILDCARD);
/* text types */
public static final MediaType CACHE_MANIFEST_UTF_8 =
createConstantUtf8(TEXT_TYPE, "cache-manifest");
public static final MediaType CSS_UTF_8 = createConstantUtf8(TEXT_TYPE, "css");
public static final MediaType CSV_UTF_8 = createConstantUtf8(TEXT_TYPE, "csv");
public static final MediaType HTML_UTF_8 = createConstantUtf8(TEXT_TYPE, "html");
public static final MediaType I_CALENDAR_UTF_8 = createConstantUtf8(TEXT_TYPE, "calendar");
public static final MediaType PLAIN_TEXT_UTF_8 = createConstantUtf8(TEXT_TYPE, "plain");
/**
* <a href="http://www.rfc-editor.org/rfc/rfc4329.txt">RFC 4329</a> declares
* {@link #JAVASCRIPT_UTF_8 application/javascript} to be the correct media type for JavaScript,
* but this may be necessary in certain situations for compatibility.
*/
public static final MediaType TEXT_JAVASCRIPT_UTF_8 = createConstantUtf8(TEXT_TYPE, "javascript");
public static final MediaType VCARD_UTF_8 = createConstantUtf8(TEXT_TYPE, "vcard");
public static final MediaType WML_UTF_8 = createConstantUtf8(TEXT_TYPE, "vnd.wap.wml");
/**
* As described in <a href="http://www.ietf.org/rfc/rfc3023.txt">RFC 3023</a>, this constant
* ({@code text/xml}) is used for XML documents that are "readable by casual users."
* {@link #APPLICATION_XML_UTF_8} is provided for documents that are intended for applications.
*/
public static final MediaType XML_UTF_8 = createConstantUtf8(TEXT_TYPE, "xml");
/* image types */
public static final MediaType BMP = createConstant(IMAGE_TYPE, "bmp");
/**
* The media type for the <a href="http://en.wikipedia.org/wiki/Camera_Image_File_Format">Canon
* Image File Format</a> ({@code crw} files), a widely-used "raw image" format for cameras. It is
* found in {@code /etc/mime.types}, e.g. in <href=
* "http://anonscm.debian.org/gitweb/?p=collab-maint/mime-support.git;a=blob;f=mime.types;hb=HEAD"
* >Debian 3.48-1</a>.
*
* @since 15.0
*/
public static final MediaType CRW = createConstant(IMAGE_TYPE, "x-canon-crw");
public static final MediaType GIF = createConstant(IMAGE_TYPE, "gif");
public static final MediaType ICO = createConstant(IMAGE_TYPE, "vnd.microsoft.icon");
public static final MediaType JPEG = createConstant(IMAGE_TYPE, "jpeg");
public static final MediaType PNG = createConstant(IMAGE_TYPE, "png");
/**
* The media type for the Photoshop File Format ({@code psd} files) as defined by <a href=
* "http://www.iana.org/assignments/media-types/image/vnd.adobe.photoshop">IANA</a>, and found in
* {@code /etc/mime.types}, e.g. <a href=
* "http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types"></a> of the Apache
* <a href="http://httpd.apache.org/">HTTPD project</a>; for the specification, see
* <href="http://www.adobe.com/devnet-apps/photoshop/fileformatashtml/PhotoshopFileFormats.htm">
* Adobe Photoshop Document Format</a> and <a href=
* "http://en.wikipedia.org/wiki/Adobe_Photoshop#File_format">Wikipedia</a>; this is the regular
* output/input of Photoshop (which can also export to various image formats; note that files with
* extension "PSB" are in a distinct but related format).
* <p>This is a more recent replacement for the older, experimental type
* {@code x-photoshop}: <a href="http://tools.ietf.org/html/rfc2046#section-6">RFC-2046.6</a>.
*
* @since 15.0
*/
public static final MediaType PSD = createConstant(IMAGE_TYPE, "vnd.adobe.photoshop");
public static final MediaType SVG_UTF_8 = createConstantUtf8(IMAGE_TYPE, "svg+xml");
public static final MediaType TIFF = createConstant(IMAGE_TYPE, "tiff");
public static final MediaType WEBP = createConstant(IMAGE_TYPE, "webp");
/* audio types */
public static final MediaType MP4_AUDIO = createConstant(AUDIO_TYPE, "mp4");
public static final MediaType MPEG_AUDIO = createConstant(AUDIO_TYPE, "mpeg");
public static final MediaType OGG_AUDIO = createConstant(AUDIO_TYPE, "ogg");
public static final MediaType WEBM_AUDIO = createConstant(AUDIO_TYPE, "webm");
/* video types */
public static final MediaType MP4_VIDEO = createConstant(VIDEO_TYPE, "mp4");
public static final MediaType MPEG_VIDEO = createConstant(VIDEO_TYPE, "mpeg");
public static final MediaType OGG_VIDEO = createConstant(VIDEO_TYPE, "ogg");
public static final MediaType QUICKTIME = createConstant(VIDEO_TYPE, "quicktime");
public static final MediaType WEBM_VIDEO = createConstant(VIDEO_TYPE, "webm");
public static final MediaType WMV = createConstant(VIDEO_TYPE, "x-ms-wmv");
/* application types */
/**
* As described in <a href="http://www.ietf.org/rfc/rfc3023.txt">RFC 3023</a>, this constant
* ({@code application/xml}) is used for XML documents that are "unreadable by casual users."
* {@link #XML_UTF_8} is provided for documents that may be read by users.
*/
public static final MediaType APPLICATION_XML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "xml");
public static final MediaType ATOM_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "atom+xml");
public static final MediaType BZIP2 = createConstant(APPLICATION_TYPE, "x-bzip2");
/**
* As described in the <a href="http://idpf.org/epub">International Digital Publishing Forum</a>
* EPUB is the distribution and interchange format standard for digital publications and
* documents. This media type is defined in the
* <a href="http://www.idpf.org/epub/30/spec/epub30-ocf.html">EPUB Open Container Format</a>
* specification.
*
* @since 15.0
*/
public static final MediaType EPUB = createConstant(APPLICATION_TYPE, "epub+zip");
public static final MediaType FORM_DATA = createConstant(APPLICATION_TYPE,
"x-www-form-urlencoded");
/**
* As described in <a href="https://www.rsa.com/rsalabs/node.asp?id=2138">PKCS #12: Personal
* Information Exchange Syntax Standard</a>, PKCS #12 defines an archive file format for storing
* many cryptography objects as a single file.
*
* @since 15.0
*/
public static final MediaType KEY_ARCHIVE = createConstant(APPLICATION_TYPE, "pkcs12");
/**
* This is a non-standard media type, but is commonly used in serving hosted binary files as it is
* <a href="http://code.google.com/p/browsersec/wiki/Part2#Survey_of_content_sniffing_behaviors">
* known not to trigger content sniffing in current browsers</a>. It <i>should not</i> be used in
* other situations as it is not specified by any RFC and does not appear in the <a href=
* "http://www.iana.org/assignments/media-types">/IANA MIME Media Types</a> list. Consider
* {@link #OCTET_STREAM} for binary data that is not being served to a browser.
*
*
* @since 14.0
*/
public static final MediaType APPLICATION_BINARY = createConstant(APPLICATION_TYPE, "binary");
public static final MediaType GZIP = createConstant(APPLICATION_TYPE, "x-gzip");
/**
* <a href="http://www.rfc-editor.org/rfc/rfc4329.txt">RFC 4329</a> declares this to be the
* correct media type for JavaScript, but {@link #TEXT_JAVASCRIPT_UTF_8 text/javascript} may be
* necessary in certain situations for compatibility.
*/
public static final MediaType JAVASCRIPT_UTF_8 =
createConstantUtf8(APPLICATION_TYPE, "javascript");
public static final MediaType JSON_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "json");
public static final MediaType KML = createConstant(APPLICATION_TYPE, "vnd.google-earth.kml+xml");
public static final MediaType KMZ = createConstant(APPLICATION_TYPE, "vnd.google-earth.kmz");
public static final MediaType MBOX = createConstant(APPLICATION_TYPE, "mbox");
public static final MediaType MICROSOFT_EXCEL = createConstant(APPLICATION_TYPE, "vnd.ms-excel");
public static final MediaType MICROSOFT_POWERPOINT =
createConstant(APPLICATION_TYPE, "vnd.ms-powerpoint");
public static final MediaType MICROSOFT_WORD = createConstant(APPLICATION_TYPE, "msword");
public static final MediaType OCTET_STREAM = createConstant(APPLICATION_TYPE, "octet-stream");
public static final MediaType OGG_CONTAINER = createConstant(APPLICATION_TYPE, "ogg");
public static final MediaType OOXML_DOCUMENT = createConstant(APPLICATION_TYPE,
"vnd.openxmlformats-officedocument.wordprocessingml.document");
public static final MediaType OOXML_PRESENTATION = createConstant(APPLICATION_TYPE,
"vnd.openxmlformats-officedocument.presentationml.presentation");
public static final MediaType OOXML_SHEET =
createConstant(APPLICATION_TYPE, "vnd.openxmlformats-officedocument.spreadsheetml.sheet");
public static final MediaType OPENDOCUMENT_GRAPHICS =
createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.graphics");
public static final MediaType OPENDOCUMENT_PRESENTATION =
createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.presentation");
public static final MediaType OPENDOCUMENT_SPREADSHEET =
createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.spreadsheet");
public static final MediaType OPENDOCUMENT_TEXT =
createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.text");
public static final MediaType PDF = createConstant(APPLICATION_TYPE, "pdf");
public static final MediaType POSTSCRIPT = createConstant(APPLICATION_TYPE, "postscript");
/**
* <a href="http://tools.ietf.org/html/draft-rfernando-protocol-buffers-00">Protocol buffers</a>
*
* @since 15.0
*/
public static final MediaType PROTOBUF = createConstant(APPLICATION_TYPE, "protobuf");
public static final MediaType RDF_XML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "rdf+xml");
public static final MediaType RTF_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "rtf");
public static final MediaType SHOCKWAVE_FLASH = createConstant(APPLICATION_TYPE,
"x-shockwave-flash");
public static final MediaType SKETCHUP = createConstant(APPLICATION_TYPE, "vnd.sketchup.skp");
public static final MediaType TAR = createConstant(APPLICATION_TYPE, "x-tar");
public static final MediaType XHTML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "xhtml+xml");
/**
* Media type for Extensible Resource Descriptors. This is not yet registered with the IANA, but
* it is specified by OASIS in the
* <a href="http://docs.oasis-open.org/xri/xrd/v1.0/cd02/xrd-1.0-cd02.html"> XRD definition</a>
* and implemented in projects such as
* <a href="http://code.google.com/p/webfinger/">WebFinger</a>.
*/
public static final MediaType XRD_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "xrd+xml");
public static final MediaType ZIP = createConstant(APPLICATION_TYPE, "zip");
private final String type;
private final String subtype;
private final ImmutableListMultimap<String, String> parameters;
private MediaType(String type, String subtype,
ImmutableListMultimap<String, String> parameters) {
this.type = type;
this.subtype = subtype;
this.parameters = parameters;
}
/** Returns the top-level media type. For example, {@code "text"} in {@code "text/plain"}. */
public String type() {
return type;
}
/** Returns the media subtype. For example, {@code "plain"} in {@code "text/plain"}. */
public String subtype() {
return subtype;
}
/** Returns a multimap containing the parameters of this media type. */
public ImmutableListMultimap<String, String> parameters() {
return parameters;
}
private Map<String, ImmutableMultiset<String>> parametersAsMap() {
return Maps.transformValues(parameters.asMap(),
new Function<Collection<String>, ImmutableMultiset<String>>() {
@Override public ImmutableMultiset<String> apply(Collection<String> input) {
return ImmutableMultiset.copyOf(input);
}
});
}
/**
* Returns an optional charset for the value of the charset parameter if it is specified.
*
* @throws IllegalStateException if multiple charset values have been set for this media type
* @throws IllegalCharsetNameException if a charset value is present, but illegal
* @throws UnsupportedCharsetException if a charset value is present, but no support is available
* in this instance of the Java virtual machine
*/
public Optional<Charset> charset() {
ImmutableSet<String> charsetValues = ImmutableSet.copyOf(parameters.get(CHARSET_ATTRIBUTE));
switch (charsetValues.size()) {
case 0:
return Optional.absent();
case 1:
return Optional.of(Charset.forName(Iterables.getOnlyElement(charsetValues)));
default:
throw new IllegalStateException("Multiple charset values defined: " + charsetValues);
}
}
/**
* Returns a new instance with the same type and subtype as this instance, but without any
* parameters.
*/
public MediaType withoutParameters() {
return parameters.isEmpty() ? this : create(type, subtype);
}
/**
* <em>Replaces</em> all parameters with the given parameters.
*
* @throws IllegalArgumentException if any parameter or value is invalid
*/
public MediaType withParameters(Multimap<String, String> parameters) {
return create(type, subtype, parameters);
}
/**
* <em>Replaces</em> all parameters with the given attribute with a single parameter with the
* given value. If multiple parameters with the same attributes are necessary use
* {@link #withParameters}. Prefer {@link #withCharset} for setting the {@code charset} parameter
* when using a {@link Charset} object.
*
* @throws IllegalArgumentException if either {@code attribute} or {@code value} is invalid
*/
public MediaType withParameter(String attribute, String value) {
checkNotNull(attribute);
checkNotNull(value);
String normalizedAttribute = normalizeToken(attribute);
ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
for (Entry<String, String> entry : parameters.entries()) {
String key = entry.getKey();
if (!normalizedAttribute.equals(key)) {
builder.put(key, entry.getValue());
}
}
builder.put(normalizedAttribute, normalizeParameterValue(normalizedAttribute, value));
MediaType mediaType = new MediaType(type, subtype, builder.build());
// Return one of the constants if the media type is a known type.
return Objects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
}
/**
* Returns a new instance with the same type and subtype as this instance, with the
* {@code charset} parameter set to the {@link Charset#name name} of the given charset. Only one
* {@code charset} parameter will be present on the new instance regardless of the number set on
* this one.
*
* <p>If a charset must be specified that is not supported on this JVM (and thus is not
* representable as a {@link Charset} instance, use {@link #withParameter}.
*/
public MediaType withCharset(Charset charset) {
checkNotNull(charset);
return withParameter(CHARSET_ATTRIBUTE, charset.name());
}
/** Returns true if either the type or subtype is the wildcard. */
public boolean hasWildcard() {
return WILDCARD.equals(type) || WILDCARD.equals(subtype);
}
/**
* Returns {@code true} if this instance falls within the range (as defined by
* <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">the HTTP Accept header</a>)
* given by the argument according to three criteria:
*
* <ol>
* <li>The type of the argument is the wildcard or equal to the type of this instance.
* <li>The subtype of the argument is the wildcard or equal to the subtype of this instance.
* <li>All of the parameters present in the argument are present in this instance.
* </ol>
*
* <p>For example: <pre> {@code
* PLAIN_TEXT_UTF_8.is(PLAIN_TEXT_UTF_8) // true
* PLAIN_TEXT_UTF_8.is(HTML_UTF_8) // false
* PLAIN_TEXT_UTF_8.is(ANY_TYPE) // true
* PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE) // true
* PLAIN_TEXT_UTF_8.is(ANY_IMAGE_TYPE) // false
* PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE.withCharset(UTF_8)) // true
* PLAIN_TEXT_UTF_8.withoutParameters().is(ANY_TEXT_TYPE.withCharset(UTF_8)) // false
* PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE.withCharset(UTF_16)) // false}</pre>
*
* <p>Note that while it is possible to have the same parameter declared multiple times within a
* media type this method does not consider the number of occurrences of a parameter. For
* example, {@code "text/plain; charset=UTF-8"} satisfies
* {@code "text/plain; charset=UTF-8; charset=UTF-8"}.
*/
public boolean is(MediaType mediaTypeRange) {
return (mediaTypeRange.type.equals(WILDCARD) || mediaTypeRange.type.equals(this.type))
&& (mediaTypeRange.subtype.equals(WILDCARD) || mediaTypeRange.subtype.equals(this.subtype))
&& this.parameters.entries().containsAll(mediaTypeRange.parameters.entries());
}
/**
* Creates a new media type with the given type and subtype.
*
* @throws IllegalArgumentException if type or subtype is invalid or if a wildcard is used for the
* type, but not the subtype.
*/
public static MediaType create(String type, String subtype) {
return create(type, subtype, ImmutableListMultimap.<String, String>of());
}
/**
* Creates a media type with the "application" type and the given subtype.
*
* @throws IllegalArgumentException if subtype is invalid
*/
static MediaType createApplicationType(String subtype) {
return create(APPLICATION_TYPE, subtype);
}
/**
* Creates a media type with the "audio" type and the given subtype.
*
* @throws IllegalArgumentException if subtype is invalid
*/
static MediaType createAudioType(String subtype) {
return create(AUDIO_TYPE, subtype);
}
/**
* Creates a media type with the "image" type and the given subtype.
*
* @throws IllegalArgumentException if subtype is invalid
*/
static MediaType createImageType(String subtype) {
return create(IMAGE_TYPE, subtype);
}
/**
* Creates a media type with the "text" type and the given subtype.
*
* @throws IllegalArgumentException if subtype is invalid
*/
static MediaType createTextType(String subtype) {
return create(TEXT_TYPE, subtype);
}
/**
* Creates a media type with the "video" type and the given subtype.
*
* @throws IllegalArgumentException if subtype is invalid
*/
static MediaType createVideoType(String subtype) {
return create(VIDEO_TYPE, subtype);
}
private static MediaType create(String type, String subtype,
Multimap<String, String> parameters) {
checkNotNull(type);
checkNotNull(subtype);
checkNotNull(parameters);
String normalizedType = normalizeToken(type);
String normalizedSubtype = normalizeToken(subtype);
checkArgument(!WILDCARD.equals(normalizedType) || WILDCARD.equals(normalizedSubtype),
"A wildcard type cannot be used with a non-wildcard subtype");
ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
for (Entry<String, String> entry : parameters.entries()) {
String attribute = normalizeToken(entry.getKey());
builder.put(attribute, normalizeParameterValue(attribute, entry.getValue()));
}
MediaType mediaType = new MediaType(normalizedType, normalizedSubtype, builder.build());
// Return one of the constants if the media type is a known type.
return Objects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
}
private static String normalizeToken(String token) {
checkArgument(TOKEN_MATCHER.matchesAllOf(token));
return Ascii.toLowerCase(token);
}
private static String normalizeParameterValue(String attribute, String value) {
return CHARSET_ATTRIBUTE.equals(attribute) ? Ascii.toLowerCase(value) : value;
}
/**
* Parses a media type from its string representation.
*
* @throws IllegalArgumentException if the input is not parsable
*/
public static MediaType parse(String input) {
checkNotNull(input);
Tokenizer tokenizer = new Tokenizer(input);
try {
String type = tokenizer.consumeToken(TOKEN_MATCHER);
tokenizer.consumeCharacter('/');
String subtype = tokenizer.consumeToken(TOKEN_MATCHER);
ImmutableListMultimap.Builder<String, String> parameters = ImmutableListMultimap.builder();
while (tokenizer.hasMore()) {
tokenizer.consumeCharacter(';');
tokenizer.consumeTokenIfPresent(LINEAR_WHITE_SPACE);
String attribute = tokenizer.consumeToken(TOKEN_MATCHER);
tokenizer.consumeCharacter('=');
final String value;
if ('"' == tokenizer.previewChar()) {
tokenizer.consumeCharacter('"');
StringBuilder valueBuilder = new StringBuilder();
while ('"' != tokenizer.previewChar()) {
if ('\\' == tokenizer.previewChar()) {
tokenizer.consumeCharacter('\\');
valueBuilder.append(tokenizer.consumeCharacter(ASCII));
} else {
valueBuilder.append(tokenizer.consumeToken(QUOTED_TEXT_MATCHER));
}
}
value = valueBuilder.toString();
tokenizer.consumeCharacter('"');
} else {
value = tokenizer.consumeToken(TOKEN_MATCHER);
}
parameters.put(attribute, value);
}
return create(type, subtype, parameters.build());
} catch (IllegalStateException e) {
throw new IllegalArgumentException(e);
}
}
private static final class Tokenizer {
final String input;
int position = 0;
Tokenizer(String input) {
this.input = input;
}
String consumeTokenIfPresent(CharMatcher matcher) {
checkState(hasMore());
int startPosition = position;
position = matcher.negate().indexIn(input, startPosition);
return hasMore() ? input.substring(startPosition, position) : input.substring(startPosition);
}
String consumeToken(CharMatcher matcher) {
int startPosition = position;
String token = consumeTokenIfPresent(matcher);
checkState(position != startPosition);
return token;
}
char consumeCharacter(CharMatcher matcher) {
checkState(hasMore());
char c = previewChar();
checkState(matcher.matches(c));
position++;
return c;
}
char consumeCharacter(char c) {
checkState(hasMore());
checkState(previewChar() == c);
position++;
return c;
}
char previewChar() {
checkState(hasMore());
return input.charAt(position);
}
boolean hasMore() {
return (position >= 0) && (position < input.length());
}
}
@Override public boolean equals(@Nullable Object obj) {
if (obj == this) {
return true;
} else if (obj instanceof MediaType) {
MediaType that = (MediaType) obj;
return this.type.equals(that.type)
&& this.subtype.equals(that.subtype)
// compare parameters regardless of order
&& this.parametersAsMap().equals(that.parametersAsMap());
} else {
return false;
}
}
@Override public int hashCode() {
return Objects.hashCode(type, subtype, parametersAsMap());
}
private static final MapJoiner PARAMETER_JOINER = Joiner.on("; ").withKeyValueSeparator("=");
/**
* Returns the string representation of this media type in the format described in <a
* href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>.
*/
@Override public String toString() {
StringBuilder builder = new StringBuilder().append(type).append('/').append(subtype);
if (!parameters.isEmpty()) {
builder.append("; ");
Multimap<String, String> quotedParameters = Multimaps.transformValues(parameters,
new Function<String, String>() {
@Override public String apply(String value) {
return TOKEN_MATCHER.matchesAllOf(value) ? value : escapeAndQuote(value);
}
});
PARAMETER_JOINER.appendTo(builder, quotedParameters.entries());
}
return builder.toString();
}
private static String escapeAndQuote(String value) {
StringBuilder escaped = new StringBuilder(value.length() + 16).append('"');
for (char ch : value.toCharArray()) {
if (ch == '\r' || ch == '\\' || ch == '"') {
escaped.append('\\');
}
escaped.append(ch);
}
return escaped.append('"').toString();
}
}
| Java |
/*
* Copyright (C) 2011 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.net;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
/**
* Contains constant definitions for the HTTP header field names. See:
* <ul>
* <li><a href="http://www.ietf.org/rfc/rfc2109.txt">RFC 2109</a>
* <li><a href="http://www.ietf.org/rfc/rfc2183.txt">RFC 2183</a>
* <li><a href="http://www.ietf.org/rfc/rfc2616.txt">RFC 2616</a>
* <li><a href="http://www.ietf.org/rfc/rfc2965.txt">RFC 2965</a>
* <li><a href="http://www.ietf.org/rfc/rfc5988.txt">RFC 5988</a>
* </ul>
*
* @author Kurt Alfred Kluever
* @since 11.0
*/
@GwtCompatible
public final class HttpHeaders {
private HttpHeaders() {}
// HTTP Request and Response header fields
/** The HTTP {@code Cache-Control} header field name. */
public static final String CACHE_CONTROL = "Cache-Control";
/** The HTTP {@code Content-Length} header field name. */
public static final String CONTENT_LENGTH = "Content-Length";
/** The HTTP {@code Content-Type} header field name. */
public static final String CONTENT_TYPE = "Content-Type";
/** The HTTP {@code Date} header field name. */
public static final String DATE = "Date";
/** The HTTP {@code Pragma} header field name. */
public static final String PRAGMA = "Pragma";
/** The HTTP {@code Via} header field name. */
public static final String VIA = "Via";
/** The HTTP {@code Warning} header field name. */
public static final String WARNING = "Warning";
// HTTP Request header fields
/** The HTTP {@code Accept} header field name. */
public static final String ACCEPT = "Accept";
/** The HTTP {@code Accept-Charset} header field name. */
public static final String ACCEPT_CHARSET = "Accept-Charset";
/** The HTTP {@code Accept-Encoding} header field name. */
public static final String ACCEPT_ENCODING = "Accept-Encoding";
/** The HTTP {@code Accept-Language} header field name. */
public static final String ACCEPT_LANGUAGE = "Accept-Language";
/** The HTTP {@code Access-Control-Request-Headers} header field name. */
public static final String ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers";
/** The HTTP {@code Access-Control-Request-Method} header field name. */
public static final String ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method";
/** The HTTP {@code Authorization} header field name. */
public static final String AUTHORIZATION = "Authorization";
/** The HTTP {@code Connection} header field name. */
public static final String CONNECTION = "Connection";
/** The HTTP {@code Cookie} header field name. */
public static final String COOKIE = "Cookie";
/** The HTTP {@code Expect} header field name. */
public static final String EXPECT = "Expect";
/** The HTTP {@code From} header field name. */
public static final String FROM = "From";
/** The HTTP {@code Host} header field name. */
public static final String HOST = "Host";
/** The HTTP {@code If-Match} header field name. */
public static final String IF_MATCH = "If-Match";
/** The HTTP {@code If-Modified-Since} header field name. */
public static final String IF_MODIFIED_SINCE = "If-Modified-Since";
/** The HTTP {@code If-None-Match} header field name. */
public static final String IF_NONE_MATCH = "If-None-Match";
/** The HTTP {@code If-Range} header field name. */
public static final String IF_RANGE = "If-Range";
/** The HTTP {@code If-Unmodified-Since} header field name. */
public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since";
/** The HTTP {@code Last-Event-ID} header field name. */
public static final String LAST_EVENT_ID = "Last-Event-ID";
/** The HTTP {@code Max-Forwards} header field name. */
public static final String MAX_FORWARDS = "Max-Forwards";
/** The HTTP {@code Origin} header field name. */
public static final String ORIGIN = "Origin";
/** The HTTP {@code Proxy-Authorization} header field name. */
public static final String PROXY_AUTHORIZATION = "Proxy-Authorization";
/** The HTTP {@code Range} header field name. */
public static final String RANGE = "Range";
/** The HTTP {@code Referer} header field name. */
public static final String REFERER = "Referer";
/** The HTTP {@code TE} header field name. */
public static final String TE = "TE";
/** The HTTP {@code Upgrade} header field name. */
public static final String UPGRADE = "Upgrade";
/** The HTTP {@code User-Agent} header field name. */
public static final String USER_AGENT = "User-Agent";
// HTTP Response header fields
/** The HTTP {@code Accept-Ranges} header field name. */
public static final String ACCEPT_RANGES = "Accept-Ranges";
/** The HTTP {@code Access-Control-Allow-Headers} header field name. */
public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
/** The HTTP {@code Access-Control-Allow-Methods} header field name. */
public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
/** The HTTP {@code Access-Control-Allow-Origin} header field name. */
public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
/** The HTTP {@code Access-Control-Allow-Credentials} header field name. */
public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
/** The HTTP {@code Access-Control-Expose-Headers} header field name. */
public static final String ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers";
/** The HTTP {@code Access-Control-Max-Age} header field name. */
public static final String ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age";
/** The HTTP {@code Age} header field name. */
public static final String AGE = "Age";
/** The HTTP {@code Allow} header field name. */
public static final String ALLOW = "Allow";
/** The HTTP {@code Content-Disposition} header field name. */
public static final String CONTENT_DISPOSITION = "Content-Disposition";
/** The HTTP {@code Content-Encoding} header field name. */
public static final String CONTENT_ENCODING = "Content-Encoding";
/** The HTTP {@code Content-Language} header field name. */
public static final String CONTENT_LANGUAGE = "Content-Language";
/** The HTTP {@code Content-Location} header field name. */
public static final String CONTENT_LOCATION = "Content-Location";
/** The HTTP {@code Content-MD5} header field name. */
public static final String CONTENT_MD5 = "Content-MD5";
/** The HTTP {@code Content-Range} header field name. */
public static final String CONTENT_RANGE = "Content-Range";
/**
* The HTTP <a href="http://w3.org/TR/CSP/#content-security-policy-header-field">
* {@code Content-Security-Policy}</a> header field name.
*
* @since 15.0
*/
public static final String CONTENT_SECURITY_POLICY = "Content-Security-Policy";
/**
* The HTTP <a href="http://w3.org/TR/CSP/#content-security-policy-report-only-header-field">
* {@code Content-Security-Policy-Report-Only}</a> header field name.
*
* @since 15.0
*/
public static final String CONTENT_SECURITY_POLICY_REPORT_ONLY =
"Content-Security-Policy-Report-Only";
/** The HTTP {@code ETag} header field name. */
public static final String ETAG = "ETag";
/** The HTTP {@code Expires} header field name. */
public static final String EXPIRES = "Expires";
/** The HTTP {@code Last-Modified} header field name. */
public static final String LAST_MODIFIED = "Last-Modified";
/** The HTTP {@code Link} header field name. */
public static final String LINK = "Link";
/** The HTTP {@code Location} header field name. */
public static final String LOCATION = "Location";
/** The HTTP {@code P3P} header field name. Limited browser support. */
public static final String P3P = "P3P";
/** The HTTP {@code Proxy-Authenticate} header field name. */
public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate";
/** The HTTP {@code Refresh} header field name. Non-standard header supported by most browsers. */
public static final String REFRESH = "Refresh";
/** The HTTP {@code Retry-After} header field name. */
public static final String RETRY_AFTER = "Retry-After";
/** The HTTP {@code Server} header field name. */
public static final String SERVER = "Server";
/** The HTTP {@code Set-Cookie} header field name. */
public static final String SET_COOKIE = "Set-Cookie";
/** The HTTP {@code Set-Cookie2} header field name. */
public static final String SET_COOKIE2 = "Set-Cookie2";
/**
* The HTTP <a href="http://tools.ietf.org/html/rfc6797#section-6.1">
* {@code Strict-Transport-Security}</a> header field name.
*
* @since 15.0
*/
public static final String STRICT_TRANSPORT_SECURITY = "Strict-Transport-Security";
/**
* The HTTP <a href="http://www.w3.org/TR/resource-timing/#cross-origin-resources">
* {@code Timing-Allow-Origin}</a> header field name.
*
* @since 15.0
*/
public static final String TIMING_ALLOW_ORIGIN = "Timing-Allow-Origin";
/** The HTTP {@code Trailer} header field name. */
public static final String TRAILER = "Trailer";
/** The HTTP {@code Transfer-Encoding} header field name. */
public static final String TRANSFER_ENCODING = "Transfer-Encoding";
/** The HTTP {@code Vary} header field name. */
public static final String VARY = "Vary";
/** The HTTP {@code WWW-Authenticate} header field name. */
public static final String WWW_AUTHENTICATE = "WWW-Authenticate";
// Common, non-standard HTTP header fields
/** The HTTP {@code DNT} header field name. */
public static final String DNT = "DNT";
/** The HTTP {@code X-Content-Type-Options} header field name. */
public static final String X_CONTENT_TYPE_OPTIONS = "X-Content-Type-Options";
/** The HTTP {@code X-Do-Not-Track} header field name. */
public static final String X_DO_NOT_TRACK = "X-Do-Not-Track";
/** The HTTP {@code X-Forwarded-For} header field name. */
public static final String X_FORWARDED_FOR = "X-Forwarded-For";
/** The HTTP {@code X-Forwarded-Proto} header field name. */
public static final String X_FORWARDED_PROTO = "X-Forwarded-Proto";
/** The HTTP {@code X-Frame-Options} header field name. */
public static final String X_FRAME_OPTIONS = "X-Frame-Options";
/** The HTTP {@code X-Powered-By} header field name. */
public static final String X_POWERED_BY = "X-Powered-By";
/**
* The HTTP <a href="http://tools.ietf.org/html/draft-evans-palmer-key-pinning">
* {@code Public-Key-Pins}</a> header field name.
*
* @since 15.0
*/
@Beta
public static final String PUBLIC_KEY_PINS = "Public-Key-Pins";
/**
* The HTTP <a href="http://tools.ietf.org/html/draft-evans-palmer-key-pinning">
* {@code Public-Key-Pins-Report-Only}</a> header field name.
*
* @since 15.0
*/
@Beta
public static final String PUBLIC_KEY_PINS_REPORT_ONLY = "Public-Key-Pins-Report-Only";
/** The HTTP {@code X-Requested-With} header field name. */
public static final String X_REQUESTED_WITH = "X-Requested-With";
/** The HTTP {@code X-User-IP} header field name. */
public static final String X_USER_IP = "X-User-IP";
/** The HTTP {@code X-XSS-Protection} header field name. */
public static final String X_XSS_PROTECTION = "X-XSS-Protection";
}
| Java |
/*
* Copyright (C) 2009 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.net;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Ascii;
import com.google.common.base.CharMatcher;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import java.util.List;
import javax.annotation.Nullable;
/**
* An immutable well-formed internet domain name, such as {@code com} or {@code
* foo.co.uk}. Only syntactic analysis is performed; no DNS lookups or other
* network interactions take place. Thus there is no guarantee that the domain
* actually exists on the internet.
*
* <p>One common use of this class is to determine whether a given string is
* likely to represent an addressable domain on the web -- that is, for a
* candidate string {@code "xxx"}, might browsing to {@code "http://xxx/"}
* result in a webpage being displayed? In the past, this test was frequently
* done by determining whether the domain ended with a {@linkplain
* #isPublicSuffix() public suffix} but was not itself a public suffix. However,
* this test is no longer accurate. There are many domains which are both public
* suffixes and addressable as hosts; {@code "uk.com"} is one example. As a
* result, the only useful test to determine if a domain is a plausible web host
* is {@link #hasPublicSuffix()}. This will return {@code true} for many domains
* which (currently) are not hosts, such as {@code "com"}, but given that any
* public suffix may become a host without warning, it is better to err on the
* side of permissiveness and thus avoid spurious rejection of valid sites.
*
* <p>During construction, names are normalized in two ways:
* <ol>
* <li>ASCII uppercase characters are converted to lowercase.
* <li>Unicode dot separators other than the ASCII period ({@code '.'}) are
* converted to the ASCII period.
* </ol>
* <p>The normalized values will be returned from {@link #name()} and
* {@link #parts()}, and will be reflected in the result of
* {@link #equals(Object)}.
*
* <p><a href="http://en.wikipedia.org/wiki/Internationalized_domain_name">
* Internationalized domain names</a> such as {@code 网络.cn} are supported, as
* are the equivalent <a
* href="http://en.wikipedia.org/wiki/Internationalized_domain_name">IDNA
* Punycode-encoded</a> versions.
*
* @author Craig Berry
* @since 5.0
*/
@Beta
@GwtCompatible
public final class InternetDomainName {
private static final CharMatcher DOTS_MATCHER =
CharMatcher.anyOf(".\u3002\uFF0E\uFF61");
private static final Splitter DOT_SPLITTER = Splitter.on('.');
private static final Joiner DOT_JOINER = Joiner.on('.');
/**
* Value of {@link #publicSuffixIndex} which indicates that no public suffix
* was found.
*/
private static final int NO_PUBLIC_SUFFIX_FOUND = -1;
private static final String DOT_REGEX = "\\.";
/**
* Maximum parts (labels) in a domain name. This value arises from
* the 255-octet limit described in
* <a href="http://www.ietf.org/rfc/rfc2181.txt">RFC 2181</a> part 11 with
* the fact that the encoding of each part occupies at least two bytes
* (dot plus label externally, length byte plus label internally). Thus, if
* all labels have the minimum size of one byte, 127 of them will fit.
*/
private static final int MAX_PARTS = 127;
/**
* Maximum length of a full domain name, including separators, and
* leaving room for the root label. See
* <a href="http://www.ietf.org/rfc/rfc2181.txt">RFC 2181</a> part 11.
*/
private static final int MAX_LENGTH = 253;
/**
* Maximum size of a single part of a domain name. See
* <a href="http://www.ietf.org/rfc/rfc2181.txt">RFC 2181</a> part 11.
*/
private static final int MAX_DOMAIN_PART_LENGTH = 63;
/**
* The full domain name, converted to lower case.
*/
private final String name;
/**
* The parts of the domain name, converted to lower case.
*/
private final ImmutableList<String> parts;
/**
* The index in the {@link #parts()} list at which the public suffix begins.
* For example, for the domain name {@code www.google.co.uk}, the value would
* be 2 (the index of the {@code co} part). The value is negative
* (specifically, {@link #NO_PUBLIC_SUFFIX_FOUND}) if no public suffix was
* found.
*/
private final int publicSuffixIndex;
/**
* Constructor used to implement {@link #from(String)}, and from subclasses.
*/
InternetDomainName(String name) {
// Normalize:
// * ASCII characters to lowercase
// * All dot-like characters to '.'
// * Strip trailing '.'
name = Ascii.toLowerCase(DOTS_MATCHER.replaceFrom(name, '.'));
if (name.endsWith(".")) {
name = name.substring(0, name.length() - 1);
}
checkArgument(name.length() <= MAX_LENGTH,
"Domain name too long: '%s':", name);
this.name = name;
this.parts = ImmutableList.copyOf(DOT_SPLITTER.split(name));
checkArgument(parts.size() <= MAX_PARTS,
"Domain has too many parts: '%s'", name);
checkArgument(validateSyntax(parts), "Not a valid domain name: '%s'", name);
this.publicSuffixIndex = findPublicSuffix();
}
/**
* Returns the index of the leftmost part of the public suffix, or -1 if not
* found. Note that the value defined as the "public suffix" may not be a
* public suffix according to {@link #isPublicSuffix()} if the domain ends
* with an excluded domain pattern such as {@code "nhs.uk"}.
*/
private int findPublicSuffix() {
final int partsSize = parts.size();
for (int i = 0; i < partsSize; i++) {
String ancestorName = DOT_JOINER.join(parts.subList(i, partsSize));
if (TldPatterns.EXACT.contains(ancestorName)) {
return i;
}
// Excluded domains (e.g. !nhs.uk) use the next highest
// domain as the effective public suffix (e.g. uk).
if (TldPatterns.EXCLUDED.contains(ancestorName)) {
return i + 1;
}
if (matchesWildcardPublicSuffix(ancestorName)) {
return i;
}
}
return NO_PUBLIC_SUFFIX_FOUND;
}
/**
* A deprecated synonym for {@link #from(String)}.
*
* @param domain A domain name (not IP address)
* @throws IllegalArgumentException if {@code name} is not syntactically valid
* according to {@link #isValid}
* @since 8.0 (previously named {@code from})
* @deprecated Use {@link #from(String)}
*/
@Deprecated
public static InternetDomainName fromLenient(String domain) {
return from(domain);
}
/**
* Returns an instance of {@link InternetDomainName} after lenient
* validation. Specifically, validation against <a
* href="http://www.ietf.org/rfc/rfc3490.txt">RFC 3490</a>
* ("Internationalizing Domain Names in Applications") is skipped, while
* validation against <a
* href="http://www.ietf.org/rfc/rfc1035.txt">RFC 1035</a> is relaxed in
* the following ways:
* <ul>
* <li>Any part containing non-ASCII characters is considered valid.
* <li>Underscores ('_') are permitted wherever dashes ('-') are permitted.
* <li>Parts other than the final part may start with a digit.
* </ul>
*
*
* @param domain A domain name (not IP address)
* @throws IllegalArgumentException if {@code name} is not syntactically valid
* according to {@link #isValid}
* @since 10.0 (previously named {@code fromLenient})
*/
public static InternetDomainName from(String domain) {
return new InternetDomainName(checkNotNull(domain));
}
/**
* Validation method used by {@from} to ensure that the domain name is
* syntactically valid according to RFC 1035.
*
* @return Is the domain name syntactically valid?
*/
private static boolean validateSyntax(List<String> parts) {
final int lastIndex = parts.size() - 1;
// Validate the last part specially, as it has different syntax rules.
if (!validatePart(parts.get(lastIndex), true)) {
return false;
}
for (int i = 0; i < lastIndex; i++) {
String part = parts.get(i);
if (!validatePart(part, false)) {
return false;
}
}
return true;
}
private static final CharMatcher DASH_MATCHER = CharMatcher.anyOf("-_");
private static final CharMatcher PART_CHAR_MATCHER =
CharMatcher.JAVA_LETTER_OR_DIGIT.or(DASH_MATCHER);
/**
* Helper method for {@link #validateSyntax(List)}. Validates that one part of
* a domain name is valid.
*
* @param part The domain name part to be validated
* @param isFinalPart Is this the final (rightmost) domain part?
* @return Whether the part is valid
*/
private static boolean validatePart(String part, boolean isFinalPart) {
// These tests could be collapsed into one big boolean expression, but
// they have been left as independent tests for clarity.
if (part.length() < 1 || part.length() > MAX_DOMAIN_PART_LENGTH) {
return false;
}
/*
* GWT claims to support java.lang.Character's char-classification methods,
* but it actually only works for ASCII. So for now, assume any non-ASCII
* characters are valid. The only place this seems to be documented is here:
* http://osdir.com/ml/GoogleWebToolkitContributors/2010-03/msg00178.html
*
* <p>ASCII characters in the part are expected to be valid per RFC 1035,
* with underscore also being allowed due to widespread practice.
*/
String asciiChars = CharMatcher.ASCII.retainFrom(part);
if (!PART_CHAR_MATCHER.matchesAllOf(asciiChars)) {
return false;
}
// No initial or final dashes or underscores.
if (DASH_MATCHER.matches(part.charAt(0))
|| DASH_MATCHER.matches(part.charAt(part.length() - 1))) {
return false;
}
/*
* Note that we allow (in contravention of a strict interpretation of the
* relevant RFCs) domain parts other than the last may begin with a digit
* (for example, "3com.com"). It's important to disallow an initial digit in
* the last part; it's the only thing that stops an IPv4 numeric address
* like 127.0.0.1 from looking like a valid domain name.
*/
if (isFinalPart && CharMatcher.DIGIT.matches(part.charAt(0))) {
return false;
}
return true;
}
/**
* A deprecated synonym for {@link #toString()}.
*
* @deprecated Use {@link #toString()}
*/
@Deprecated
public String name() {
return toString();
}
/**
* Returns the individual components of this domain name, normalized to all
* lower case. For example, for the domain name {@code mail.google.com}, this
* method returns the list {@code ["mail", "google", "com"]}.
*/
public ImmutableList<String> parts() {
return parts;
}
/**
* Indicates whether this domain name represents a <i>public suffix</i>, as
* defined by the Mozilla Foundation's
* <a href="http://publicsuffix.org/">Public Suffix List</a> (PSL). A public
* suffix is one under which Internet users can directly register names, such
* as {@code com}, {@code co.uk} or {@code pvt.k12.wy.us}. Examples of domain
* names that are <i>not</i> public suffixes include {@code google}, {@code
* google.com} and {@code foo.co.uk}.
*
* @return {@code true} if this domain name appears exactly on the public
* suffix list
* @since 6.0
*/
public boolean isPublicSuffix() {
return publicSuffixIndex == 0;
}
/**
* Indicates whether this domain name ends in a {@linkplain #isPublicSuffix()
* public suffix}, including if it is a public suffix itself. For example,
* returns {@code true} for {@code www.google.com}, {@code foo.co.uk} and
* {@code com}, but not for {@code google} or {@code google.foo}. This is
* the recommended method for determining whether a domain is potentially an
* addressable host.
*
* @since 6.0
*/
public boolean hasPublicSuffix() {
return publicSuffixIndex != NO_PUBLIC_SUFFIX_FOUND;
}
/**
* Returns the {@linkplain #isPublicSuffix() public suffix} portion of the
* domain name, or {@code null} if no public suffix is present.
*
* @since 6.0
*/
public InternetDomainName publicSuffix() {
return hasPublicSuffix() ? ancestor(publicSuffixIndex) : null;
}
/**
* Indicates whether this domain name ends in a {@linkplain #isPublicSuffix()
* public suffix}, while not being a public suffix itself. For example,
* returns {@code true} for {@code www.google.com}, {@code foo.co.uk} and
* {@code bar.ca.us}, but not for {@code google}, {@code com}, or {@code
* google.foo}.
*
* <p><b>Warning:</b> a {@code false} result from this method does not imply
* that the domain does not represent an addressable host, as many public
* suffixes are also addressable hosts. Use {@link #hasPublicSuffix()} for
* that test.
*
* <p>This method can be used to determine whether it will probably be
* possible to set cookies on the domain, though even that depends on
* individual browsers' implementations of cookie controls. See
* <a href="http://www.ietf.org/rfc/rfc2109.txt">RFC 2109</a> for details.
*
* @since 6.0
*/
public boolean isUnderPublicSuffix() {
return publicSuffixIndex > 0;
}
/**
* Indicates whether this domain name is composed of exactly one subdomain
* component followed by a {@linkplain #isPublicSuffix() public suffix}. For
* example, returns {@code true} for {@code google.com} and {@code foo.co.uk},
* but not for {@code www.google.com} or {@code co.uk}.
*
* <p><b>Warning:</b> A {@code true} result from this method does not imply
* that the domain is at the highest level which is addressable as a host, as
* many public suffixes are also addressable hosts. For example, the domain
* {@code bar.uk.com} has a public suffix of {@code uk.com}, so it would
* return {@code true} from this method. But {@code uk.com} is itself an
* addressable host.
*
* <p>This method can be used to determine whether a domain is probably the
* highest level for which cookies may be set, though even that depends on
* individual browsers' implementations of cookie controls. See
* <a href="http://www.ietf.org/rfc/rfc2109.txt">RFC 2109</a> for details.
*
* @since 6.0
*/
public boolean isTopPrivateDomain() {
return publicSuffixIndex == 1;
}
/**
* Returns the portion of this domain name that is one level beneath the
* public suffix. For example, for {@code x.adwords.google.co.uk} it returns
* {@code google.co.uk}, since {@code co.uk} is a public suffix.
*
* <p>If {@link #isTopPrivateDomain()} is true, the current domain name
* instance is returned.
*
* <p>This method should not be used to determine the topmost parent domain
* which is addressable as a host, as many public suffixes are also
* addressable hosts. For example, the domain {@code foo.bar.uk.com} has
* a public suffix of {@code uk.com}, so it would return {@code bar.uk.com}
* from this method. But {@code uk.com} is itself an addressable host.
*
* <p>This method can be used to determine the probable highest level parent
* domain for which cookies may be set, though even that depends on individual
* browsers' implementations of cookie controls.
*
* @throws IllegalStateException if this domain does not end with a
* public suffix
* @since 6.0
*/
public InternetDomainName topPrivateDomain() {
if (isTopPrivateDomain()) {
return this;
}
checkState(isUnderPublicSuffix(), "Not under a public suffix: %s", name);
return ancestor(publicSuffixIndex - 1);
}
/**
* Indicates whether this domain is composed of two or more parts.
*/
public boolean hasParent() {
return parts.size() > 1;
}
/**
* Returns an {@code InternetDomainName} that is the immediate ancestor of
* this one; that is, the current domain with the leftmost part removed. For
* example, the parent of {@code www.google.com} is {@code google.com}.
*
* @throws IllegalStateException if the domain has no parent, as determined
* by {@link #hasParent}
*/
public InternetDomainName parent() {
checkState(hasParent(), "Domain '%s' has no parent", name);
return ancestor(1);
}
/**
* Returns the ancestor of the current domain at the given number of levels
* "higher" (rightward) in the subdomain list. The number of levels must be
* non-negative, and less than {@code N-1}, where {@code N} is the number of
* parts in the domain.
*
* <p>TODO: Reasonable candidate for addition to public API.
*/
private InternetDomainName ancestor(int levels) {
return from(DOT_JOINER.join(parts.subList(levels, parts.size())));
}
/**
* Creates and returns a new {@code InternetDomainName} by prepending the
* argument and a dot to the current name. For example, {@code
* InternetDomainName.from("foo.com").child("www.bar")} returns a new
* {@code InternetDomainName} with the value {@code www.bar.foo.com}. Only
* lenient validation is performed, as described {@link #from(String) here}.
*
* @throws NullPointerException if leftParts is null
* @throws IllegalArgumentException if the resulting name is not valid
*/
public InternetDomainName child(String leftParts) {
return from(checkNotNull(leftParts) + "." + name);
}
/**
* Indicates whether the argument is a syntactically valid domain name using
* lenient validation. Specifically, validation against <a
* href="http://www.ietf.org/rfc/rfc3490.txt">RFC 3490</a>
* ("Internationalizing Domain Names in Applications") is skipped.
*
* <p>The following two code snippets are equivalent:
*
* <pre> {@code
* domainName = InternetDomainName.isValid(name)
* ? InternetDomainName.from(name)
* : DEFAULT_DOMAIN;}</pre>
*
* <pre> {@code
* try {
* domainName = InternetDomainName.from(name);
* } catch (IllegalArgumentException e) {
* domainName = DEFAULT_DOMAIN;
* }}</pre>
*
* @since 8.0 (previously named {@code isValidLenient})
*/
public static boolean isValid(String name) {
try {
from(name);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
/**
* Does the domain name match one of the "wildcard" patterns (e.g.
* {@code "*.ar"})?
*/
private static boolean matchesWildcardPublicSuffix(String domain) {
final String[] pieces = domain.split(DOT_REGEX, 2);
return pieces.length == 2 && TldPatterns.UNDER.contains(pieces[1]);
}
/**
* Returns the domain name, normalized to all lower case.
*/
@Override
public String toString() {
return name;
}
/**
* Equality testing is based on the text supplied by the caller,
* after normalization as described in the class documentation. For
* example, a non-ASCII Unicode domain name and the Punycode version
* of the same domain name would not be considered equal.
*
*/
@Override
public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof InternetDomainName) {
InternetDomainName that = (InternetDomainName) object;
return this.name.equals(that.name);
}
return false;
}
@Override
public int hashCode() {
return name.hashCode();
}
}
| Java |
/*
* Copyright (C) 2009 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.net;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.escape.Escaper;
/**
* {@code Escaper} instances suitable for strings to be included in particular
* sections of URLs.
*
* <p>If the resulting URLs are inserted into an HTML or XML document, they will
* require additional escaping with {@link com.google.common.html.HtmlEscapers}
* or {@link com.google.common.xml.XmlEscapers}.
*
*
* @author David Beaumont
* @author Chris Povirk
* @since 15.0
*/
@Beta
@GwtCompatible
public final class UrlEscapers {
private UrlEscapers() {}
// For each xxxEscaper() method, please add links to external reference pages
// that are considered authoritative for the behavior of that escaper.
static final String URL_FORM_PARAMETER_OTHER_SAFE_CHARS = "-_.*";
static final String URL_PATH_OTHER_SAFE_CHARS_LACKING_PLUS =
"-._~" + // Unreserved characters.
"!$'()*,;&=" + // The subdelim characters (excluding '+').
"@:"; // The gendelim characters permitted in paths.
/**
* Returns an {@link Escaper} instance that escapes strings so they can be
* safely included in <a href="http://goo.gl/OQEc8">URL form parameter names
* and values</a>. Escaping is performed with the UTF-8 character encoding.
* The caller is responsible for <a href="http://goo.gl/i20ms">replacing any
* unpaired carriage return or line feed characters with a CR+LF pair</a> on
* any non-file inputs before escaping them with this escaper.
*
* <p>When escaping a String, the following rules apply:
* <ul>
* <li>The alphanumeric characters "a" through "z", "A" through "Z" and "0"
* through "9" remain the same.
* <li>The special characters ".", "-", "*", and "_" remain the same.
* <li>The space character " " is converted into a plus sign "+".
* <li>All other characters are converted into one or more bytes using UTF-8
* encoding and each byte is then represented by the 3-character string
* "%XY", where "XY" is the two-digit, uppercase, hexadecimal
* representation of the byte value.
* </ul>
*
* <p>This escaper is suitable for escaping parameter names and values even
* when <a href="http://goo.gl/utn6M">using the non-standard semicolon</a>,
* rather than the ampersand, as a parameter delimiter. Nevertheless, we
* recommend using the ampersand unless you must interoperate with systems
* that require semicolons.
*
* <p><b>Note</b>: Unlike other escapers, URL escapers produce uppercase
* hexadecimal sequences. From <a href="http://www.ietf.org/rfc/rfc3986.txt">
* RFC 3986</a>:<br>
* <i>"URI producers and normalizers should use uppercase hexadecimal digits
* for all percent-encodings."</i>
*
*/
public static Escaper urlFormParameterEscaper() {
return URL_FORM_PARAMETER_ESCAPER;
}
private static final Escaper URL_FORM_PARAMETER_ESCAPER =
new PercentEscaper(URL_FORM_PARAMETER_OTHER_SAFE_CHARS, true);
/**
* Returns an {@link Escaper} instance that escapes strings so they can be
* safely included in <a href="http://goo.gl/swjbR">URL path segments</a>. The
* returned escaper escapes all non-ASCII characters, even though <a
* href="http://goo.gl/xIJWe">many of these are accepted in modern URLs</a>.
* (<a href="http://goo.gl/WMGvZ">If the escaper were to leave these
* characters unescaped, they would be escaped by the consumer at parse time,
* anyway.</a>) Additionally, the escaper escapes the slash character ("/").
* While slashes are acceptable in URL paths, they are considered by the
* specification to be separators between "path segments." This implies that,
* if you wish for your path to contain slashes, you must escape each segment
* separately and then join them.
*
* <p>When escaping a String, the following rules apply:
* <ul>
* <li>The alphanumeric characters "a" through "z", "A" through "Z" and "0"
* through "9" remain the same.
* <li>The unreserved characters ".", "-", "~", and "_" remain the same.
* <li>The general delimiters "@" and ":" remain the same.
* <li>The subdelimiters "!", "$", "&", "'", "(", ")", "*", "+", ",", ";",
* and "=" remain the same.
* <li>The space character " " is converted into %20.
* <li>All other characters are converted into one or more bytes using UTF-8
* encoding and each byte is then represented by the 3-character string
* "%XY", where "XY" is the two-digit, uppercase, hexadecimal
* representation of the byte value.
* </ul>
*
* <p><b>Note</b>: Unlike other escapers, URL escapers produce uppercase
* hexadecimal sequences. From <a href="http://www.ietf.org/rfc/rfc3986.txt">
* RFC 3986</a>:<br>
* <i>"URI producers and normalizers should use uppercase hexadecimal digits
* for all percent-encodings."</i>
*/
public static Escaper urlPathSegmentEscaper() {
return URL_PATH_SEGMENT_ESCAPER;
}
private static final Escaper URL_PATH_SEGMENT_ESCAPER =
new PercentEscaper(URL_PATH_OTHER_SAFE_CHARS_LACKING_PLUS + "+", false);
}
| Java |
/*
* 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.net;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.escape.UnicodeEscaper;
/**
* A {@code UnicodeEscaper} that escapes some set of Java characters using a
* UTF-8 based percent encoding scheme. The set of safe characters (those which
* remain unescaped) can be specified on construction.
*
* <p>This class is primarily used for creating URI escapers in {@link
* UrlEscapers} but can be used directly if required. While URI escapers impose
* specific semantics on which characters are considered 'safe', this class has
* a minimal set of restrictions.
*
* <p>When escaping a String, the following rules apply:
* <ul>
* <li>All specified safe characters remain unchanged.
* <li>If {@code plusForSpace} was specified, the space character " " is
* converted into a plus sign {@code "+"}.
* <li>All other characters are converted into one or more bytes using UTF-8
* encoding and each byte is then represented by the 3-character string
* "%XX", where "XX" is the two-digit, uppercase, hexadecimal representation
* of the byte value.
* </ul>
*
* <p>For performance reasons the only currently supported character encoding of
* this class is UTF-8.
*
* <p><b>Note</b>: This escaper produces uppercase hexadecimal sequences. From
* <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>:<br>
* <i>"URI producers and normalizers should use uppercase hexadecimal digits
* for all percent-encodings."</i>
*
* @author David Beaumont
* @since 15.0
*/
@Beta
@GwtCompatible
public final class PercentEscaper extends UnicodeEscaper {
// In some escapers spaces are escaped to '+'
private static final char[] PLUS_SIGN = { '+' };
// Percent escapers output upper case hex digits (uri escapers require this).
private static final char[] UPPER_HEX_DIGITS =
"0123456789ABCDEF".toCharArray();
/**
* If true we should convert space to the {@code +} character.
*/
private final boolean plusForSpace;
/**
* An array of flags where for any {@code char c} if {@code safeOctets[c]} is
* true then {@code c} should remain unmodified in the output. If
* {@code c > safeOctets.length} then it should be escaped.
*/
private final boolean[] safeOctets;
/**
* Constructs a percent escaper with the specified safe characters and
* optional handling of the space character.
*
* <p>Not that it is allowed, but not necessarily desirable to specify {@code %}
* as a safe character. This has the effect of creating an escaper which has no
* well defined inverse but it can be useful when escaping additional characters.
*
* @param safeChars a non null string specifying additional safe characters
* for this escaper (the ranges 0..9, a..z and A..Z are always safe and
* should not be specified here)
* @param plusForSpace true if ASCII space should be escaped to {@code +}
* rather than {@code %20}
* @throws IllegalArgumentException if any of the parameters were invalid
*/
public PercentEscaper(String safeChars, boolean plusForSpace) {
// TODO(user): Switch to static factory methods for creation now that class is final.
// TODO(user): Support escapers where alphanumeric chars are not safe.
checkNotNull(safeChars); // eager for GWT.
// Avoid any misunderstandings about the behavior of this escaper
if (safeChars.matches(".*[0-9A-Za-z].*")) {
throw new IllegalArgumentException(
"Alphanumeric characters are always 'safe' and should not be " +
"explicitly specified");
}
safeChars += "abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"0123456789";
// Avoid ambiguous parameters. Safe characters are never modified so if
// space is a safe character then setting plusForSpace is meaningless.
if (plusForSpace && safeChars.contains(" ")) {
throw new IllegalArgumentException(
"plusForSpace cannot be specified when space is a 'safe' character");
}
this.plusForSpace = plusForSpace;
this.safeOctets = createSafeOctets(safeChars);
}
/**
* Creates a boolean array with entries corresponding to the character values
* specified in safeChars set to true. The array is as small as is required to
* hold the given character information.
*/
private static boolean[] createSafeOctets(String safeChars) {
int maxChar = -1;
char[] safeCharArray = safeChars.toCharArray();
for (char c : safeCharArray) {
maxChar = Math.max(c, maxChar);
}
boolean[] octets = new boolean[maxChar + 1];
for (char c : safeCharArray) {
octets[c] = true;
}
return octets;
}
/*
* Overridden for performance. For unescaped strings this improved the
* performance of the uri escaper from ~760ns to ~400ns as measured by
* {@link CharEscapersBenchmark}.
*/
@Override
protected int nextEscapeIndex(CharSequence csq, int index, int end) {
checkNotNull(csq);
for (; index < end; index++) {
char c = csq.charAt(index);
if (c >= safeOctets.length || !safeOctets[c]) {
break;
}
}
return index;
}
/*
* Overridden for performance. For unescaped strings this improved the
* performance of the uri escaper from ~400ns to ~170ns as measured by
* {@link CharEscapersBenchmark}.
*/
@Override
public String escape(String s) {
checkNotNull(s);
int slen = s.length();
for (int index = 0; index < slen; index++) {
char c = s.charAt(index);
if (c >= safeOctets.length || !safeOctets[c]) {
return escapeSlow(s, index);
}
}
return s;
}
/**
* Escapes the given Unicode code point in UTF-8.
*/
@Override
protected char[] escape(int cp) {
// We should never get negative values here but if we do it will throw an
// IndexOutOfBoundsException, so at least it will get spotted.
if (cp < safeOctets.length && safeOctets[cp]) {
return null;
} else if (cp == ' ' && plusForSpace) {
return PLUS_SIGN;
} else if (cp <= 0x7F) {
// Single byte UTF-8 characters
// Start with "%--" and fill in the blanks
char[] dest = new char[3];
dest[0] = '%';
dest[2] = UPPER_HEX_DIGITS[cp & 0xF];
dest[1] = UPPER_HEX_DIGITS[cp >>> 4];
return dest;
} else if (cp <= 0x7ff) {
// Two byte UTF-8 characters [cp >= 0x80 && cp <= 0x7ff]
// Start with "%--%--" and fill in the blanks
char[] dest = new char[6];
dest[0] = '%';
dest[3] = '%';
dest[5] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[2] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[1] = UPPER_HEX_DIGITS[0xC | cp];
return dest;
} else if (cp <= 0xffff) {
// Three byte UTF-8 characters [cp >= 0x800 && cp <= 0xffff]
// Start with "%E-%--%--" and fill in the blanks
char[] dest = new char[9];
dest[0] = '%';
dest[1] = 'E';
dest[3] = '%';
dest[6] = '%';
dest[8] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[7] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[5] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[2] = UPPER_HEX_DIGITS[cp];
return dest;
} else if (cp <= 0x10ffff) {
char[] dest = new char[12];
// Four byte UTF-8 characters [cp >= 0xffff && cp <= 0x10ffff]
// Start with "%F-%--%--%--" and fill in the blanks
dest[0] = '%';
dest[1] = 'F';
dest[3] = '%';
dest[6] = '%';
dest[9] = '%';
dest[11] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[10] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[8] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[7] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[5] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[2] = UPPER_HEX_DIGITS[cp & 0x7];
return dest;
} else {
// If this ever happens it is due to bug in UnicodeEscaper, not bad input.
throw new IllegalArgumentException(
"Invalid unicode character value " + cp);
}
}
}
| Java |
/*
* Copyright (C) 2011 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.net;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import com.google.common.base.Strings;
import java.io.Serializable;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
/**
* An immutable representation of a host and port.
*
* <p>Example usage:
* <pre>
* HostAndPort hp = HostAndPort.fromString("[2001:db8::1]")
* .withDefaultPort(80)
* .requireBracketsForIPv6();
* hp.getHostText(); // returns "2001:db8::1"
* hp.getPort(); // returns 80
* hp.toString(); // returns "[2001:db8::1]:80"
* </pre>
*
* <p>Here are some examples of recognized formats:
* <ul>
* <li>example.com
* <li>example.com:80
* <li>192.0.2.1
* <li>192.0.2.1:80
* <li>[2001:db8::1] - {@link #getHostText()} omits brackets
* <li>[2001:db8::1]:80 - {@link #getHostText()} omits brackets
* <li>2001:db8::1 - Use {@link #requireBracketsForIPv6()} to prohibit this
* </ul>
*
* <p>Note that this is not an exhaustive list, because these methods are only
* concerned with brackets, colons, and port numbers. Full validation of the
* host field (if desired) is the caller's responsibility.
*
* @author Paul Marks
* @since 10.0
*/
@Beta
@Immutable
@GwtCompatible
public final class HostAndPort implements Serializable {
/** Magic value indicating the absence of a port number. */
private static final int NO_PORT = -1;
/** Hostname, IPv4/IPv6 literal, or unvalidated nonsense. */
private final String host;
/** Validated port number in the range [0..65535], or NO_PORT */
private final int port;
/** True if the parsed host has colons, but no surrounding brackets. */
private final boolean hasBracketlessColons;
private HostAndPort(String host, int port, boolean hasBracketlessColons) {
this.host = host;
this.port = port;
this.hasBracketlessColons = hasBracketlessColons;
}
/**
* Returns the portion of this {@code HostAndPort} instance that should
* represent the hostname or IPv4/IPv6 literal.
*
* <p>A successful parse does not imply any degree of sanity in this field.
* For additional validation, see the {@link HostSpecifier} class.
*/
public String getHostText() {
return host;
}
/** Return true if this instance has a defined port. */
public boolean hasPort() {
return port >= 0;
}
/**
* Get the current port number, failing if no port is defined.
*
* @return a validated port number, in the range [0..65535]
* @throws IllegalStateException if no port is defined. You can use
* {@link #withDefaultPort(int)} to prevent this from occurring.
*/
public int getPort() {
checkState(hasPort());
return port;
}
/**
* Returns the current port number, with a default if no port is defined.
*/
public int getPortOrDefault(int defaultPort) {
return hasPort() ? port : defaultPort;
}
/**
* Build a HostAndPort instance from separate host and port values.
*
* <p>Note: Non-bracketed IPv6 literals are allowed.
* Use {@link #requireBracketsForIPv6()} to prohibit these.
*
* @param host the host string to parse. Must not contain a port number.
* @param port a port number from [0..65535]
* @return if parsing was successful, a populated HostAndPort object.
* @throws IllegalArgumentException if {@code host} contains a port number,
* or {@code port} is out of range.
*/
public static HostAndPort fromParts(String host, int port) {
checkArgument(isValidPort(port), "Port out of range: %s", port);
HostAndPort parsedHost = fromString(host);
checkArgument(!parsedHost.hasPort(), "Host has a port: %s", host);
return new HostAndPort(parsedHost.host, port, parsedHost.hasBracketlessColons);
}
/**
* Split a freeform string into a host and port, without strict validation.
*
* Note that the host-only formats will leave the port field undefined. You
* can use {@link #withDefaultPort(int)} to patch in a default value.
*
* @param hostPortString the input string to parse.
* @return if parsing was successful, a populated HostAndPort object.
* @throws IllegalArgumentException if nothing meaningful could be parsed.
*/
public static HostAndPort fromString(String hostPortString) {
checkNotNull(hostPortString);
String host;
String portString = null;
boolean hasBracketlessColons = false;
if (hostPortString.startsWith("[")) {
String[] hostAndPort = getHostAndPortFromBracketedHost(hostPortString);
host = hostAndPort[0];
portString = hostAndPort[1];
} else {
int colonPos = hostPortString.indexOf(':');
if (colonPos >= 0 && hostPortString.indexOf(':', colonPos + 1) == -1) {
// Exactly 1 colon. Split into host:port.
host = hostPortString.substring(0, colonPos);
portString = hostPortString.substring(colonPos + 1);
} else {
// 0 or 2+ colons. Bare hostname or IPv6 literal.
host = hostPortString;
hasBracketlessColons = (colonPos >= 0);
}
}
int port = NO_PORT;
if (!Strings.isNullOrEmpty(portString)) {
// Try to parse the whole port string as a number.
// JDK7 accepts leading plus signs. We don't want to.
checkArgument(!portString.startsWith("+"), "Unparseable port number: %s", hostPortString);
try {
port = Integer.parseInt(portString);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Unparseable port number: " + hostPortString);
}
checkArgument(isValidPort(port), "Port number out of range: %s", hostPortString);
}
return new HostAndPort(host, port, hasBracketlessColons);
}
/**
* Parses a bracketed host-port string, throwing IllegalArgumentException if parsing fails.
*
* @param hostPortString the full bracketed host-port specification. Post might not be specified.
* @return an array with 2 strings: host and port, in that order.
* @throws IllegalArgumentException if parsing the bracketed host-port string fails.
*/
private static String[] getHostAndPortFromBracketedHost(String hostPortString) {
int colonIndex = 0;
int closeBracketIndex = 0;
boolean hasPort = false;
checkArgument(hostPortString.charAt(0) == '[',
"Bracketed host-port string must start with a bracket: %s", hostPortString);
colonIndex = hostPortString.indexOf(':');
closeBracketIndex = hostPortString.lastIndexOf(']');
checkArgument(colonIndex > -1 && closeBracketIndex > colonIndex,
"Invalid bracketed host/port: %s", hostPortString);
String host = hostPortString.substring(1, closeBracketIndex);
if (closeBracketIndex + 1 == hostPortString.length()) {
return new String[] { host, "" };
} else {
checkArgument(hostPortString.charAt(closeBracketIndex + 1) == ':',
"Only a colon may follow a close bracket: %s", hostPortString);
for (int i = closeBracketIndex + 2; i < hostPortString.length(); ++i) {
checkArgument(Character.isDigit(hostPortString.charAt(i)),
"Port must be numeric: %s", hostPortString);
}
return new String[] { host, hostPortString.substring(closeBracketIndex + 2) };
}
}
/**
* Provide a default port if the parsed string contained only a host.
*
* You can chain this after {@link #fromString(String)} to include a port in
* case the port was omitted from the input string. If a port was already
* provided, then this method is a no-op.
*
* @param defaultPort a port number, from [0..65535]
* @return a HostAndPort instance, guaranteed to have a defined port.
*/
public HostAndPort withDefaultPort(int defaultPort) {
checkArgument(isValidPort(defaultPort));
if (hasPort() || port == defaultPort) {
return this;
}
return new HostAndPort(host, defaultPort, hasBracketlessColons);
}
/**
* Generate an error if the host might be a non-bracketed IPv6 literal.
*
* <p>URI formatting requires that IPv6 literals be surrounded by brackets,
* like "[2001:db8::1]". Chain this call after {@link #fromString(String)}
* to increase the strictness of the parser, and disallow IPv6 literals
* that don't contain these brackets.
*
* <p>Note that this parser identifies IPv6 literals solely based on the
* presence of a colon. To perform actual validation of IP addresses, see
* the {@link InetAddresses#forString(String)} method.
*
* @return {@code this}, to enable chaining of calls.
* @throws IllegalArgumentException if bracketless IPv6 is detected.
*/
public HostAndPort requireBracketsForIPv6() {
checkArgument(!hasBracketlessColons, "Possible bracketless IPv6 literal: %s", host);
return this;
}
@Override
public boolean equals(@Nullable Object other) {
if (this == other) {
return true;
}
if (other instanceof HostAndPort) {
HostAndPort that = (HostAndPort) other;
return Objects.equal(this.host, that.host)
&& this.port == that.port
&& this.hasBracketlessColons == that.hasBracketlessColons;
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(host, port, hasBracketlessColons);
}
/** Rebuild the host:port string, including brackets if necessary. */
@Override
public String toString() {
StringBuilder builder = new StringBuilder(host.length() + 7);
if (host.indexOf(':') >= 0) {
builder.append('[').append(host).append(']');
} else {
builder.append(host);
}
if (hasPort()) {
builder.append(':').append(port);
}
return builder.toString();
}
/** Return true for valid port numbers. */
private static boolean isValidPort(int port) {
return port >= 0 && port <= 65535;
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* 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.collect;
import com.google.common.annotations.GwtCompatible;
/**
* Implementation of {@link ImmutableListMultimap} with no entries.
*
* @author Jared Levy
*/
@GwtCompatible(serializable = true)
class EmptyImmutableListMultimap extends ImmutableListMultimap<Object, Object> {
static final EmptyImmutableListMultimap INSTANCE
= new EmptyImmutableListMultimap();
private EmptyImmutableListMultimap() {
super(ImmutableMap.<Object, ImmutableList<Object>>of(), 0);
}
private Object readResolve() {
return INSTANCE; // preserve singleton property
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2007 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.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.concurrent.ConcurrentMap;
/**
* A concurrent map which forwards all its method calls to another concurrent
* map. Subclasses should override one or more methods to modify the behavior of
* the backing map as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* @author Charles Fry
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public abstract class ForwardingConcurrentMap<K, V> extends ForwardingMap<K, V>
implements ConcurrentMap<K, V> {
/** Constructor for use by subclasses. */
protected ForwardingConcurrentMap() {}
@Override protected abstract ConcurrentMap<K, V> delegate();
@Override
public V putIfAbsent(K key, V value) {
return delegate().putIfAbsent(key, value);
}
@Override
public boolean remove(Object key, Object value) {
return delegate().remove(key, value);
}
@Override
public V replace(K key, V value) {
return delegate().replace(key, value);
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
return delegate().replace(key, oldValue, newValue);
}
}
| Java |
/*
* Copyright (C) 2007 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.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A map, each entry of which maps a Java
* <a href="http://tinyurl.com/2cmwkz">raw type</a> to an instance of that type.
* In addition to implementing {@code Map}, the additional type-safe operations
* {@link #putInstance} and {@link #getInstance} are available.
*
* <p>Like any other {@code Map<Class, Object>}, this map may contain entries
* for primitive types, and a primitive type and its corresponding wrapper type
* may map to different values.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#ClassToInstanceMap">
* {@code ClassToInstanceMap}</a>.
*
* <p>To map a generic type to an instance of that type, use {@link
* com.google.common.reflect.TypeToInstanceMap} instead.
*
* @param <B> the common supertype that all entries must share; often this is
* simply {@link Object}
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public interface ClassToInstanceMap<B> extends Map<Class<? extends B>, B> {
/**
* Returns the value the specified class is mapped to, or {@code null} if no
* entry for this class is present. This will only return a value that was
* bound to this specific class, not a value that may have been bound to a
* subtype.
*/
<T extends B> T getInstance(Class<T> type);
/**
* Maps the specified class to the specified value. Does <i>not</i> associate
* this value with any of the class's supertypes.
*
* @return the value previously associated with this class (possibly {@code
* null}), or {@code null} if there was no previous entry.
*/
<T extends B> T putInstance(Class<T> type, @Nullable T value);
}
| Java |
/*
* Copyright (C) 2011 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.collect;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NavigableSet;
/**
* A sorted multiset which forwards all its method calls to another sorted multiset. Subclasses
* should override one or more methods to modify the behavior of the backing multiset as desired
* per the <a href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p><b>Warning:</b> The methods of {@code ForwardingSortedMultiset} forward
* <b>indiscriminately</b> to the methods of the delegate. For example, overriding
* {@link #add(Object, int)} alone <b>will not</b> change the behavior of {@link #add(Object)},
* which can lead to unexpected behavior. In this case, you should override {@code add(Object)} as
* well, either providing your own implementation, or delegating to the provided {@code
* standardAdd} method.
*
* <p>The {@code standard} methods and any collection views they return are not guaranteed to be
* thread-safe, even when all of the methods that they depend on are thread-safe.
*
* @author Louis Wasserman
* @since 15.0
*/
@Beta
@GwtCompatible(emulated = true)
public abstract class ForwardingSortedMultiset<E> extends ForwardingMultiset<E>
implements SortedMultiset<E> {
/** Constructor for use by subclasses. */
protected ForwardingSortedMultiset() {}
@Override
protected abstract SortedMultiset<E> delegate();
@Override
public NavigableSet<E> elementSet() {
return (NavigableSet<E>) super.elementSet();
}
/**
* A sensible implementation of {@link SortedMultiset#elementSet} in terms of the following
* methods: {@link SortedMultiset#clear}, {@link SortedMultiset#comparator}, {@link
* SortedMultiset#contains}, {@link SortedMultiset#containsAll}, {@link SortedMultiset#count},
* {@link SortedMultiset#firstEntry} {@link SortedMultiset#headMultiset}, {@link
* SortedMultiset#isEmpty}, {@link SortedMultiset#lastEntry}, {@link SortedMultiset#subMultiset},
* {@link SortedMultiset#tailMultiset}, the {@code size()} and {@code iterator()} methods of
* {@link SortedMultiset#entrySet}, and {@link SortedMultiset#remove(Object, int)}. In many
* situations, you may wish to override {@link SortedMultiset#elementSet} to forward to this
* implementation or a subclass thereof.
*/
protected class StandardElementSet extends SortedMultisets.NavigableElementSet<E> {
/** Constructor for use by subclasses. */
public StandardElementSet() {
super(ForwardingSortedMultiset.this);
}
}
@Override
public Comparator<? super E> comparator() {
return delegate().comparator();
}
@Override
public SortedMultiset<E> descendingMultiset() {
return delegate().descendingMultiset();
}
/**
* A skeleton implementation of a descending multiset view. Normally,
* {@link #descendingMultiset()} will not reflect any changes you make to the behavior of methods
* such as {@link #add(Object)} or {@link #pollFirstEntry}. This skeleton implementation
* correctly delegates each of its operations to the appropriate methods of this {@code
* ForwardingSortedMultiset}.
*
* In many cases, you may wish to override {@link #descendingMultiset()} to return an instance of
* a subclass of {@code StandardDescendingMultiset}.
*/
protected abstract class StandardDescendingMultiset
extends DescendingMultiset<E> {
/** Constructor for use by subclasses. */
public StandardDescendingMultiset() {}
@Override
SortedMultiset<E> forwardMultiset() {
return ForwardingSortedMultiset.this;
}
}
@Override
public Entry<E> firstEntry() {
return delegate().firstEntry();
}
/**
* A sensible definition of {@link #firstEntry()} in terms of {@code entrySet().iterator()}.
*
* If you override {@link #entrySet()}, you may wish to override {@link #firstEntry()} to forward
* to this implementation.
*/
protected Entry<E> standardFirstEntry() {
Iterator<Entry<E>> entryIterator = entrySet().iterator();
if (!entryIterator.hasNext()) {
return null;
}
Entry<E> entry = entryIterator.next();
return Multisets.immutableEntry(entry.getElement(), entry.getCount());
}
@Override
public Entry<E> lastEntry() {
return delegate().lastEntry();
}
/**
* A sensible definition of {@link #lastEntry()} in terms of {@code
* descendingMultiset().entrySet().iterator()}.
*
* If you override {@link #descendingMultiset} or {@link #entrySet()}, you may wish to override
* {@link #firstEntry()} to forward to this implementation.
*/
protected Entry<E> standardLastEntry() {
Iterator<Entry<E>> entryIterator = descendingMultiset()
.entrySet()
.iterator();
if (!entryIterator.hasNext()) {
return null;
}
Entry<E> entry = entryIterator.next();
return Multisets.immutableEntry(entry.getElement(), entry.getCount());
}
@Override
public Entry<E> pollFirstEntry() {
return delegate().pollFirstEntry();
}
/**
* A sensible definition of {@link #pollFirstEntry()} in terms of {@code entrySet().iterator()}.
*
* If you override {@link #entrySet()}, you may wish to override {@link #pollFirstEntry()} to
* forward to this implementation.
*/
protected Entry<E> standardPollFirstEntry() {
Iterator<Entry<E>> entryIterator = entrySet().iterator();
if (!entryIterator.hasNext()) {
return null;
}
Entry<E> entry = entryIterator.next();
entry = Multisets.immutableEntry(entry.getElement(), entry.getCount());
entryIterator.remove();
return entry;
}
@Override
public Entry<E> pollLastEntry() {
return delegate().pollLastEntry();
}
/**
* A sensible definition of {@link #pollLastEntry()} in terms of {@code
* descendingMultiset().entrySet().iterator()}.
*
* If you override {@link #descendingMultiset()} or {@link #entrySet()}, you may wish to override
* {@link #pollLastEntry()} to forward to this implementation.
*/
protected Entry<E> standardPollLastEntry() {
Iterator<Entry<E>> entryIterator = descendingMultiset()
.entrySet()
.iterator();
if (!entryIterator.hasNext()) {
return null;
}
Entry<E> entry = entryIterator.next();
entry = Multisets.immutableEntry(entry.getElement(), entry.getCount());
entryIterator.remove();
return entry;
}
@Override
public SortedMultiset<E> headMultiset(E upperBound, BoundType boundType) {
return delegate().headMultiset(upperBound, boundType);
}
@Override
public SortedMultiset<E> subMultiset(
E lowerBound, BoundType lowerBoundType, E upperBound, BoundType upperBoundType) {
return delegate().subMultiset(lowerBound, lowerBoundType, upperBound, upperBoundType);
}
/**
* A sensible definition of {@link #subMultiset(Object, BoundType, Object, BoundType)} in terms
* of {@link #headMultiset(Object, BoundType) headMultiset} and
* {@link #tailMultiset(Object, BoundType) tailMultiset}.
*
* If you override either of these methods, you may wish to override
* {@link #subMultiset(Object, BoundType, Object, BoundType)} to forward to this implementation.
*/
protected SortedMultiset<E> standardSubMultiset(
E lowerBound, BoundType lowerBoundType, E upperBound, BoundType upperBoundType) {
return tailMultiset(lowerBound, lowerBoundType).headMultiset(upperBound, upperBoundType);
}
@Override
public SortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) {
return delegate().tailMultiset(lowerBound, boundType);
}
}
| Java |
/*
* Copyright (C) 2012 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.collect;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.EnumMap;
import java.util.Iterator;
import javax.annotation.Nullable;
/**
* Implementation of {@link ImmutableMap} backed by a non-empty {@link
* java.util.EnumMap}.
*
* @author Louis Wasserman
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
final class ImmutableEnumMap<K extends Enum<K>, V> extends ImmutableMap<K, V> {
static <K extends Enum<K>, V> ImmutableMap<K, V> asImmutable(EnumMap<K, V> map) {
switch (map.size()) {
case 0:
return ImmutableMap.of();
case 1: {
Entry<K, V> entry = Iterables.getOnlyElement(map.entrySet());
return ImmutableMap.of(entry.getKey(), entry.getValue());
}
default:
return new ImmutableEnumMap<K, V>(map);
}
}
private transient final EnumMap<K, V> delegate;
private ImmutableEnumMap(EnumMap<K, V> delegate) {
this.delegate = delegate;
checkArgument(!delegate.isEmpty());
}
@Override
ImmutableSet<K> createKeySet() {
return new ImmutableSet<K>() {
@Override
public boolean contains(Object object) {
return delegate.containsKey(object);
}
@Override
public int size() {
return ImmutableEnumMap.this.size();
}
@Override
public UnmodifiableIterator<K> iterator() {
return Iterators.unmodifiableIterator(delegate.keySet().iterator());
}
@Override
boolean isPartialView() {
return true;
}
};
}
@Override
public int size() {
return delegate.size();
}
@Override
public boolean containsKey(@Nullable Object key) {
return delegate.containsKey(key);
}
@Override
public V get(Object key) {
return delegate.get(key);
}
@Override
ImmutableSet<Entry<K, V>> createEntrySet() {
return new ImmutableMapEntrySet<K, V>() {
@Override
ImmutableMap<K, V> map() {
return ImmutableEnumMap.this;
}
@Override
public UnmodifiableIterator<Entry<K, V>> iterator() {
return new UnmodifiableIterator<Entry<K, V>>() {
private final Iterator<Entry<K, V>> backingIterator = delegate.entrySet().iterator();
@Override
public boolean hasNext() {
return backingIterator.hasNext();
}
@Override
public Entry<K, V> next() {
Entry<K, V> entry = backingIterator.next();
return Maps.immutableEntry(entry.getKey(), entry.getValue());
}
};
}
};
}
@Override
boolean isPartialView() {
return false;
}
// All callers of the constructor are restricted to <K extends Enum<K>>.
@Override Object writeReplace() {
return new EnumSerializedForm<K, V>(delegate);
}
/*
* This class is used to serialize ImmutableEnumSet instances.
*/
private static class EnumSerializedForm<K extends Enum<K>, V>
implements Serializable {
final EnumMap<K, V> delegate;
EnumSerializedForm(EnumMap<K, V> delegate) {
this.delegate = delegate;
}
Object readResolve() {
return new ImmutableEnumMap<K, V>(delegate);
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* Copyright (C) 2009 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.collect;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.Collection;
import java.util.EnumSet;
/**
* Implementation of {@link ImmutableSet} backed by a non-empty {@link
* java.util.EnumSet}.
*
* @author Jared Levy
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
final class ImmutableEnumSet<E extends Enum<E>> extends ImmutableSet<E> {
static <E extends Enum<E>> ImmutableSet<E> asImmutable(EnumSet<E> set) {
switch (set.size()) {
case 0:
return ImmutableSet.of();
case 1:
return ImmutableSet.of(Iterables.getOnlyElement(set));
default:
return new ImmutableEnumSet<E>(set);
}
}
/*
* Notes on EnumSet and <E extends Enum<E>>:
*
* This class isn't an arbitrary ForwardingImmutableSet because we need to
* know that calling {@code clone()} during deserialization will return an
* object that no one else has a reference to, allowing us to guarantee
* immutability. Hence, we support only {@link EnumSet}.
*/
private final transient EnumSet<E> delegate;
private ImmutableEnumSet(EnumSet<E> delegate) {
this.delegate = delegate;
}
@Override boolean isPartialView() {
return false;
}
@Override public UnmodifiableIterator<E> iterator() {
return Iterators.unmodifiableIterator(delegate.iterator());
}
@Override
public int size() {
return delegate.size();
}
@Override public boolean contains(Object object) {
return delegate.contains(object);
}
@Override public boolean containsAll(Collection<?> collection) {
return delegate.containsAll(collection);
}
@Override public boolean isEmpty() {
return delegate.isEmpty();
}
@Override public boolean equals(Object object) {
return object == this || delegate.equals(object);
}
private transient int hashCode;
@Override public int hashCode() {
int result = hashCode;
return (result == 0) ? hashCode = delegate.hashCode() : result;
}
@Override public String toString() {
return delegate.toString();
}
// All callers of the constructor are restricted to <E extends Enum<E>>.
@Override Object writeReplace() {
return new EnumSerializedForm<E>(delegate);
}
/*
* This class is used to serialize ImmutableEnumSet instances.
*/
private static class EnumSerializedForm<E extends Enum<E>>
implements Serializable {
final EnumSet<E> delegate;
EnumSerializedForm(EnumSet<E> delegate) {
this.delegate = delegate;
}
Object readResolve() {
// EJ2 #76: Write readObject() methods defensively.
return new ImmutableEnumSet<E>(delegate.clone());
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* Copyright (C) 2010 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.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.RandomAccess;
import javax.annotation.Nullable;
/**
* Static methods pertaining to sorted {@link List} instances.
*
* In this documentation, the terms <i>greatest</i>, <i>greater</i>, <i>least</i>, and
* <i>lesser</i> are considered to refer to the comparator on the elements, and the terms
* <i>first</i> and <i>last</i> are considered to refer to the elements' ordering in a
* list.
*
* @author Louis Wasserman
*/
@GwtCompatible
@Beta final class SortedLists {
private SortedLists() {}
/**
* A specification for which index to return if the list contains at least one element that
* compares as equal to the key.
*/
public enum KeyPresentBehavior {
/**
* Return the index of any list element that compares as equal to the key. No guarantees are
* made as to which index is returned, if more than one element compares as equal to the key.
*/
ANY_PRESENT {
@Override
<E> int resultIndex(
Comparator<? super E> comparator, E key, List<? extends E> list, int foundIndex) {
return foundIndex;
}
},
/**
* Return the index of the last list element that compares as equal to the key.
*/
LAST_PRESENT {
@Override
<E> int resultIndex(
Comparator<? super E> comparator, E key, List<? extends E> list, int foundIndex) {
// Of course, we have to use binary search to find the precise
// breakpoint...
int lower = foundIndex;
int upper = list.size() - 1;
// Everything between lower and upper inclusive compares at >= 0.
while (lower < upper) {
int middle = (lower + upper + 1) >>> 1;
int c = comparator.compare(list.get(middle), key);
if (c > 0) {
upper = middle - 1;
} else { // c == 0
lower = middle;
}
}
return lower;
}
},
/**
* Return the index of the first list element that compares as equal to the key.
*/
FIRST_PRESENT {
@Override
<E> int resultIndex(
Comparator<? super E> comparator, E key, List<? extends E> list, int foundIndex) {
// Of course, we have to use binary search to find the precise
// breakpoint...
int lower = 0;
int upper = foundIndex;
// Of course, we have to use binary search to find the precise breakpoint...
// Everything between lower and upper inclusive compares at <= 0.
while (lower < upper) {
int middle = (lower + upper) >>> 1;
int c = comparator.compare(list.get(middle), key);
if (c < 0) {
lower = middle + 1;
} else { // c == 0
upper = middle;
}
}
return lower;
}
},
/**
* Return the index of the first list element that compares as greater than the key, or {@code
* list.size()} if there is no such element.
*/
FIRST_AFTER {
@Override
public <E> int resultIndex(
Comparator<? super E> comparator, E key, List<? extends E> list, int foundIndex) {
return LAST_PRESENT.resultIndex(comparator, key, list, foundIndex) + 1;
}
},
/**
* Return the index of the last list element that compares as less than the key, or {@code -1}
* if there is no such element.
*/
LAST_BEFORE {
@Override
public <E> int resultIndex(
Comparator<? super E> comparator, E key, List<? extends E> list, int foundIndex) {
return FIRST_PRESENT.resultIndex(comparator, key, list, foundIndex) - 1;
}
};
abstract <E> int resultIndex(
Comparator<? super E> comparator, E key, List<? extends E> list, int foundIndex);
}
/**
* A specification for which index to return if the list contains no elements that compare as
* equal to the key.
*/
public enum KeyAbsentBehavior {
/**
* Return the index of the next lower element in the list, or {@code -1} if there is no such
* element.
*/
NEXT_LOWER {
@Override
int resultIndex(int higherIndex) {
return higherIndex - 1;
}
},
/**
* Return the index of the next higher element in the list, or {@code list.size()} if there is
* no such element.
*/
NEXT_HIGHER {
@Override
public int resultIndex(int higherIndex) {
return higherIndex;
}
},
/**
* Return {@code ~insertionIndex}, where {@code insertionIndex} is defined as the point at
* which the key would be inserted into the list: the index of the next higher element in the
* list, or {@code list.size()} if there is no such element.
*
* <p>Note that the return value will be {@code >= 0} if and only if there is an element of the
* list that compares as equal to the key.
*
* <p>This is equivalent to the behavior of
* {@link java.util.Collections#binarySearch(List, Object)} when the key isn't present, since
* {@code ~insertionIndex} is equal to {@code -1 - insertionIndex}.
*/
INVERTED_INSERTION_INDEX {
@Override
public int resultIndex(int higherIndex) {
return ~higherIndex;
}
};
abstract int resultIndex(int higherIndex);
}
/**
* Searches the specified naturally ordered list for the specified object using the binary search
* algorithm.
*
* <p>Equivalent to {@link #binarySearch(List, Function, Object, Comparator, KeyPresentBehavior,
* KeyAbsentBehavior)} using {@link Ordering#natural}.
*/
public static <E extends Comparable> int binarySearch(List<? extends E> list, E e,
KeyPresentBehavior presentBehavior, KeyAbsentBehavior absentBehavior) {
checkNotNull(e);
return binarySearch(
list, checkNotNull(e), Ordering.natural(), presentBehavior, absentBehavior);
}
/**
* Binary searches the list for the specified key, using the specified key function.
*
* <p>Equivalent to {@link #binarySearch(List, Function, Object, Comparator, KeyPresentBehavior,
* KeyAbsentBehavior)} using {@link Ordering#natural}.
*/
public static <E, K extends Comparable> int binarySearch(List<E> list,
Function<? super E, K> keyFunction, @Nullable K key, KeyPresentBehavior presentBehavior,
KeyAbsentBehavior absentBehavior) {
return binarySearch(
list,
keyFunction,
key,
Ordering.natural(),
presentBehavior,
absentBehavior);
}
/**
* Binary searches the list for the specified key, using the specified key function.
*
* <p>Equivalent to
* {@link #binarySearch(List, Object, Comparator, KeyPresentBehavior, KeyAbsentBehavior)} using
* {@link Lists#transform(List, Function) Lists.transform(list, keyFunction)}.
*/
public static <E, K> int binarySearch(
List<E> list,
Function<? super E, K> keyFunction,
@Nullable K key,
Comparator<? super K> keyComparator,
KeyPresentBehavior presentBehavior,
KeyAbsentBehavior absentBehavior) {
return binarySearch(
Lists.transform(list, keyFunction), key, keyComparator, presentBehavior, absentBehavior);
}
/**
* Searches the specified list for the specified object using the binary search algorithm. The
* list must be sorted into ascending order according to the specified comparator (as by the
* {@link Collections#sort(List, Comparator) Collections.sort(List, Comparator)} method), prior
* to making this call. If it is not sorted, the results are undefined.
*
* <p>If there are elements in the list which compare as equal to the key, the choice of
* {@link KeyPresentBehavior} decides which index is returned. If no elements compare as equal to
* the key, the choice of {@link KeyAbsentBehavior} decides which index is returned.
*
* <p>This method runs in log(n) time on random-access lists, which offer near-constant-time
* access to each list element.
*
* @param list the list to be searched.
* @param key the value to be searched for.
* @param comparator the comparator by which the list is ordered.
* @param presentBehavior the specification for what to do if at least one element of the list
* compares as equal to the key.
* @param absentBehavior the specification for what to do if no elements of the list compare as
* equal to the key.
* @return the index determined by the {@code KeyPresentBehavior}, if the key is in the list;
* otherwise the index determined by the {@code KeyAbsentBehavior}.
*/
public static <E> int binarySearch(List<? extends E> list, @Nullable E key,
Comparator<? super E> comparator, KeyPresentBehavior presentBehavior,
KeyAbsentBehavior absentBehavior) {
checkNotNull(comparator);
checkNotNull(list);
checkNotNull(presentBehavior);
checkNotNull(absentBehavior);
if (!(list instanceof RandomAccess)) {
list = Lists.newArrayList(list);
}
// TODO(user): benchmark when it's best to do a linear search
int lower = 0;
int upper = list.size() - 1;
while (lower <= upper) {
int middle = (lower + upper) >>> 1;
int c = comparator.compare(key, list.get(middle));
if (c < 0) {
upper = middle - 1;
} else if (c > 0) {
lower = middle + 1;
} else {
return lower + presentBehavior.resultIndex(
comparator, key, list.subList(lower, upper + 1), middle - lower);
}
}
return absentBehavior.resultIndex(lower);
}
}
| Java |
/*
* Copyright (C) 2011 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.collect;
import com.google.common.annotations.Beta;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A set comprising zero or more {@linkplain Range#isEmpty nonempty},
* {@linkplain Range#isConnected(Range) disconnected} ranges of type {@code C}.
*
* <p>Implementations that choose to support the {@link #add(Range)} operation are required to
* ignore empty ranges and coalesce connected ranges. For example: <pre> {@code
*
* RangeSet<Integer> rangeSet = TreeRangeSet.create();
* rangeSet.add(Range.closed(1, 10)); // {[1, 10]}
* rangeSet.add(Range.closedOpen(11, 15)); // {[1, 10], [11, 15)}
* rangeSet.add(Range.open(15, 20)); // disconnected range; {[1, 10], [11, 20)}
* rangeSet.add(Range.openClosed(0, 0)); // empty range; {[1, 10], [11, 20)}
* rangeSet.remove(Range.open(5, 10)); // splits [1, 10]; {[1, 5], [10, 10], [11, 20)}}</pre>
*
* <p>Note that the behavior of {@link Range#isEmpty()} and {@link Range#isConnected(Range)} may
* not be as expected on discrete ranges. See the Javadoc of those methods for details.
*
* <p>For a {@link Set} whose contents are specified by a {@link Range}, see {@link ContiguousSet}.
*
* @author Kevin Bourrillion
* @author Louis Wasserman
* @since 14.0
*/
@Beta
public interface RangeSet<C extends Comparable> {
// Query methods
/**
* Determines whether any of this range set's member ranges contains {@code value}.
*/
boolean contains(C value);
/**
* Returns the unique range from this range set that {@linkplain Range#contains contains}
* {@code value}, or {@code null} if this range set does not contain {@code value}.
*/
Range<C> rangeContaining(C value);
/**
* Returns {@code true} if there exists a member range in this range set which
* {@linkplain Range#encloses encloses} the specified range.
*/
boolean encloses(Range<C> otherRange);
/**
* Returns {@code true} if for each member range in {@code other} there exists a member range in
* this range set which {@linkplain Range#encloses encloses} it. It follows that
* {@code this.contains(value)} whenever {@code other.contains(value)}. Returns {@code true} if
* {@code other} is empty.
*
* <p>This is equivalent to checking if this range set {@link #encloses} each of the ranges in
* {@code other}.
*/
boolean enclosesAll(RangeSet<C> other);
/**
* Returns {@code true} if this range set contains no ranges.
*/
boolean isEmpty();
/**
* Returns the minimal range which {@linkplain Range#encloses(Range) encloses} all ranges
* in this range set.
*
* @throws NoSuchElementException if this range set is {@linkplain #isEmpty() empty}
*/
Range<C> span();
// Views
/**
* Returns a view of the {@linkplain Range#isConnected disconnected} ranges that make up this
* range set. The returned set may be empty. The iterators returned by its
* {@link Iterable#iterator} method return the ranges in increasing order of lower bound
* (equivalently, of upper bound).
*/
Set<Range<C>> asRanges();
/**
* Returns a view of the complement of this {@code RangeSet}.
*
* <p>The returned view supports the {@link #add} operation if this {@code RangeSet} supports
* {@link #remove}, and vice versa.
*/
RangeSet<C> complement();
/**
* Returns a view of the intersection of this {@code RangeSet} with the specified range.
*
* <p>The returned view supports all optional operations supported by this {@code RangeSet}, with
* the caveat that an {@link IllegalArgumentException} is thrown on an attempt to
* {@linkplain #add(Range) add} any range not {@linkplain Range#encloses(Range) enclosed} by
* {@code view}.
*/
RangeSet<C> subRangeSet(Range<C> view);
// Modification
/**
* Adds the specified range to this {@code RangeSet} (optional operation). That is, for equal
* range sets a and b, the result of {@code a.add(range)} is that {@code a} will be the minimal
* range set for which both {@code a.enclosesAll(b)} and {@code a.encloses(range)}.
*
* <p>Note that {@code range} will be {@linkplain Range#span(Range) coalesced} with any ranges in
* the range set that are {@linkplain Range#isConnected(Range) connected} with it. Moreover,
* if {@code range} is empty, this is a no-op.
*
* @throws UnsupportedOperationException if this range set does not support the {@code add}
* operation
*/
void add(Range<C> range);
/**
* Removes the specified range from this {@code RangeSet} (optional operation). After this
* operation, if {@code range.contains(c)}, {@code this.contains(c)} will return {@code false}.
*
* <p>If {@code range} is empty, this is a no-op.
*
* @throws UnsupportedOperationException if this range set does not support the {@code remove}
* operation
*/
void remove(Range<C> range);
/**
* Removes all ranges from this {@code RangeSet} (optional operation). After this operation,
* {@code this.contains(c)} will return false for all {@code c}.
*
* <p>This is equivalent to {@code remove(Range.all())}.
*
* @throws UnsupportedOperationException if this range set does not support the {@code clear}
* operation
*/
void clear();
/**
* Adds all of the ranges from the specified range set to this range set (optional operation).
* After this operation, this range set is the minimal range set that
* {@linkplain #enclosesAll(RangeSet) encloses} both the original range set and {@code other}.
*
* <p>This is equivalent to calling {@link #add} on each of the ranges in {@code other} in turn.
*
* @throws UnsupportedOperationException if this range set does not support the {@code addAll}
* operation
*/
void addAll(RangeSet<C> other);
/**
* Removes all of the ranges from the specified range set from this range set (optional
* operation). After this operation, if {@code other.contains(c)}, {@code this.contains(c)} will
* return {@code false}.
*
* <p>This is equivalent to calling {@link #remove} on each of the ranges in {@code other} in
* turn.
*
* @throws UnsupportedOperationException if this range set does not support the {@code removeAll}
* operation
*/
void removeAll(RangeSet<C> other);
// Object methods
/**
* Returns {@code true} if {@code obj} is another {@code RangeSet} that contains the same ranges
* according to {@link Range#equals(Object)}.
*/
@Override
boolean equals(@Nullable Object obj);
/**
* Returns {@code asRanges().hashCode()}.
*/
@Override
int hashCode();
/**
* Returns a readable string representation of this range set. For example, if this
* {@code RangeSet} consisted of {@code Range.closed(1, 3)} and {@code Range.greaterThan(4)},
* this might return {@code " [1‥3](4‥+∞)}"}.
*/
@Override
String toString();
}
| Java |
/*
* Copyright (C) 2007 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.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
/**
* Basic implementation of the {@link ListMultimap} interface. It's a wrapper
* around {@link AbstractMapBasedMultimap} that converts the returned collections into
* {@code Lists}. The {@link #createCollection} method must return a {@code
* List}.
*
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
abstract class AbstractListMultimap<K, V>
extends AbstractMapBasedMultimap<K, V> implements ListMultimap<K, V> {
/**
* Creates a new multimap that uses the provided map.
*
* @param map place to store the mapping from each key to its corresponding
* values
*/
protected AbstractListMultimap(Map<K, Collection<V>> map) {
super(map);
}
@Override abstract List<V> createCollection();
@Override
List<V> createUnmodifiableEmptyCollection() {
return ImmutableList.of();
}
// Following Javadoc copied from ListMultimap.
/**
* {@inheritDoc}
*
* <p>Because the values for a given key may have duplicates and follow the
* insertion ordering, this method returns a {@link List}, instead of the
* {@link Collection} specified in the {@link Multimap} interface.
*/
@Override public List<V> get(@Nullable K key) {
return (List<V>) super.get(key);
}
/**
* {@inheritDoc}
*
* <p>Because the values for a given key may have duplicates and follow the
* insertion ordering, this method returns a {@link List}, instead of the
* {@link Collection} specified in the {@link Multimap} interface.
*/
@Override public List<V> removeAll(@Nullable Object key) {
return (List<V>) super.removeAll(key);
}
/**
* {@inheritDoc}
*
* <p>Because the values for a given key may have duplicates and follow the
* insertion ordering, this method returns a {@link List}, instead of the
* {@link Collection} specified in the {@link Multimap} interface.
*/
@Override public List<V> replaceValues(
@Nullable K key, Iterable<? extends V> values) {
return (List<V>) super.replaceValues(key, values);
}
/**
* Stores a key-value pair in the multimap.
*
* @param key key to store in the multimap
* @param value value to store in the multimap
* @return {@code true} always
*/
@Override public boolean put(@Nullable K key, @Nullable V value) {
return super.put(key, value);
}
/**
* {@inheritDoc}
*
* <p>Though the method signature doesn't say so explicitly, the returned map
* has {@link List} values.
*/
@Override public Map<K, Collection<V>> asMap() {
return super.asMap();
}
/**
* Compares the specified object to this multimap for equality.
*
* <p>Two {@code ListMultimap} instances are equal if, for each key, they
* contain the same values in the same order. If the value orderings disagree,
* the multimaps will not be considered equal.
*/
@Override public boolean equals(@Nullable Object object) {
return super.equals(object);
}
private static final long serialVersionUID = 6588350623831699109L;
}
| Java |
/*
* Copyright (C) 2009 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.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
/**
* An immutable {@link Table} with reliable user-specified iteration order.
* Does not permit null keys or values.
*
* <p><b>Note</b>: Although this class is not final, it cannot be subclassed as
* it has no public or protected constructors. Thus, instances of this class are
* guaranteed to be immutable.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained">
* immutable collections</a>.
*
* @author Gregory Kick
* @since 11.0
*/
@GwtCompatible
// TODO(gak): make serializable
public abstract class ImmutableTable<R, C, V> extends AbstractTable<R, C, V> {
private static final ImmutableTable<Object, Object, Object> EMPTY
= new SparseImmutableTable<Object, Object, Object>(
ImmutableList.<Cell<Object, Object, Object>>of(),
ImmutableSet.of(), ImmutableSet.of());
/** Returns an empty immutable table. */
@SuppressWarnings("unchecked")
public static <R, C, V> ImmutableTable<R, C, V> of() {
return (ImmutableTable<R, C, V>) EMPTY;
}
/** Returns an immutable table containing a single cell. */
public static <R, C, V> ImmutableTable<R, C, V> of(R rowKey,
C columnKey, V value) {
return new SingletonImmutableTable<R, C, V>(rowKey, columnKey, value);
}
/**
* Returns an immutable copy of the provided table.
*
* <p>The {@link Table#cellSet()} iteration order of the provided table
* determines the iteration ordering of all views in the returned table. Note
* that some views of the original table and the copied table may have
* different iteration orders. For more control over the ordering, create a
* {@link Builder} and call {@link Builder#orderRowsBy},
* {@link Builder#orderColumnsBy}, and {@link Builder#putAll}
*
* <p>Despite the method name, this method attempts to avoid actually copying
* the data when it is safe to do so. The exact circumstances under which a
* copy will or will not be performed are undocumented and subject to change.
*/
public static <R, C, V> ImmutableTable<R, C, V> copyOf(
Table<? extends R, ? extends C, ? extends V> table) {
if (table instanceof ImmutableTable) {
@SuppressWarnings("unchecked")
ImmutableTable<R, C, V> parameterizedTable
= (ImmutableTable<R, C, V>) table;
return parameterizedTable;
} else {
int size = table.size();
switch (size) {
case 0:
return of();
case 1:
Cell<? extends R, ? extends C, ? extends V> onlyCell
= Iterables.getOnlyElement(table.cellSet());
return ImmutableTable.<R, C, V>of(onlyCell.getRowKey(),
onlyCell.getColumnKey(), onlyCell.getValue());
default:
ImmutableSet.Builder<Cell<R, C, V>> cellSetBuilder
= ImmutableSet.builder();
for (Cell<? extends R, ? extends C, ? extends V> cell :
table.cellSet()) {
/*
* Must cast to be able to create a Cell<R, C, V> rather than a
* Cell<? extends R, ? extends C, ? extends V>
*/
cellSetBuilder.add(cellOf((R) cell.getRowKey(),
(C) cell.getColumnKey(), (V) cell.getValue()));
}
return RegularImmutableTable.forCells(cellSetBuilder.build());
}
}
}
/**
* Returns a new builder. The generated builder is equivalent to the builder
* created by the {@link Builder#ImmutableTable.Builder()} constructor.
*/
public static <R, C, V> Builder<R, C, V> builder() {
return new Builder<R, C, V>();
}
/**
* Verifies that {@code rowKey}, {@code columnKey} and {@code value} are
* non-null, and returns a new entry with those values.
*/
static <R, C, V> Cell<R, C, V> cellOf(R rowKey, C columnKey, V value) {
return Tables.immutableCell(checkNotNull(rowKey), checkNotNull(columnKey),
checkNotNull(value));
}
/**
* A builder for creating immutable table instances, especially {@code public
* static final} tables ("constant tables"). Example: <pre> {@code
*
* static final ImmutableTable<Integer, Character, String> SPREADSHEET =
* new ImmutableTable.Builder<Integer, Character, String>()
* .put(1, 'A', "foo")
* .put(1, 'B', "bar")
* .put(2, 'A', "baz")
* .build();}</pre>
*
* <p>By default, the order in which cells are added to the builder determines
* the iteration ordering of all views in the returned table, with {@link
* #putAll} following the {@link Table#cellSet()} iteration order. However, if
* {@link #orderRowsBy} or {@link #orderColumnsBy} is called, the views are
* sorted by the supplied comparators.
*
* For empty or single-cell immutable tables, {@link #of()} and
* {@link #of(Object, Object, Object)} are even more convenient.
*
* <p>Builder instances can be reused - it is safe to call {@link #build}
* multiple times to build multiple tables in series. Each table is a superset
* of the tables created before it.
*
* @since 11.0
*/
public static final class Builder<R, C, V> {
private final List<Cell<R, C, V>> cells = Lists.newArrayList();
private Comparator<? super R> rowComparator;
private Comparator<? super C> columnComparator;
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableTable#builder}.
*/
public Builder() {}
/**
* Specifies the ordering of the generated table's rows.
*/
public Builder<R, C, V> orderRowsBy(Comparator<? super R> rowComparator) {
this.rowComparator = checkNotNull(rowComparator);
return this;
}
/**
* Specifies the ordering of the generated table's columns.
*/
public Builder<R, C, V> orderColumnsBy(
Comparator<? super C> columnComparator) {
this.columnComparator = checkNotNull(columnComparator);
return this;
}
/**
* Associates the ({@code rowKey}, {@code columnKey}) pair with {@code
* value} in the built table. Duplicate key pairs are not allowed and will
* cause {@link #build} to fail.
*/
public Builder<R, C, V> put(R rowKey, C columnKey, V value) {
cells.add(cellOf(rowKey, columnKey, value));
return this;
}
/**
* Adds the given {@code cell} to the table, making it immutable if
* necessary. Duplicate key pairs are not allowed and will cause {@link
* #build} to fail.
*/
public Builder<R, C, V> put(
Cell<? extends R, ? extends C, ? extends V> cell) {
if (cell instanceof Tables.ImmutableCell) {
checkNotNull(cell.getRowKey());
checkNotNull(cell.getColumnKey());
checkNotNull(cell.getValue());
@SuppressWarnings("unchecked") // all supported methods are covariant
Cell<R, C, V> immutableCell = (Cell<R, C, V>) cell;
cells.add(immutableCell);
} else {
put(cell.getRowKey(), cell.getColumnKey(), cell.getValue());
}
return this;
}
/**
* Associates all of the given table's keys and values in the built table.
* Duplicate row key column key pairs are not allowed, and will cause
* {@link #build} to fail.
*
* @throws NullPointerException if any key or value in {@code table} is null
*/
public Builder<R, C, V> putAll(
Table<? extends R, ? extends C, ? extends V> table) {
for (Cell<? extends R, ? extends C, ? extends V> cell : table.cellSet()) {
put(cell);
}
return this;
}
/**
* Returns a newly-created immutable table.
*
* @throws IllegalArgumentException if duplicate key pairs were added
*/
public ImmutableTable<R, C, V> build() {
int size = cells.size();
switch (size) {
case 0:
return of();
case 1:
return new SingletonImmutableTable<R, C, V>(
Iterables.getOnlyElement(cells));
default:
return RegularImmutableTable.forCells(
cells, rowComparator, columnComparator);
}
}
}
ImmutableTable() {}
@Override public ImmutableSet<Cell<R, C, V>> cellSet() {
return (ImmutableSet<Cell<R, C, V>>) super.cellSet();
}
@Override
abstract ImmutableSet<Cell<R, C, V>> createCellSet();
@Override
final UnmodifiableIterator<Cell<R, C, V>> cellIterator() {
throw new AssertionError("should never be called");
}
@Override
public ImmutableCollection<V> values() {
return (ImmutableCollection<V>) super.values();
}
@Override
abstract ImmutableCollection<V> createValues();
@Override
final Iterator<V> valuesIterator() {
throw new AssertionError("should never be called");
}
/**
* {@inheritDoc}
*
* @throws NullPointerException if {@code columnKey} is {@code null}
*/
@Override public ImmutableMap<R, V> column(C columnKey) {
checkNotNull(columnKey);
return Objects.firstNonNull(
(ImmutableMap<R, V>) columnMap().get(columnKey),
ImmutableMap.<R, V>of());
}
@Override public ImmutableSet<C> columnKeySet() {
return columnMap().keySet();
}
/**
* {@inheritDoc}
*
* <p>The value {@code Map<R, V>} instances in the returned map are
* {@link ImmutableMap} instances as well.
*/
@Override public abstract ImmutableMap<C, Map<R, V>> columnMap();
/**
* {@inheritDoc}
*
* @throws NullPointerException if {@code rowKey} is {@code null}
*/
@Override public ImmutableMap<C, V> row(R rowKey) {
checkNotNull(rowKey);
return Objects.firstNonNull(
(ImmutableMap<C, V>) rowMap().get(rowKey),
ImmutableMap.<C, V>of());
}
@Override public ImmutableSet<R> rowKeySet() {
return rowMap().keySet();
}
/**
* {@inheritDoc}
*
* <p>The value {@code Map<C, V>} instances in the returned map are
* {@link ImmutableMap} instances as well.
*/
@Override public abstract ImmutableMap<R, Map<C, V>> rowMap();
@Override
public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) {
return get(rowKey, columnKey) != null;
}
@Override
public boolean containsValue(@Nullable Object value) {
return values().contains(value);
}
/**
* Guaranteed to throw an exception and leave the table unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated @Override public final void clear() {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the table unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated @Override public final V put(R rowKey, C columnKey, V value) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the table unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated @Override public final void putAll(
Table<? extends R, ? extends C, ? extends V> table) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the table unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated @Override public final V remove(Object rowKey, Object columnKey) {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright (C) 2007 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.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import java.io.Serializable;
import javax.annotation.Nullable;
/**
* An ordering that orders elements by applying an order to the result of a
* function on those elements.
*/
@GwtCompatible(serializable = true)
final class ByFunctionOrdering<F, T>
extends Ordering<F> implements Serializable {
final Function<F, ? extends T> function;
final Ordering<T> ordering;
ByFunctionOrdering(
Function<F, ? extends T> function, Ordering<T> ordering) {
this.function = checkNotNull(function);
this.ordering = checkNotNull(ordering);
}
@Override public int compare(F left, F right) {
return ordering.compare(function.apply(left), function.apply(right));
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof ByFunctionOrdering) {
ByFunctionOrdering<?, ?> that = (ByFunctionOrdering<?, ?>) object;
return this.function.equals(that.function)
&& this.ordering.equals(that.ordering);
}
return false;
}
@Override public int hashCode() {
return Objects.hashCode(function, ordering);
}
@Override public String toString() {
return ordering + ".onResultOf(" + function + ")";
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2007 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.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.Set;
import javax.annotation.Nullable;
/**
* An empty immutable set.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(serializable = true, emulated = true)
final class EmptyImmutableSet extends ImmutableSet<Object> {
static final EmptyImmutableSet INSTANCE = new EmptyImmutableSet();
private EmptyImmutableSet() {}
@Override
public int size() {
return 0;
}
@Override public boolean isEmpty() {
return true;
}
@Override public boolean contains(@Nullable Object target) {
return false;
}
@Override public boolean containsAll(Collection<?> targets) {
return targets.isEmpty();
}
@Override public UnmodifiableIterator<Object> iterator() {
return Iterators.emptyIterator();
}
@Override boolean isPartialView() {
return false;
}
@Override
int copyIntoArray(Object[] dst, int offset) {
return offset;
}
@Override
public ImmutableList<Object> asList() {
return ImmutableList.of();
}
@Override public boolean equals(@Nullable Object object) {
if (object instanceof Set) {
Set<?> that = (Set<?>) object;
return that.isEmpty();
}
return false;
}
@Override public final int hashCode() {
return 0;
}
@Override boolean isHashCodeFast() {
return true;
}
@Override public String toString() {
return "[]";
}
Object readResolve() {
return INSTANCE; // preserve singleton property
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2012 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.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.util.Iterator;
/**
* An iterator that transforms a backing iterator; for internal use. This avoids
* the object overhead of constructing a {@link Function} for internal methods.
*
* @author Louis Wasserman
*/
@GwtCompatible
abstract class TransformedIterator<F, T> implements Iterator<T> {
final Iterator<? extends F> backingIterator;
TransformedIterator(Iterator<? extends F> backingIterator) {
this.backingIterator = checkNotNull(backingIterator);
}
abstract T transform(F from);
@Override
public final boolean hasNext() {
return backingIterator.hasNext();
}
@Override
public final T next() {
return transform(backingIterator.next());
}
@Override
public final void remove() {
backingIterator.remove();
}
}
| Java |
/*
* Copyright (C) 2009 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.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Equivalence;
import com.google.common.base.Ticker;
import com.google.common.collect.GenericMapMaker.NullListener;
import com.google.common.collect.MapMaker.RemovalCause;
import com.google.common.collect.MapMaker.RemovalListener;
import com.google.common.collect.MapMaker.RemovalNotification;
import com.google.common.primitives.Ints;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractQueue;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
/**
* The concurrent hash map implementation built by {@link MapMaker}.
*
* <p>This implementation is heavily derived from revision 1.96 of <a
* href="http://tinyurl.com/ConcurrentHashMap">ConcurrentHashMap.java</a>.
*
* @author Bob Lee
* @author Charles Fry
* @author Doug Lea ({@code ConcurrentHashMap})
*/
class MapMakerInternalMap<K, V>
extends AbstractMap<K, V> implements ConcurrentMap<K, V>, Serializable {
/*
* The basic strategy is to subdivide the table among Segments, each of which itself is a
* concurrently readable hash table. The map supports non-blocking reads and concurrent writes
* across different segments.
*
* If a maximum size is specified, a best-effort bounding is performed per segment, using a
* page-replacement algorithm to determine which entries to evict when the capacity has been
* exceeded.
*
* The page replacement algorithm's data structures are kept casually consistent with the map. The
* ordering of writes to a segment is sequentially consistent. An update to the map and recording
* of reads may not be immediately reflected on the algorithm's data structures. These structures
* are guarded by a lock and operations are applied in batches to avoid lock contention. The
* penalty of applying the batches is spread across threads so that the amortized cost is slightly
* higher than performing just the operation without enforcing the capacity constraint.
*
* This implementation uses a per-segment queue to record a memento of the additions, removals,
* and accesses that were performed on the map. The queue is drained on writes and when it exceeds
* its capacity threshold.
*
* The Least Recently Used page replacement algorithm was chosen due to its simplicity, high hit
* rate, and ability to be implemented with O(1) time complexity. The initial LRU implementation
* operates per-segment rather than globally for increased implementation simplicity. We expect
* the cache hit rate to be similar to that of a global LRU algorithm.
*/
// Constants
/**
* The maximum capacity, used if a higher value is implicitly specified by either of the
* constructors with arguments. MUST be a power of two <= 1<<30 to ensure that entries are
* indexable using ints.
*/
static final int MAXIMUM_CAPACITY = Ints.MAX_POWER_OF_TWO;
/** The maximum number of segments to allow; used to bound constructor arguments. */
static final int MAX_SEGMENTS = 1 << 16; // slightly conservative
/** Number of (unsynchronized) retries in the containsValue method. */
static final int CONTAINS_VALUE_RETRIES = 3;
/**
* Number of cache access operations that can be buffered per segment before the cache's recency
* ordering information is updated. This is used to avoid lock contention by recording a memento
* of reads and delaying a lock acquisition until the threshold is crossed or a mutation occurs.
*
* <p>This must be a (2^n)-1 as it is used as a mask.
*/
static final int DRAIN_THRESHOLD = 0x3F;
/**
* Maximum number of entries to be drained in a single cleanup run. This applies independently to
* the cleanup queue and both reference queues.
*/
// TODO(fry): empirically optimize this
static final int DRAIN_MAX = 16;
static final long CLEANUP_EXECUTOR_DELAY_SECS = 60;
// Fields
private static final Logger logger = Logger.getLogger(MapMakerInternalMap.class.getName());
/**
* Mask value for indexing into segments. The upper bits of a key's hash code are used to choose
* the segment.
*/
final transient int segmentMask;
/**
* Shift value for indexing within segments. Helps prevent entries that end up in the same segment
* from also ending up in the same bucket.
*/
final transient int segmentShift;
/** The segments, each of which is a specialized hash table. */
final transient Segment<K, V>[] segments;
/** The concurrency level. */
final int concurrencyLevel;
/** Strategy for comparing keys. */
final Equivalence<Object> keyEquivalence;
/** Strategy for comparing values. */
final Equivalence<Object> valueEquivalence;
/** Strategy for referencing keys. */
final Strength keyStrength;
/** Strategy for referencing values. */
final Strength valueStrength;
/** The maximum size of this map. MapMaker.UNSET_INT if there is no maximum. */
final int maximumSize;
/** How long after the last access to an entry the map will retain that entry. */
final long expireAfterAccessNanos;
/** How long after the last write to an entry the map will retain that entry. */
final long expireAfterWriteNanos;
/** Entries waiting to be consumed by the removal listener. */
// TODO(fry): define a new type which creates event objects and automates the clear logic
final Queue<RemovalNotification<K, V>> removalNotificationQueue;
/**
* A listener that is invoked when an entry is removed due to expiration or garbage collection of
* soft/weak entries.
*/
final RemovalListener<K, V> removalListener;
/** Factory used to create new entries. */
final transient EntryFactory entryFactory;
/** Measures time in a testable way. */
final Ticker ticker;
/**
* Creates a new, empty map with the specified strategy, initial capacity and concurrency level.
*/
MapMakerInternalMap(MapMaker builder) {
concurrencyLevel = Math.min(builder.getConcurrencyLevel(), MAX_SEGMENTS);
keyStrength = builder.getKeyStrength();
valueStrength = builder.getValueStrength();
keyEquivalence = builder.getKeyEquivalence();
valueEquivalence = valueStrength.defaultEquivalence();
maximumSize = builder.maximumSize;
expireAfterAccessNanos = builder.getExpireAfterAccessNanos();
expireAfterWriteNanos = builder.getExpireAfterWriteNanos();
entryFactory = EntryFactory.getFactory(keyStrength, expires(), evictsBySize());
ticker = builder.getTicker();
removalListener = builder.getRemovalListener();
removalNotificationQueue = (removalListener == NullListener.INSTANCE)
? MapMakerInternalMap.<RemovalNotification<K, V>>discardingQueue()
: new ConcurrentLinkedQueue<RemovalNotification<K, V>>();
int initialCapacity = Math.min(builder.getInitialCapacity(), MAXIMUM_CAPACITY);
if (evictsBySize()) {
initialCapacity = Math.min(initialCapacity, maximumSize);
}
// Find power-of-two sizes best matching arguments. Constraints:
// (segmentCount <= maximumSize)
// && (concurrencyLevel > maximumSize || segmentCount > concurrencyLevel)
int segmentShift = 0;
int segmentCount = 1;
while (segmentCount < concurrencyLevel
&& (!evictsBySize() || segmentCount * 2 <= maximumSize)) {
++segmentShift;
segmentCount <<= 1;
}
this.segmentShift = 32 - segmentShift;
segmentMask = segmentCount - 1;
this.segments = newSegmentArray(segmentCount);
int segmentCapacity = initialCapacity / segmentCount;
if (segmentCapacity * segmentCount < initialCapacity) {
++segmentCapacity;
}
int segmentSize = 1;
while (segmentSize < segmentCapacity) {
segmentSize <<= 1;
}
if (evictsBySize()) {
// Ensure sum of segment max sizes = overall max size
int maximumSegmentSize = maximumSize / segmentCount + 1;
int remainder = maximumSize % segmentCount;
for (int i = 0; i < this.segments.length; ++i) {
if (i == remainder) {
maximumSegmentSize--;
}
this.segments[i] =
createSegment(segmentSize, maximumSegmentSize);
}
} else {
for (int i = 0; i < this.segments.length; ++i) {
this.segments[i] =
createSegment(segmentSize, MapMaker.UNSET_INT);
}
}
}
boolean evictsBySize() {
return maximumSize != MapMaker.UNSET_INT;
}
boolean expires() {
return expiresAfterWrite() || expiresAfterAccess();
}
boolean expiresAfterWrite() {
return expireAfterWriteNanos > 0;
}
boolean expiresAfterAccess() {
return expireAfterAccessNanos > 0;
}
boolean usesKeyReferences() {
return keyStrength != Strength.STRONG;
}
boolean usesValueReferences() {
return valueStrength != Strength.STRONG;
}
enum Strength {
/*
* TODO(kevinb): If we strongly reference the value and aren't computing, we needn't wrap the
* value. This could save ~8 bytes per entry.
*/
STRONG {
@Override
<K, V> ValueReference<K, V> referenceValue(
Segment<K, V> segment, ReferenceEntry<K, V> entry, V value) {
return new StrongValueReference<K, V>(value);
}
@Override
Equivalence<Object> defaultEquivalence() {
return Equivalence.equals();
}
},
SOFT {
@Override
<K, V> ValueReference<K, V> referenceValue(
Segment<K, V> segment, ReferenceEntry<K, V> entry, V value) {
return new SoftValueReference<K, V>(segment.valueReferenceQueue, value, entry);
}
@Override
Equivalence<Object> defaultEquivalence() {
return Equivalence.identity();
}
},
WEAK {
@Override
<K, V> ValueReference<K, V> referenceValue(
Segment<K, V> segment, ReferenceEntry<K, V> entry, V value) {
return new WeakValueReference<K, V>(segment.valueReferenceQueue, value, entry);
}
@Override
Equivalence<Object> defaultEquivalence() {
return Equivalence.identity();
}
};
/**
* Creates a reference for the given value according to this value strength.
*/
abstract <K, V> ValueReference<K, V> referenceValue(
Segment<K, V> segment, ReferenceEntry<K, V> entry, V value);
/**
* Returns the default equivalence strategy used to compare and hash keys or values referenced
* at this strength. This strategy will be used unless the user explicitly specifies an
* alternate strategy.
*/
abstract Equivalence<Object> defaultEquivalence();
}
/**
* Creates new entries.
*/
enum EntryFactory {
STRONG {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new StrongEntry<K, V>(key, hash, next);
}
},
STRONG_EXPIRABLE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new StrongExpirableEntry<K, V>(key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyExpirableEntry(original, newEntry);
return newEntry;
}
},
STRONG_EVICTABLE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new StrongEvictableEntry<K, V>(key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyEvictableEntry(original, newEntry);
return newEntry;
}
},
STRONG_EXPIRABLE_EVICTABLE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new StrongExpirableEvictableEntry<K, V>(key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyExpirableEntry(original, newEntry);
copyEvictableEntry(original, newEntry);
return newEntry;
}
},
WEAK {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new WeakEntry<K, V>(segment.keyReferenceQueue, key, hash, next);
}
},
WEAK_EXPIRABLE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new WeakExpirableEntry<K, V>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyExpirableEntry(original, newEntry);
return newEntry;
}
},
WEAK_EVICTABLE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new WeakEvictableEntry<K, V>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyEvictableEntry(original, newEntry);
return newEntry;
}
},
WEAK_EXPIRABLE_EVICTABLE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new WeakExpirableEvictableEntry<K, V>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyExpirableEntry(original, newEntry);
copyEvictableEntry(original, newEntry);
return newEntry;
}
};
/**
* Masks used to compute indices in the following table.
*/
static final int EXPIRABLE_MASK = 1;
static final int EVICTABLE_MASK = 2;
/**
* Look-up table for factories. First dimension is the reference type. The second dimension is
* the result of OR-ing the feature masks.
*/
static final EntryFactory[][] factories = {
{ STRONG, STRONG_EXPIRABLE, STRONG_EVICTABLE, STRONG_EXPIRABLE_EVICTABLE },
{}, // no support for SOFT keys
{ WEAK, WEAK_EXPIRABLE, WEAK_EVICTABLE, WEAK_EXPIRABLE_EVICTABLE }
};
static EntryFactory getFactory(Strength keyStrength, boolean expireAfterWrite,
boolean evictsBySize) {
int flags = (expireAfterWrite ? EXPIRABLE_MASK : 0) | (evictsBySize ? EVICTABLE_MASK : 0);
return factories[keyStrength.ordinal()][flags];
}
/**
* Creates a new entry.
*
* @param segment to create the entry for
* @param key of the entry
* @param hash of the key
* @param next entry in the same bucket
*/
abstract <K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next);
/**
* Copies an entry, assigning it a new {@code next} entry.
*
* @param original the entry to copy
* @param newNext entry in the same bucket
*/
@GuardedBy("Segment.this")
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
return newEntry(segment, original.getKey(), original.getHash(), newNext);
}
@GuardedBy("Segment.this")
<K, V> void copyExpirableEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newEntry) {
// TODO(fry): when we link values instead of entries this method can go
// away, as can connectExpirables, nullifyExpirable.
newEntry.setExpirationTime(original.getExpirationTime());
connectExpirables(original.getPreviousExpirable(), newEntry);
connectExpirables(newEntry, original.getNextExpirable());
nullifyExpirable(original);
}
@GuardedBy("Segment.this")
<K, V> void copyEvictableEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newEntry) {
// TODO(fry): when we link values instead of entries this method can go
// away, as can connectEvictables, nullifyEvictable.
connectEvictables(original.getPreviousEvictable(), newEntry);
connectEvictables(newEntry, original.getNextEvictable());
nullifyEvictable(original);
}
}
/**
* A reference to a value.
*/
interface ValueReference<K, V> {
/**
* Gets the value. Does not block or throw exceptions.
*/
V get();
/**
* Waits for a value that may still be computing. Unlike get(), this method can block (in the
* case of FutureValueReference).
*
* @throws ExecutionException if the computing thread throws an exception
*/
V waitForValue() throws ExecutionException;
/**
* Returns the entry associated with this value reference, or {@code null} if this value
* reference is independent of any entry.
*/
ReferenceEntry<K, V> getEntry();
/**
* Creates a copy of this reference for the given entry.
*
* <p>{@code value} may be null only for a loading reference.
*/
ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, @Nullable V value, ReferenceEntry<K, V> entry);
/**
* Clears this reference object.
*
* @param newValue the new value reference which will replace this one; this is only used during
* computation to immediately notify blocked threads of the new value
*/
void clear(@Nullable ValueReference<K, V> newValue);
/**
* Returns {@code true} if the value type is a computing reference (regardless of whether or not
* computation has completed). This is necessary to distiguish between partially-collected
* entries and computing entries, which need to be cleaned up differently.
*/
boolean isComputingReference();
}
/**
* Placeholder. Indicates that the value hasn't been set yet.
*/
static final ValueReference<Object, Object> UNSET = new ValueReference<Object, Object>() {
@Override
public Object get() {
return null;
}
@Override
public ReferenceEntry<Object, Object> getEntry() {
return null;
}
@Override
public ValueReference<Object, Object> copyFor(ReferenceQueue<Object> queue,
@Nullable Object value, ReferenceEntry<Object, Object> entry) {
return this;
}
@Override
public boolean isComputingReference() {
return false;
}
@Override
public Object waitForValue() {
return null;
}
@Override
public void clear(ValueReference<Object, Object> newValue) {}
};
/**
* Singleton placeholder that indicates a value is being computed.
*/
@SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value
static <K, V> ValueReference<K, V> unset() {
return (ValueReference<K, V>) UNSET;
}
/**
* An entry in a reference map.
*
* Entries in the map can be in the following states:
*
* Valid:
* - Live: valid key/value are set
* - Computing: computation is pending
*
* Invalid:
* - Expired: time expired (key/value may still be set)
* - Collected: key/value was partially collected, but not yet cleaned up
*/
interface ReferenceEntry<K, V> {
/**
* Gets the value reference from this entry.
*/
ValueReference<K, V> getValueReference();
/**
* Sets the value reference for this entry.
*/
void setValueReference(ValueReference<K, V> valueReference);
/**
* Gets the next entry in the chain.
*/
ReferenceEntry<K, V> getNext();
/**
* Gets the entry's hash.
*/
int getHash();
/**
* Gets the key for this entry.
*/
K getKey();
/*
* Used by entries that are expirable. Expirable entries are maintained in a doubly-linked list.
* New entries are added at the tail of the list at write time; stale entries are expired from
* the head of the list.
*/
/**
* Gets the entry expiration time in ns.
*/
long getExpirationTime();
/**
* Sets the entry expiration time in ns.
*/
void setExpirationTime(long time);
/**
* Gets the next entry in the recency list.
*/
ReferenceEntry<K, V> getNextExpirable();
/**
* Sets the next entry in the recency list.
*/
void setNextExpirable(ReferenceEntry<K, V> next);
/**
* Gets the previous entry in the recency list.
*/
ReferenceEntry<K, V> getPreviousExpirable();
/**
* Sets the previous entry in the recency list.
*/
void setPreviousExpirable(ReferenceEntry<K, V> previous);
/*
* Implemented by entries that are evictable. Evictable entries are maintained in a
* doubly-linked list. New entries are added at the tail of the list at write time and stale
* entries are expired from the head of the list.
*/
/**
* Gets the next entry in the recency list.
*/
ReferenceEntry<K, V> getNextEvictable();
/**
* Sets the next entry in the recency list.
*/
void setNextEvictable(ReferenceEntry<K, V> next);
/**
* Gets the previous entry in the recency list.
*/
ReferenceEntry<K, V> getPreviousEvictable();
/**
* Sets the previous entry in the recency list.
*/
void setPreviousEvictable(ReferenceEntry<K, V> previous);
}
private enum NullEntry implements ReferenceEntry<Object, Object> {
INSTANCE;
@Override
public ValueReference<Object, Object> getValueReference() {
return null;
}
@Override
public void setValueReference(ValueReference<Object, Object> valueReference) {}
@Override
public ReferenceEntry<Object, Object> getNext() {
return null;
}
@Override
public int getHash() {
return 0;
}
@Override
public Object getKey() {
return null;
}
@Override
public long getExpirationTime() {
return 0;
}
@Override
public void setExpirationTime(long time) {}
@Override
public ReferenceEntry<Object, Object> getNextExpirable() {
return this;
}
@Override
public void setNextExpirable(ReferenceEntry<Object, Object> next) {}
@Override
public ReferenceEntry<Object, Object> getPreviousExpirable() {
return this;
}
@Override
public void setPreviousExpirable(ReferenceEntry<Object, Object> previous) {}
@Override
public ReferenceEntry<Object, Object> getNextEvictable() {
return this;
}
@Override
public void setNextEvictable(ReferenceEntry<Object, Object> next) {}
@Override
public ReferenceEntry<Object, Object> getPreviousEvictable() {
return this;
}
@Override
public void setPreviousEvictable(ReferenceEntry<Object, Object> previous) {}
}
abstract static class AbstractReferenceEntry<K, V> implements ReferenceEntry<K, V> {
@Override
public ValueReference<K, V> getValueReference() {
throw new UnsupportedOperationException();
}
@Override
public void setValueReference(ValueReference<K, V> valueReference) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNext() {
throw new UnsupportedOperationException();
}
@Override
public int getHash() {
throw new UnsupportedOperationException();
}
@Override
public K getKey() {
throw new UnsupportedOperationException();
}
@Override
public long getExpirationTime() {
throw new UnsupportedOperationException();
}
@Override
public void setExpirationTime(long time) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextExpirable() {
throw new UnsupportedOperationException();
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextEvictable() {
throw new UnsupportedOperationException();
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
}
@SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value
static <K, V> ReferenceEntry<K, V> nullEntry() {
return (ReferenceEntry<K, V>) NullEntry.INSTANCE;
}
static final Queue<? extends Object> DISCARDING_QUEUE = new AbstractQueue<Object>() {
@Override
public boolean offer(Object o) {
return true;
}
@Override
public Object peek() {
return null;
}
@Override
public Object poll() {
return null;
}
@Override
public int size() {
return 0;
}
@Override
public Iterator<Object> iterator() {
return Iterators.emptyIterator();
}
};
/**
* Queue that discards all elements.
*/
@SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value
static <E> Queue<E> discardingQueue() {
return (Queue) DISCARDING_QUEUE;
}
/*
* Note: All of this duplicate code sucks, but it saves a lot of memory. If only Java had mixins!
* To maintain this code, make a change for the strong reference type. Then, cut and paste, and
* replace "Strong" with "Soft" or "Weak" within the pasted text. The primary difference is that
* strong entries store the key reference directly while soft and weak entries delegate to their
* respective superclasses.
*/
/**
* Used for strongly-referenced keys.
*/
static class StrongEntry<K, V> implements ReferenceEntry<K, V> {
final K key;
StrongEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
this.key = key;
this.hash = hash;
this.next = next;
}
@Override
public K getKey() {
return this.key;
}
// null expiration
@Override
public long getExpirationTime() {
throw new UnsupportedOperationException();
}
@Override
public void setExpirationTime(long time) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextExpirable() {
throw new UnsupportedOperationException();
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
// null eviction
@Override
public ReferenceEntry<K, V> getNextEvictable() {
throw new UnsupportedOperationException();
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
// The code below is exactly the same for each entry type.
final int hash;
final ReferenceEntry<K, V> next;
volatile ValueReference<K, V> valueReference = unset();
@Override
public ValueReference<K, V> getValueReference() {
return valueReference;
}
@Override
public void setValueReference(ValueReference<K, V> valueReference) {
ValueReference<K, V> previous = this.valueReference;
this.valueReference = valueReference;
previous.clear(valueReference);
}
@Override
public int getHash() {
return hash;
}
@Override
public ReferenceEntry<K, V> getNext() {
return next;
}
}
static final class StrongExpirableEntry<K, V> extends StrongEntry<K, V>
implements ReferenceEntry<K, V> {
StrongExpirableEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(key, hash, next);
}
// The code below is exactly the same for each expirable entry type.
volatile long time = Long.MAX_VALUE;
@Override
public long getExpirationTime() {
return time;
}
@Override
public void setExpirationTime(long time) {
this.time = time;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextExpirable() {
return nextExpirable;
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
this.nextExpirable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
return previousExpirable;
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
this.previousExpirable = previous;
}
}
static final class StrongEvictableEntry<K, V>
extends StrongEntry<K, V> implements ReferenceEntry<K, V> {
StrongEvictableEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(key, hash, next);
}
// The code below is exactly the same for each evictable entry type.
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextEvictable() {
return nextEvictable;
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
this.nextEvictable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
return previousEvictable;
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
this.previousEvictable = previous;
}
}
static final class StrongExpirableEvictableEntry<K, V>
extends StrongEntry<K, V> implements ReferenceEntry<K, V> {
StrongExpirableEvictableEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(key, hash, next);
}
// The code below is exactly the same for each expirable entry type.
volatile long time = Long.MAX_VALUE;
@Override
public long getExpirationTime() {
return time;
}
@Override
public void setExpirationTime(long time) {
this.time = time;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextExpirable() {
return nextExpirable;
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
this.nextExpirable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
return previousExpirable;
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
this.previousExpirable = previous;
}
// The code below is exactly the same for each evictable entry type.
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextEvictable() {
return nextEvictable;
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
this.nextEvictable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
return previousEvictable;
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
this.previousEvictable = previous;
}
}
/**
* Used for softly-referenced keys.
*/
static class SoftEntry<K, V> extends SoftReference<K> implements ReferenceEntry<K, V> {
SoftEntry(ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(key, queue);
this.hash = hash;
this.next = next;
}
@Override
public K getKey() {
return get();
}
// null expiration
@Override
public long getExpirationTime() {
throw new UnsupportedOperationException();
}
@Override
public void setExpirationTime(long time) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextExpirable() {
throw new UnsupportedOperationException();
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
// null eviction
@Override
public ReferenceEntry<K, V> getNextEvictable() {
throw new UnsupportedOperationException();
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
// The code below is exactly the same for each entry type.
final int hash;
final ReferenceEntry<K, V> next;
volatile ValueReference<K, V> valueReference = unset();
@Override
public ValueReference<K, V> getValueReference() {
return valueReference;
}
@Override
public void setValueReference(ValueReference<K, V> valueReference) {
ValueReference<K, V> previous = this.valueReference;
this.valueReference = valueReference;
previous.clear(valueReference);
}
@Override
public int getHash() {
return hash;
}
@Override
public ReferenceEntry<K, V> getNext() {
return next;
}
}
static final class SoftExpirableEntry<K, V>
extends SoftEntry<K, V> implements ReferenceEntry<K, V> {
SoftExpirableEntry(
ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each expirable entry type.
volatile long time = Long.MAX_VALUE;
@Override
public long getExpirationTime() {
return time;
}
@Override
public void setExpirationTime(long time) {
this.time = time;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextExpirable() {
return nextExpirable;
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
this.nextExpirable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
return previousExpirable;
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
this.previousExpirable = previous;
}
}
static final class SoftEvictableEntry<K, V>
extends SoftEntry<K, V> implements ReferenceEntry<K, V> {
SoftEvictableEntry(
ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each evictable entry type.
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextEvictable() {
return nextEvictable;
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
this.nextEvictable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
return previousEvictable;
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
this.previousEvictable = previous;
}
}
static final class SoftExpirableEvictableEntry<K, V>
extends SoftEntry<K, V> implements ReferenceEntry<K, V> {
SoftExpirableEvictableEntry(
ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each expirable entry type.
volatile long time = Long.MAX_VALUE;
@Override
public long getExpirationTime() {
return time;
}
@Override
public void setExpirationTime(long time) {
this.time = time;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextExpirable() {
return nextExpirable;
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
this.nextExpirable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
return previousExpirable;
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
this.previousExpirable = previous;
}
// The code below is exactly the same for each evictable entry type.
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextEvictable() {
return nextEvictable;
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
this.nextEvictable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
return previousEvictable;
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
this.previousEvictable = previous;
}
}
/**
* Used for weakly-referenced keys.
*/
static class WeakEntry<K, V> extends WeakReference<K> implements ReferenceEntry<K, V> {
WeakEntry(ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(key, queue);
this.hash = hash;
this.next = next;
}
@Override
public K getKey() {
return get();
}
// null expiration
@Override
public long getExpirationTime() {
throw new UnsupportedOperationException();
}
@Override
public void setExpirationTime(long time) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextExpirable() {
throw new UnsupportedOperationException();
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
// null eviction
@Override
public ReferenceEntry<K, V> getNextEvictable() {
throw new UnsupportedOperationException();
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
// The code below is exactly the same for each entry type.
final int hash;
final ReferenceEntry<K, V> next;
volatile ValueReference<K, V> valueReference = unset();
@Override
public ValueReference<K, V> getValueReference() {
return valueReference;
}
@Override
public void setValueReference(ValueReference<K, V> valueReference) {
ValueReference<K, V> previous = this.valueReference;
this.valueReference = valueReference;
previous.clear(valueReference);
}
@Override
public int getHash() {
return hash;
}
@Override
public ReferenceEntry<K, V> getNext() {
return next;
}
}
static final class WeakExpirableEntry<K, V>
extends WeakEntry<K, V> implements ReferenceEntry<K, V> {
WeakExpirableEntry(
ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each expirable entry type.
volatile long time = Long.MAX_VALUE;
@Override
public long getExpirationTime() {
return time;
}
@Override
public void setExpirationTime(long time) {
this.time = time;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextExpirable() {
return nextExpirable;
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
this.nextExpirable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
return previousExpirable;
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
this.previousExpirable = previous;
}
}
static final class WeakEvictableEntry<K, V>
extends WeakEntry<K, V> implements ReferenceEntry<K, V> {
WeakEvictableEntry(
ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each evictable entry type.
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextEvictable() {
return nextEvictable;
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
this.nextEvictable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
return previousEvictable;
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
this.previousEvictable = previous;
}
}
static final class WeakExpirableEvictableEntry<K, V>
extends WeakEntry<K, V> implements ReferenceEntry<K, V> {
WeakExpirableEvictableEntry(
ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each expirable entry type.
volatile long time = Long.MAX_VALUE;
@Override
public long getExpirationTime() {
return time;
}
@Override
public void setExpirationTime(long time) {
this.time = time;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextExpirable() {
return nextExpirable;
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
this.nextExpirable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousExpirable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
return previousExpirable;
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
this.previousExpirable = previous;
}
// The code below is exactly the same for each evictable entry type.
@GuardedBy("Segment.this")
ReferenceEntry<K, V> nextEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getNextEvictable() {
return nextEvictable;
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
this.nextEvictable = next;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> previousEvictable = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
return previousEvictable;
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
this.previousEvictable = previous;
}
}
/**
* References a weak value.
*/
static final class WeakValueReference<K, V>
extends WeakReference<V> implements ValueReference<K, V> {
final ReferenceEntry<K, V> entry;
WeakValueReference(ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry) {
super(referent, queue);
this.entry = entry;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return entry;
}
@Override
public void clear(ValueReference<K, V> newValue) {
clear();
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return new WeakValueReference<K, V>(queue, value, entry);
}
@Override
public boolean isComputingReference() {
return false;
}
@Override
public V waitForValue() {
return get();
}
}
/**
* References a soft value.
*/
static final class SoftValueReference<K, V>
extends SoftReference<V> implements ValueReference<K, V> {
final ReferenceEntry<K, V> entry;
SoftValueReference(ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry) {
super(referent, queue);
this.entry = entry;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return entry;
}
@Override
public void clear(ValueReference<K, V> newValue) {
clear();
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return new SoftValueReference<K, V>(queue, value, entry);
}
@Override
public boolean isComputingReference() {
return false;
}
@Override
public V waitForValue() {
return get();
}
}
/**
* References a strong value.
*/
static final class StrongValueReference<K, V> implements ValueReference<K, V> {
final V referent;
StrongValueReference(V referent) {
this.referent = referent;
}
@Override
public V get() {
return referent;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return null;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return this;
}
@Override
public boolean isComputingReference() {
return false;
}
@Override
public V waitForValue() {
return get();
}
@Override
public void clear(ValueReference<K, V> newValue) {}
}
/**
* Applies a supplemental hash function to a given hash code, which defends against poor quality
* hash functions. This is critical when the concurrent hash map uses power-of-two length hash
* tables, that otherwise encounter collisions for hash codes that do not differ in lower or
* upper bits.
*
* @param h hash code
*/
static int rehash(int h) {
// Spread bits to regularize both segment and index locations,
// using variant of single-word Wang/Jenkins hash.
// TODO(kevinb): use Hashing/move this to Hashing?
h += (h << 15) ^ 0xffffcd7d;
h ^= (h >>> 10);
h += (h << 3);
h ^= (h >>> 6);
h += (h << 2) + (h << 14);
return h ^ (h >>> 16);
}
/**
* This method is a convenience for testing. Code should call {@link Segment#newEntry} directly.
*/
@GuardedBy("Segment.this")
@VisibleForTesting
ReferenceEntry<K, V> newEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return segmentFor(hash).newEntry(key, hash, next);
}
/**
* This method is a convenience for testing. Code should call {@link Segment#copyEntry} directly.
*/
@GuardedBy("Segment.this")
@VisibleForTesting
ReferenceEntry<K, V> copyEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
int hash = original.getHash();
return segmentFor(hash).copyEntry(original, newNext);
}
/**
* This method is a convenience for testing. Code should call {@link Segment#setValue} instead.
*/
@GuardedBy("Segment.this")
@VisibleForTesting
ValueReference<K, V> newValueReference(ReferenceEntry<K, V> entry, V value) {
int hash = entry.getHash();
return valueStrength.referenceValue(segmentFor(hash), entry, value);
}
int hash(Object key) {
int h = keyEquivalence.hash(key);
return rehash(h);
}
void reclaimValue(ValueReference<K, V> valueReference) {
ReferenceEntry<K, V> entry = valueReference.getEntry();
int hash = entry.getHash();
segmentFor(hash).reclaimValue(entry.getKey(), hash, valueReference);
}
void reclaimKey(ReferenceEntry<K, V> entry) {
int hash = entry.getHash();
segmentFor(hash).reclaimKey(entry, hash);
}
/**
* This method is a convenience for testing. Code should call {@link Segment#getLiveValue}
* instead.
*/
@VisibleForTesting
boolean isLive(ReferenceEntry<K, V> entry) {
return segmentFor(entry.getHash()).getLiveValue(entry) != null;
}
/**
* Returns the segment that should be used for a key with the given hash.
*
* @param hash the hash code for the key
* @return the segment
*/
Segment<K, V> segmentFor(int hash) {
// TODO(fry): Lazily create segments?
return segments[(hash >>> segmentShift) & segmentMask];
}
Segment<K, V> createSegment(int initialCapacity, int maxSegmentSize) {
return new Segment<K, V>(this, initialCapacity, maxSegmentSize);
}
/**
* Gets the value from an entry. Returns {@code null} if the entry is invalid,
* partially-collected, computing, or expired. Unlike {@link Segment#getLiveValue} this method
* does not attempt to clean up stale entries.
*/
V getLiveValue(ReferenceEntry<K, V> entry) {
if (entry.getKey() == null) {
return null;
}
V value = entry.getValueReference().get();
if (value == null) {
return null;
}
if (expires() && isExpired(entry)) {
return null;
}
return value;
}
// expiration
/**
* Returns {@code true} if the entry has expired.
*/
boolean isExpired(ReferenceEntry<K, V> entry) {
return isExpired(entry, ticker.read());
}
/**
* Returns {@code true} if the entry has expired.
*/
boolean isExpired(ReferenceEntry<K, V> entry, long now) {
// if the expiration time had overflowed, this "undoes" the overflow
return now - entry.getExpirationTime() > 0;
}
@GuardedBy("Segment.this")
static <K, V> void connectExpirables(ReferenceEntry<K, V> previous, ReferenceEntry<K, V> next) {
previous.setNextExpirable(next);
next.setPreviousExpirable(previous);
}
@GuardedBy("Segment.this")
static <K, V> void nullifyExpirable(ReferenceEntry<K, V> nulled) {
ReferenceEntry<K, V> nullEntry = nullEntry();
nulled.setNextExpirable(nullEntry);
nulled.setPreviousExpirable(nullEntry);
}
// eviction
/**
* Notifies listeners that an entry has been automatically removed due to expiration, eviction,
* or eligibility for garbage collection. This should be called every time expireEntries or
* evictEntry is called (once the lock is released).
*/
void processPendingNotifications() {
RemovalNotification<K, V> notification;
while ((notification = removalNotificationQueue.poll()) != null) {
try {
removalListener.onRemoval(notification);
} catch (Exception e) {
logger.log(Level.WARNING, "Exception thrown by removal listener", e);
}
}
}
/** Links the evitables together. */
@GuardedBy("Segment.this")
static <K, V> void connectEvictables(ReferenceEntry<K, V> previous, ReferenceEntry<K, V> next) {
previous.setNextEvictable(next);
next.setPreviousEvictable(previous);
}
@GuardedBy("Segment.this")
static <K, V> void nullifyEvictable(ReferenceEntry<K, V> nulled) {
ReferenceEntry<K, V> nullEntry = nullEntry();
nulled.setNextEvictable(nullEntry);
nulled.setPreviousEvictable(nullEntry);
}
@SuppressWarnings("unchecked")
final Segment<K, V>[] newSegmentArray(int ssize) {
return new Segment[ssize];
}
// Inner Classes
/**
* Segments are specialized versions of hash tables. This subclass inherits from ReentrantLock
* opportunistically, just to simplify some locking and avoid separate construction.
*/
@SuppressWarnings("serial") // This class is never serialized.
static class Segment<K, V> extends ReentrantLock {
/*
* TODO(fry): Consider copying variables (like evictsBySize) from outer class into this class.
* It will require more memory but will reduce indirection.
*/
/*
* Segments maintain a table of entry lists that are ALWAYS kept in a consistent state, so can
* be read without locking. Next fields of nodes are immutable (final). All list additions are
* performed at the front of each bin. This makes it easy to check changes, and also fast to
* traverse. When nodes would otherwise be changed, new nodes are created to replace them. This
* works well for hash tables since the bin lists tend to be short. (The average length is less
* than two.)
*
* Read operations can thus proceed without locking, but rely on selected uses of volatiles to
* ensure that completed write operations performed by other threads are noticed. For most
* purposes, the "count" field, tracking the number of elements, serves as that volatile
* variable ensuring visibility. This is convenient because this field needs to be read in many
* read operations anyway:
*
* - All (unsynchronized) read operations must first read the "count" field, and should not
* look at table entries if it is 0.
*
* - All (synchronized) write operations should write to the "count" field after structurally
* changing any bin. The operations must not take any action that could even momentarily
* cause a concurrent read operation to see inconsistent data. This is made easier by the
* nature of the read operations in Map. For example, no operation can reveal that the table
* has grown but the threshold has not yet been updated, so there are no atomicity requirements
* for this with respect to reads.
*
* As a guide, all critical volatile reads and writes to the count field are marked in code
* comments.
*/
final MapMakerInternalMap<K, V> map;
/**
* The number of live elements in this segment's region. This does not include unset elements
* which are awaiting cleanup.
*/
volatile int count;
/**
* Number of updates that alter the size of the table. This is used during bulk-read methods to
* make sure they see a consistent snapshot: If modCounts change during a traversal of segments
* computing size or checking containsValue, then we might have an inconsistent view of state
* so (usually) must retry.
*/
int modCount;
/**
* The table is expanded when its size exceeds this threshold. (The value of this field is
* always {@code (int) (capacity * 0.75)}.)
*/
int threshold;
/**
* The per-segment table.
*/
volatile AtomicReferenceArray<ReferenceEntry<K, V>> table;
/**
* The maximum size of this map. MapMaker.UNSET_INT if there is no maximum.
*/
final int maxSegmentSize;
/**
* The key reference queue contains entries whose keys have been garbage collected, and which
* need to be cleaned up internally.
*/
final ReferenceQueue<K> keyReferenceQueue;
/**
* The value reference queue contains value references whose values have been garbage collected,
* and which need to be cleaned up internally.
*/
final ReferenceQueue<V> valueReferenceQueue;
/**
* The recency queue is used to record which entries were accessed for updating the eviction
* list's ordering. It is drained as a batch operation when either the DRAIN_THRESHOLD is
* crossed or a write occurs on the segment.
*/
final Queue<ReferenceEntry<K, V>> recencyQueue;
/**
* A counter of the number of reads since the last write, used to drain queues on a small
* fraction of read operations.
*/
final AtomicInteger readCount = new AtomicInteger();
/**
* A queue of elements currently in the map, ordered by access time. Elements are added to the
* tail of the queue on access/write.
*/
@GuardedBy("Segment.this")
final Queue<ReferenceEntry<K, V>> evictionQueue;
/**
* A queue of elements currently in the map, ordered by expiration time (either access or write
* time). Elements are added to the tail of the queue on access/write.
*/
@GuardedBy("Segment.this")
final Queue<ReferenceEntry<K, V>> expirationQueue;
Segment(MapMakerInternalMap<K, V> map, int initialCapacity, int maxSegmentSize) {
this.map = map;
this.maxSegmentSize = maxSegmentSize;
initTable(newEntryArray(initialCapacity));
keyReferenceQueue = map.usesKeyReferences()
? new ReferenceQueue<K>() : null;
valueReferenceQueue = map.usesValueReferences()
? new ReferenceQueue<V>() : null;
recencyQueue = (map.evictsBySize() || map.expiresAfterAccess())
? new ConcurrentLinkedQueue<ReferenceEntry<K, V>>()
: MapMakerInternalMap.<ReferenceEntry<K, V>>discardingQueue();
evictionQueue = map.evictsBySize()
? new EvictionQueue<K, V>()
: MapMakerInternalMap.<ReferenceEntry<K, V>>discardingQueue();
expirationQueue = map.expires()
? new ExpirationQueue<K, V>()
: MapMakerInternalMap.<ReferenceEntry<K, V>>discardingQueue();
}
AtomicReferenceArray<ReferenceEntry<K, V>> newEntryArray(int size) {
return new AtomicReferenceArray<ReferenceEntry<K, V>>(size);
}
void initTable(AtomicReferenceArray<ReferenceEntry<K, V>> newTable) {
this.threshold = newTable.length() * 3 / 4; // 0.75
if (this.threshold == maxSegmentSize) {
// prevent spurious expansion before eviction
this.threshold++;
}
this.table = newTable;
}
@GuardedBy("Segment.this")
ReferenceEntry<K, V> newEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return map.entryFactory.newEntry(this, key, hash, next);
}
/**
* Copies {@code original} into a new entry chained to {@code newNext}. Returns the new entry,
* or {@code null} if {@code original} was already garbage collected.
*/
@GuardedBy("Segment.this")
ReferenceEntry<K, V> copyEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
if (original.getKey() == null) {
// key collected
return null;
}
ValueReference<K, V> valueReference = original.getValueReference();
V value = valueReference.get();
if ((value == null) && !valueReference.isComputingReference()) {
// value collected
return null;
}
ReferenceEntry<K, V> newEntry = map.entryFactory.copyEntry(this, original, newNext);
newEntry.setValueReference(valueReference.copyFor(this.valueReferenceQueue, value, newEntry));
return newEntry;
}
/**
* Sets a new value of an entry. Adds newly created entries at the end of the expiration queue.
*/
@GuardedBy("Segment.this")
void setValue(ReferenceEntry<K, V> entry, V value) {
ValueReference<K, V> valueReference = map.valueStrength.referenceValue(this, entry, value);
entry.setValueReference(valueReference);
recordWrite(entry);
}
// reference queues, for garbage collection cleanup
/**
* Cleanup collected entries when the lock is available.
*/
void tryDrainReferenceQueues() {
if (tryLock()) {
try {
drainReferenceQueues();
} finally {
unlock();
}
}
}
/**
* Drain the key and value reference queues, cleaning up internal entries containing garbage
* collected keys or values.
*/
@GuardedBy("Segment.this")
void drainReferenceQueues() {
if (map.usesKeyReferences()) {
drainKeyReferenceQueue();
}
if (map.usesValueReferences()) {
drainValueReferenceQueue();
}
}
@GuardedBy("Segment.this")
void drainKeyReferenceQueue() {
Reference<? extends K> ref;
int i = 0;
while ((ref = keyReferenceQueue.poll()) != null) {
@SuppressWarnings("unchecked")
ReferenceEntry<K, V> entry = (ReferenceEntry<K, V>) ref;
map.reclaimKey(entry);
if (++i == DRAIN_MAX) {
break;
}
}
}
@GuardedBy("Segment.this")
void drainValueReferenceQueue() {
Reference<? extends V> ref;
int i = 0;
while ((ref = valueReferenceQueue.poll()) != null) {
@SuppressWarnings("unchecked")
ValueReference<K, V> valueReference = (ValueReference<K, V>) ref;
map.reclaimValue(valueReference);
if (++i == DRAIN_MAX) {
break;
}
}
}
/**
* Clears all entries from the key and value reference queues.
*/
void clearReferenceQueues() {
if (map.usesKeyReferences()) {
clearKeyReferenceQueue();
}
if (map.usesValueReferences()) {
clearValueReferenceQueue();
}
}
void clearKeyReferenceQueue() {
while (keyReferenceQueue.poll() != null) {}
}
void clearValueReferenceQueue() {
while (valueReferenceQueue.poll() != null) {}
}
// recency queue, shared by expiration and eviction
/**
* Records the relative order in which this read was performed by adding {@code entry} to the
* recency queue. At write-time, or when the queue is full past the threshold, the queue will
* be drained and the entries therein processed.
*
* <p>Note: locked reads should use {@link #recordLockedRead}.
*/
void recordRead(ReferenceEntry<K, V> entry) {
if (map.expiresAfterAccess()) {
recordExpirationTime(entry, map.expireAfterAccessNanos);
}
recencyQueue.add(entry);
}
/**
* Updates the eviction metadata that {@code entry} was just read. This currently amounts to
* adding {@code entry} to relevant eviction lists.
*
* <p>Note: this method should only be called under lock, as it directly manipulates the
* eviction queues. Unlocked reads should use {@link #recordRead}.
*/
@GuardedBy("Segment.this")
void recordLockedRead(ReferenceEntry<K, V> entry) {
evictionQueue.add(entry);
if (map.expiresAfterAccess()) {
recordExpirationTime(entry, map.expireAfterAccessNanos);
expirationQueue.add(entry);
}
}
/**
* Updates eviction metadata that {@code entry} was just written. This currently amounts to
* adding {@code entry} to relevant eviction lists.
*/
@GuardedBy("Segment.this")
void recordWrite(ReferenceEntry<K, V> entry) {
// we are already under lock, so drain the recency queue immediately
drainRecencyQueue();
evictionQueue.add(entry);
if (map.expires()) {
// currently MapMaker ensures that expireAfterWrite and
// expireAfterAccess are mutually exclusive
long expiration = map.expiresAfterAccess()
? map.expireAfterAccessNanos
: map.expireAfterWriteNanos;
recordExpirationTime(entry, expiration);
expirationQueue.add(entry);
}
}
/**
* Drains the recency queue, updating eviction metadata that the entries therein were read in
* the specified relative order. This currently amounts to adding them to relevant eviction
* lists (accounting for the fact that they could have been removed from the map since being
* added to the recency queue).
*/
@GuardedBy("Segment.this")
void drainRecencyQueue() {
ReferenceEntry<K, V> e;
while ((e = recencyQueue.poll()) != null) {
// An entry may be in the recency queue despite it being removed from
// the map . This can occur when the entry was concurrently read while a
// writer is removing it from the segment or after a clear has removed
// all of the segment's entries.
if (evictionQueue.contains(e)) {
evictionQueue.add(e);
}
if (map.expiresAfterAccess() && expirationQueue.contains(e)) {
expirationQueue.add(e);
}
}
}
// expiration
void recordExpirationTime(ReferenceEntry<K, V> entry, long expirationNanos) {
// might overflow, but that's okay (see isExpired())
entry.setExpirationTime(map.ticker.read() + expirationNanos);
}
/**
* Cleanup expired entries when the lock is available.
*/
void tryExpireEntries() {
if (tryLock()) {
try {
expireEntries();
} finally {
unlock();
// don't call postWriteCleanup as we're in a read
}
}
}
@GuardedBy("Segment.this")
void expireEntries() {
drainRecencyQueue();
if (expirationQueue.isEmpty()) {
// There's no point in calling nanoTime() if we have no entries to
// expire.
return;
}
long now = map.ticker.read();
ReferenceEntry<K, V> e;
while ((e = expirationQueue.peek()) != null && map.isExpired(e, now)) {
if (!removeEntry(e, e.getHash(), RemovalCause.EXPIRED)) {
throw new AssertionError();
}
}
}
// eviction
void enqueueNotification(ReferenceEntry<K, V> entry, RemovalCause cause) {
enqueueNotification(entry.getKey(), entry.getHash(), entry.getValueReference().get(), cause);
}
void enqueueNotification(@Nullable K key, int hash, @Nullable V value, RemovalCause cause) {
if (map.removalNotificationQueue != DISCARDING_QUEUE) {
RemovalNotification<K, V> notification = new RemovalNotification<K, V>(key, value, cause);
map.removalNotificationQueue.offer(notification);
}
}
/**
* Performs eviction if the segment is full. This should only be called prior to adding a new
* entry and increasing {@code count}.
*
* @return {@code true} if eviction occurred
*/
@GuardedBy("Segment.this")
boolean evictEntries() {
if (map.evictsBySize() && count >= maxSegmentSize) {
drainRecencyQueue();
ReferenceEntry<K, V> e = evictionQueue.remove();
if (!removeEntry(e, e.getHash(), RemovalCause.SIZE)) {
throw new AssertionError();
}
return true;
}
return false;
}
/**
* Returns first entry of bin for given hash.
*/
ReferenceEntry<K, V> getFirst(int hash) {
// read this volatile field only once
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
return table.get(hash & (table.length() - 1));
}
// Specialized implementations of map methods
ReferenceEntry<K, V> getEntry(Object key, int hash) {
if (count != 0) { // read-volatile
for (ReferenceEntry<K, V> e = getFirst(hash); e != null; e = e.getNext()) {
if (e.getHash() != hash) {
continue;
}
K entryKey = e.getKey();
if (entryKey == null) {
tryDrainReferenceQueues();
continue;
}
if (map.keyEquivalence.equivalent(key, entryKey)) {
return e;
}
}
}
return null;
}
ReferenceEntry<K, V> getLiveEntry(Object key, int hash) {
ReferenceEntry<K, V> e = getEntry(key, hash);
if (e == null) {
return null;
} else if (map.expires() && map.isExpired(e)) {
tryExpireEntries();
return null;
}
return e;
}
V get(Object key, int hash) {
try {
ReferenceEntry<K, V> e = getLiveEntry(key, hash);
if (e == null) {
return null;
}
V value = e.getValueReference().get();
if (value != null) {
recordRead(e);
} else {
tryDrainReferenceQueues();
}
return value;
} finally {
postReadCleanup();
}
}
boolean containsKey(Object key, int hash) {
try {
if (count != 0) { // read-volatile
ReferenceEntry<K, V> e = getLiveEntry(key, hash);
if (e == null) {
return false;
}
return e.getValueReference().get() != null;
}
return false;
} finally {
postReadCleanup();
}
}
/**
* This method is a convenience for testing. Code should call {@link
* MapMakerInternalMap#containsValue} directly.
*/
@VisibleForTesting
boolean containsValue(Object value) {
try {
if (count != 0) { // read-volatile
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int length = table.length();
for (int i = 0; i < length; ++i) {
for (ReferenceEntry<K, V> e = table.get(i); e != null; e = e.getNext()) {
V entryValue = getLiveValue(e);
if (entryValue == null) {
continue;
}
if (map.valueEquivalence.equivalent(value, entryValue)) {
return true;
}
}
}
}
return false;
} finally {
postReadCleanup();
}
}
V put(K key, int hash, V value, boolean onlyIfAbsent) {
lock();
try {
preWriteCleanup();
int newCount = this.count + 1;
if (newCount > this.threshold) { // ensure capacity
expand();
newCount = this.count + 1;
}
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
// Look for an existing entry.
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
// We found an existing entry.
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
if (entryValue == null) {
++modCount;
setValue(e, value);
if (!valueReference.isComputingReference()) {
enqueueNotification(key, hash, entryValue, RemovalCause.COLLECTED);
newCount = this.count; // count remains unchanged
} else if (evictEntries()) { // evictEntries after setting new value
newCount = this.count + 1;
}
this.count = newCount; // write-volatile
return null;
} else if (onlyIfAbsent) {
// Mimic
// "if (!map.containsKey(key)) ...
// else return map.get(key);
recordLockedRead(e);
return entryValue;
} else {
// clobber existing entry, count remains unchanged
++modCount;
enqueueNotification(key, hash, entryValue, RemovalCause.REPLACED);
setValue(e, value);
return entryValue;
}
}
}
// Create a new entry.
++modCount;
ReferenceEntry<K, V> newEntry = newEntry(key, hash, first);
setValue(newEntry, value);
table.set(index, newEntry);
if (evictEntries()) { // evictEntries after setting new value
newCount = this.count + 1;
}
this.count = newCount; // write-volatile
return null;
} finally {
unlock();
postWriteCleanup();
}
}
/**
* Expands the table if possible.
*/
@GuardedBy("Segment.this")
void expand() {
AtomicReferenceArray<ReferenceEntry<K, V>> oldTable = table;
int oldCapacity = oldTable.length();
if (oldCapacity >= MAXIMUM_CAPACITY) {
return;
}
/*
* Reclassify nodes in each list to new Map. Because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move with a power of two offset.
* We eliminate unnecessary node creation by catching cases where old nodes can be reused
* because their next fields won't change. Statistically, at the default threshold, only
* about one-sixth of them need cloning when a table doubles. The nodes they replace will be
* garbage collectable as soon as they are no longer referenced by any reader thread that may
* be in the midst of traversing table right now.
*/
int newCount = count;
AtomicReferenceArray<ReferenceEntry<K, V>> newTable = newEntryArray(oldCapacity << 1);
threshold = newTable.length() * 3 / 4;
int newMask = newTable.length() - 1;
for (int oldIndex = 0; oldIndex < oldCapacity; ++oldIndex) {
// We need to guarantee that any existing reads of old Map can
// proceed. So we cannot yet null out each bin.
ReferenceEntry<K, V> head = oldTable.get(oldIndex);
if (head != null) {
ReferenceEntry<K, V> next = head.getNext();
int headIndex = head.getHash() & newMask;
// Single node on list
if (next == null) {
newTable.set(headIndex, head);
} else {
// Reuse the consecutive sequence of nodes with the same target
// index from the end of the list. tail points to the first
// entry in the reusable list.
ReferenceEntry<K, V> tail = head;
int tailIndex = headIndex;
for (ReferenceEntry<K, V> e = next; e != null; e = e.getNext()) {
int newIndex = e.getHash() & newMask;
if (newIndex != tailIndex) {
// The index changed. We'll need to copy the previous entry.
tailIndex = newIndex;
tail = e;
}
}
newTable.set(tailIndex, tail);
// Clone nodes leading up to the tail.
for (ReferenceEntry<K, V> e = head; e != tail; e = e.getNext()) {
int newIndex = e.getHash() & newMask;
ReferenceEntry<K, V> newNext = newTable.get(newIndex);
ReferenceEntry<K, V> newFirst = copyEntry(e, newNext);
if (newFirst != null) {
newTable.set(newIndex, newFirst);
} else {
removeCollectedEntry(e);
newCount--;
}
}
}
}
}
table = newTable;
this.count = newCount;
}
boolean replace(K key, int hash, V oldValue, V newValue) {
lock();
try {
preWriteCleanup();
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
// If the value disappeared, this entry is partially collected,
// and we should pretend like it doesn't exist.
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
if (entryValue == null) {
if (isCollected(valueReference)) {
int newCount = this.count - 1;
++modCount;
enqueueNotification(entryKey, hash, entryValue, RemovalCause.COLLECTED);
ReferenceEntry<K, V> newFirst = removeFromChain(first, e);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
}
return false;
}
if (map.valueEquivalence.equivalent(oldValue, entryValue)) {
++modCount;
enqueueNotification(key, hash, entryValue, RemovalCause.REPLACED);
setValue(e, newValue);
return true;
} else {
// Mimic
// "if (map.containsKey(key) && map.get(key).equals(oldValue))..."
recordLockedRead(e);
return false;
}
}
}
return false;
} finally {
unlock();
postWriteCleanup();
}
}
V replace(K key, int hash, V newValue) {
lock();
try {
preWriteCleanup();
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
// If the value disappeared, this entry is partially collected,
// and we should pretend like it doesn't exist.
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
if (entryValue == null) {
if (isCollected(valueReference)) {
int newCount = this.count - 1;
++modCount;
enqueueNotification(entryKey, hash, entryValue, RemovalCause.COLLECTED);
ReferenceEntry<K, V> newFirst = removeFromChain(first, e);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
}
return null;
}
++modCount;
enqueueNotification(key, hash, entryValue, RemovalCause.REPLACED);
setValue(e, newValue);
return entryValue;
}
}
return null;
} finally {
unlock();
postWriteCleanup();
}
}
V remove(Object key, int hash) {
lock();
try {
preWriteCleanup();
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
RemovalCause cause;
if (entryValue != null) {
cause = RemovalCause.EXPLICIT;
} else if (isCollected(valueReference)) {
cause = RemovalCause.COLLECTED;
} else {
return null;
}
++modCount;
enqueueNotification(entryKey, hash, entryValue, cause);
ReferenceEntry<K, V> newFirst = removeFromChain(first, e);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return entryValue;
}
}
return null;
} finally {
unlock();
postWriteCleanup();
}
}
boolean remove(Object key, int hash, Object value) {
lock();
try {
preWriteCleanup();
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
RemovalCause cause;
if (map.valueEquivalence.equivalent(value, entryValue)) {
cause = RemovalCause.EXPLICIT;
} else if (isCollected(valueReference)) {
cause = RemovalCause.COLLECTED;
} else {
return false;
}
++modCount;
enqueueNotification(entryKey, hash, entryValue, cause);
ReferenceEntry<K, V> newFirst = removeFromChain(first, e);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return (cause == RemovalCause.EXPLICIT);
}
}
return false;
} finally {
unlock();
postWriteCleanup();
}
}
void clear() {
if (count != 0) {
lock();
try {
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
if (map.removalNotificationQueue != DISCARDING_QUEUE) {
for (int i = 0; i < table.length(); ++i) {
for (ReferenceEntry<K, V> e = table.get(i); e != null; e = e.getNext()) {
// Computing references aren't actually in the map yet.
if (!e.getValueReference().isComputingReference()) {
enqueueNotification(e, RemovalCause.EXPLICIT);
}
}
}
}
for (int i = 0; i < table.length(); ++i) {
table.set(i, null);
}
clearReferenceQueues();
evictionQueue.clear();
expirationQueue.clear();
readCount.set(0);
++modCount;
count = 0; // write-volatile
} finally {
unlock();
postWriteCleanup();
}
}
}
/**
* Removes an entry from within a table. All entries following the removed node can stay, but
* all preceding ones need to be cloned.
*
* <p>This method does not decrement count for the removed entry, but does decrement count for
* all partially collected entries which are skipped. As such callers which are modifying count
* must re-read it after calling removeFromChain.
*
* @param first the first entry of the table
* @param entry the entry being removed from the table
* @return the new first entry for the table
*/
@GuardedBy("Segment.this")
ReferenceEntry<K, V> removeFromChain(ReferenceEntry<K, V> first, ReferenceEntry<K, V> entry) {
evictionQueue.remove(entry);
expirationQueue.remove(entry);
int newCount = count;
ReferenceEntry<K, V> newFirst = entry.getNext();
for (ReferenceEntry<K, V> e = first; e != entry; e = e.getNext()) {
ReferenceEntry<K, V> next = copyEntry(e, newFirst);
if (next != null) {
newFirst = next;
} else {
removeCollectedEntry(e);
newCount--;
}
}
this.count = newCount;
return newFirst;
}
void removeCollectedEntry(ReferenceEntry<K, V> entry) {
enqueueNotification(entry, RemovalCause.COLLECTED);
evictionQueue.remove(entry);
expirationQueue.remove(entry);
}
/**
* Removes an entry whose key has been garbage collected.
*/
boolean reclaimKey(ReferenceEntry<K, V> entry, int hash) {
lock();
try {
int newCount = count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
if (e == entry) {
++modCount;
enqueueNotification(
e.getKey(), hash, e.getValueReference().get(), RemovalCause.COLLECTED);
ReferenceEntry<K, V> newFirst = removeFromChain(first, e);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return true;
}
}
return false;
} finally {
unlock();
postWriteCleanup();
}
}
/**
* Removes an entry whose value has been garbage collected.
*/
boolean reclaimValue(K key, int hash, ValueReference<K, V> valueReference) {
lock();
try {
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> v = e.getValueReference();
if (v == valueReference) {
++modCount;
enqueueNotification(key, hash, valueReference.get(), RemovalCause.COLLECTED);
ReferenceEntry<K, V> newFirst = removeFromChain(first, e);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return true;
}
return false;
}
}
return false;
} finally {
unlock();
if (!isHeldByCurrentThread()) { // don't cleanup inside of put
postWriteCleanup();
}
}
}
/**
* Clears a value that has not yet been set, and thus does not require count to be modified.
*/
boolean clearValue(K key, int hash, ValueReference<K, V> valueReference) {
lock();
try {
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> v = e.getValueReference();
if (v == valueReference) {
ReferenceEntry<K, V> newFirst = removeFromChain(first, e);
table.set(index, newFirst);
return true;
}
return false;
}
}
return false;
} finally {
unlock();
postWriteCleanup();
}
}
@GuardedBy("Segment.this")
boolean removeEntry(ReferenceEntry<K, V> entry, int hash, RemovalCause cause) {
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
if (e == entry) {
++modCount;
enqueueNotification(e.getKey(), hash, e.getValueReference().get(), cause);
ReferenceEntry<K, V> newFirst = removeFromChain(first, e);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return true;
}
}
return false;
}
/**
* Returns {@code true} if the value has been partially collected, meaning that the value is
* null and it is not computing.
*/
boolean isCollected(ValueReference<K, V> valueReference) {
if (valueReference.isComputingReference()) {
return false;
}
return (valueReference.get() == null);
}
/**
* Gets the value from an entry. Returns {@code null} if the entry is invalid,
* partially-collected, computing, or expired.
*/
V getLiveValue(ReferenceEntry<K, V> entry) {
if (entry.getKey() == null) {
tryDrainReferenceQueues();
return null;
}
V value = entry.getValueReference().get();
if (value == null) {
tryDrainReferenceQueues();
return null;
}
if (map.expires() && map.isExpired(entry)) {
tryExpireEntries();
return null;
}
return value;
}
/**
* Performs routine cleanup following a read. Normally cleanup happens during writes, or from
* the cleanupExecutor. If cleanup is not observed after a sufficient number of reads, try
* cleaning up from the read thread.
*/
void postReadCleanup() {
if ((readCount.incrementAndGet() & DRAIN_THRESHOLD) == 0) {
runCleanup();
}
}
/**
* Performs routine cleanup prior to executing a write. This should be called every time a
* write thread acquires the segment lock, immediately after acquiring the lock.
*
* <p>Post-condition: expireEntries has been run.
*/
@GuardedBy("Segment.this")
void preWriteCleanup() {
runLockedCleanup();
}
/**
* Performs routine cleanup following a write.
*/
void postWriteCleanup() {
runUnlockedCleanup();
}
void runCleanup() {
runLockedCleanup();
runUnlockedCleanup();
}
void runLockedCleanup() {
if (tryLock()) {
try {
drainReferenceQueues();
expireEntries(); // calls drainRecencyQueue
readCount.set(0);
} finally {
unlock();
}
}
}
void runUnlockedCleanup() {
// locked cleanup may generate notifications we can send unlocked
if (!isHeldByCurrentThread()) {
map.processPendingNotifications();
}
}
}
// Queues
/**
* A custom queue for managing eviction order. Note that this is tightly integrated with {@code
* ReferenceEntry}, upon which it relies to perform its linking.
*
* <p>Note that this entire implementation makes the assumption that all elements which are in
* the map are also in this queue, and that all elements not in the queue are not in the map.
*
* <p>The benefits of creating our own queue are that (1) we can replace elements in the middle
* of the queue as part of copyEvictableEntry, and (2) the contains method is highly optimized
* for the current model.
*/
static final class EvictionQueue<K, V> extends AbstractQueue<ReferenceEntry<K, V>> {
final ReferenceEntry<K, V> head = new AbstractReferenceEntry<K, V>() {
ReferenceEntry<K, V> nextEvictable = this;
@Override
public ReferenceEntry<K, V> getNextEvictable() {
return nextEvictable;
}
@Override
public void setNextEvictable(ReferenceEntry<K, V> next) {
this.nextEvictable = next;
}
ReferenceEntry<K, V> previousEvictable = this;
@Override
public ReferenceEntry<K, V> getPreviousEvictable() {
return previousEvictable;
}
@Override
public void setPreviousEvictable(ReferenceEntry<K, V> previous) {
this.previousEvictable = previous;
}
};
// implements Queue
@Override
public boolean offer(ReferenceEntry<K, V> entry) {
// unlink
connectEvictables(entry.getPreviousEvictable(), entry.getNextEvictable());
// add to tail
connectEvictables(head.getPreviousEvictable(), entry);
connectEvictables(entry, head);
return true;
}
@Override
public ReferenceEntry<K, V> peek() {
ReferenceEntry<K, V> next = head.getNextEvictable();
return (next == head) ? null : next;
}
@Override
public ReferenceEntry<K, V> poll() {
ReferenceEntry<K, V> next = head.getNextEvictable();
if (next == head) {
return null;
}
remove(next);
return next;
}
@Override
@SuppressWarnings("unchecked")
public boolean remove(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry) o;
ReferenceEntry<K, V> previous = e.getPreviousEvictable();
ReferenceEntry<K, V> next = e.getNextEvictable();
connectEvictables(previous, next);
nullifyEvictable(e);
return next != NullEntry.INSTANCE;
}
@Override
@SuppressWarnings("unchecked")
public boolean contains(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry) o;
return e.getNextEvictable() != NullEntry.INSTANCE;
}
@Override
public boolean isEmpty() {
return head.getNextEvictable() == head;
}
@Override
public int size() {
int size = 0;
for (ReferenceEntry<K, V> e = head.getNextEvictable(); e != head; e = e.getNextEvictable()) {
size++;
}
return size;
}
@Override
public void clear() {
ReferenceEntry<K, V> e = head.getNextEvictable();
while (e != head) {
ReferenceEntry<K, V> next = e.getNextEvictable();
nullifyEvictable(e);
e = next;
}
head.setNextEvictable(head);
head.setPreviousEvictable(head);
}
@Override
public Iterator<ReferenceEntry<K, V>> iterator() {
return new AbstractSequentialIterator<ReferenceEntry<K, V>>(peek()) {
@Override
protected ReferenceEntry<K, V> computeNext(ReferenceEntry<K, V> previous) {
ReferenceEntry<K, V> next = previous.getNextEvictable();
return (next == head) ? null : next;
}
};
}
}
/**
* A custom queue for managing expiration order. Note that this is tightly integrated with
* {@code ReferenceEntry}, upon which it reliese to perform its linking.
*
* <p>Note that this entire implementation makes the assumption that all elements which are in
* the map are also in this queue, and that all elements not in the queue are not in the map.
*
* <p>The benefits of creating our own queue are that (1) we can replace elements in the middle
* of the queue as part of copyEvictableEntry, and (2) the contains method is highly optimized
* for the current model.
*/
static final class ExpirationQueue<K, V> extends AbstractQueue<ReferenceEntry<K, V>> {
final ReferenceEntry<K, V> head = new AbstractReferenceEntry<K, V>() {
@Override
public long getExpirationTime() {
return Long.MAX_VALUE;
}
@Override
public void setExpirationTime(long time) {}
ReferenceEntry<K, V> nextExpirable = this;
@Override
public ReferenceEntry<K, V> getNextExpirable() {
return nextExpirable;
}
@Override
public void setNextExpirable(ReferenceEntry<K, V> next) {
this.nextExpirable = next;
}
ReferenceEntry<K, V> previousExpirable = this;
@Override
public ReferenceEntry<K, V> getPreviousExpirable() {
return previousExpirable;
}
@Override
public void setPreviousExpirable(ReferenceEntry<K, V> previous) {
this.previousExpirable = previous;
}
};
// implements Queue
@Override
public boolean offer(ReferenceEntry<K, V> entry) {
// unlink
connectExpirables(entry.getPreviousExpirable(), entry.getNextExpirable());
// add to tail
connectExpirables(head.getPreviousExpirable(), entry);
connectExpirables(entry, head);
return true;
}
@Override
public ReferenceEntry<K, V> peek() {
ReferenceEntry<K, V> next = head.getNextExpirable();
return (next == head) ? null : next;
}
@Override
public ReferenceEntry<K, V> poll() {
ReferenceEntry<K, V> next = head.getNextExpirable();
if (next == head) {
return null;
}
remove(next);
return next;
}
@Override
@SuppressWarnings("unchecked")
public boolean remove(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry) o;
ReferenceEntry<K, V> previous = e.getPreviousExpirable();
ReferenceEntry<K, V> next = e.getNextExpirable();
connectExpirables(previous, next);
nullifyExpirable(e);
return next != NullEntry.INSTANCE;
}
@Override
@SuppressWarnings("unchecked")
public boolean contains(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry) o;
return e.getNextExpirable() != NullEntry.INSTANCE;
}
@Override
public boolean isEmpty() {
return head.getNextExpirable() == head;
}
@Override
public int size() {
int size = 0;
for (ReferenceEntry<K, V> e = head.getNextExpirable(); e != head; e = e.getNextExpirable()) {
size++;
}
return size;
}
@Override
public void clear() {
ReferenceEntry<K, V> e = head.getNextExpirable();
while (e != head) {
ReferenceEntry<K, V> next = e.getNextExpirable();
nullifyExpirable(e);
e = next;
}
head.setNextExpirable(head);
head.setPreviousExpirable(head);
}
@Override
public Iterator<ReferenceEntry<K, V>> iterator() {
return new AbstractSequentialIterator<ReferenceEntry<K, V>>(peek()) {
@Override
protected ReferenceEntry<K, V> computeNext(ReferenceEntry<K, V> previous) {
ReferenceEntry<K, V> next = previous.getNextExpirable();
return (next == head) ? null : next;
}
};
}
}
static final class CleanupMapTask implements Runnable {
final WeakReference<MapMakerInternalMap<?, ?>> mapReference;
public CleanupMapTask(MapMakerInternalMap<?, ?> map) {
this.mapReference = new WeakReference<MapMakerInternalMap<?, ?>>(map);
}
@Override
public void run() {
MapMakerInternalMap<?, ?> map = mapReference.get();
if (map == null) {
throw new CancellationException();
}
for (Segment<?, ?> segment : map.segments) {
segment.runCleanup();
}
}
}
// ConcurrentMap methods
@Override
public boolean isEmpty() {
/*
* Sum per-segment modCounts to avoid mis-reporting when elements are concurrently added and
* removed in one segment while checking another, in which case the table was never actually
* empty at any point. (The sum ensures accuracy up through at least 1<<31 per-segment
* modifications before recheck.) Method containsValue() uses similar constructions for
* stability checks.
*/
long sum = 0L;
Segment<K, V>[] segments = this.segments;
for (int i = 0; i < segments.length; ++i) {
if (segments[i].count != 0) {
return false;
}
sum += segments[i].modCount;
}
if (sum != 0L) { // recheck unless no modifications
for (int i = 0; i < segments.length; ++i) {
if (segments[i].count != 0) {
return false;
}
sum -= segments[i].modCount;
}
if (sum != 0L) {
return false;
}
}
return true;
}
@Override
public int size() {
Segment<K, V>[] segments = this.segments;
long sum = 0;
for (int i = 0; i < segments.length; ++i) {
sum += segments[i].count;
}
return Ints.saturatedCast(sum);
}
@Override
public V get(@Nullable Object key) {
if (key == null) {
return null;
}
int hash = hash(key);
return segmentFor(hash).get(key, hash);
}
/**
* Returns the internal entry for the specified key. The entry may be computing, expired, or
* partially collected. Does not impact recency ordering.
*/
ReferenceEntry<K, V> getEntry(@Nullable Object key) {
if (key == null) {
return null;
}
int hash = hash(key);
return segmentFor(hash).getEntry(key, hash);
}
@Override
public boolean containsKey(@Nullable Object key) {
if (key == null) {
return false;
}
int hash = hash(key);
return segmentFor(hash).containsKey(key, hash);
}
@Override
public boolean containsValue(@Nullable Object value) {
if (value == null) {
return false;
}
// This implementation is patterned after ConcurrentHashMap, but without the locking. The only
// way for it to return a false negative would be for the target value to jump around in the map
// such that none of the subsequent iterations observed it, despite the fact that at every point
// in time it was present somewhere int the map. This becomes increasingly unlikely as
// CONTAINS_VALUE_RETRIES increases, though without locking it is theoretically possible.
final Segment<K, V>[] segments = this.segments;
long last = -1L;
for (int i = 0; i < CONTAINS_VALUE_RETRIES; i++) {
long sum = 0L;
for (Segment<K, V> segment : segments) {
// ensure visibility of most recent completed write
@SuppressWarnings({"UnusedDeclaration", "unused"})
int c = segment.count; // read-volatile
AtomicReferenceArray<ReferenceEntry<K, V>> table = segment.table;
for (int j = 0; j < table.length(); j++) {
for (ReferenceEntry<K, V> e = table.get(j); e != null; e = e.getNext()) {
V v = segment.getLiveValue(e);
if (v != null && valueEquivalence.equivalent(value, v)) {
return true;
}
}
}
sum += segment.modCount;
}
if (sum == last) {
break;
}
last = sum;
}
return false;
}
@Override
public V put(K key, V value) {
checkNotNull(key);
checkNotNull(value);
int hash = hash(key);
return segmentFor(hash).put(key, hash, value, false);
}
@Override
public V putIfAbsent(K key, V value) {
checkNotNull(key);
checkNotNull(value);
int hash = hash(key);
return segmentFor(hash).put(key, hash, value, true);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (Entry<? extends K, ? extends V> e : m.entrySet()) {
put(e.getKey(), e.getValue());
}
}
@Override
public V remove(@Nullable Object key) {
if (key == null) {
return null;
}
int hash = hash(key);
return segmentFor(hash).remove(key, hash);
}
@Override
public boolean remove(@Nullable Object key, @Nullable Object value) {
if (key == null || value == null) {
return false;
}
int hash = hash(key);
return segmentFor(hash).remove(key, hash, value);
}
@Override
public boolean replace(K key, @Nullable V oldValue, V newValue) {
checkNotNull(key);
checkNotNull(newValue);
if (oldValue == null) {
return false;
}
int hash = hash(key);
return segmentFor(hash).replace(key, hash, oldValue, newValue);
}
@Override
public V replace(K key, V value) {
checkNotNull(key);
checkNotNull(value);
int hash = hash(key);
return segmentFor(hash).replace(key, hash, value);
}
@Override
public void clear() {
for (Segment<K, V> segment : segments) {
segment.clear();
}
}
transient Set<K> keySet;
@Override
public Set<K> keySet() {
Set<K> ks = keySet;
return (ks != null) ? ks : (keySet = new KeySet());
}
transient Collection<V> values;
@Override
public Collection<V> values() {
Collection<V> vs = values;
return (vs != null) ? vs : (values = new Values());
}
transient Set<Entry<K, V>> entrySet;
@Override
public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> es = entrySet;
return (es != null) ? es : (entrySet = new EntrySet());
}
// Iterator Support
abstract class HashIterator<E> implements Iterator<E> {
int nextSegmentIndex;
int nextTableIndex;
Segment<K, V> currentSegment;
AtomicReferenceArray<ReferenceEntry<K, V>> currentTable;
ReferenceEntry<K, V> nextEntry;
WriteThroughEntry nextExternal;
WriteThroughEntry lastReturned;
HashIterator() {
nextSegmentIndex = segments.length - 1;
nextTableIndex = -1;
advance();
}
public abstract E next();
final void advance() {
nextExternal = null;
if (nextInChain()) {
return;
}
if (nextInTable()) {
return;
}
while (nextSegmentIndex >= 0) {
currentSegment = segments[nextSegmentIndex--];
if (currentSegment.count != 0) {
currentTable = currentSegment.table;
nextTableIndex = currentTable.length() - 1;
if (nextInTable()) {
return;
}
}
}
}
/**
* Finds the next entry in the current chain. Returns {@code true} if an entry was found.
*/
boolean nextInChain() {
if (nextEntry != null) {
for (nextEntry = nextEntry.getNext(); nextEntry != null; nextEntry = nextEntry.getNext()) {
if (advanceTo(nextEntry)) {
return true;
}
}
}
return false;
}
/**
* Finds the next entry in the current table. Returns {@code true} if an entry was found.
*/
boolean nextInTable() {
while (nextTableIndex >= 0) {
if ((nextEntry = currentTable.get(nextTableIndex--)) != null) {
if (advanceTo(nextEntry) || nextInChain()) {
return true;
}
}
}
return false;
}
/**
* Advances to the given entry. Returns {@code true} if the entry was valid, {@code false} if it
* should be skipped.
*/
boolean advanceTo(ReferenceEntry<K, V> entry) {
try {
K key = entry.getKey();
V value = getLiveValue(entry);
if (value != null) {
nextExternal = new WriteThroughEntry(key, value);
return true;
} else {
// Skip stale entry.
return false;
}
} finally {
currentSegment.postReadCleanup();
}
}
public boolean hasNext() {
return nextExternal != null;
}
WriteThroughEntry nextEntry() {
if (nextExternal == null) {
throw new NoSuchElementException();
}
lastReturned = nextExternal;
advance();
return lastReturned;
}
public void remove() {
checkState(lastReturned != null);
MapMakerInternalMap.this.remove(lastReturned.getKey());
lastReturned = null;
}
}
final class KeyIterator extends HashIterator<K> {
@Override
public K next() {
return nextEntry().getKey();
}
}
final class ValueIterator extends HashIterator<V> {
@Override
public V next() {
return nextEntry().getValue();
}
}
/**
* Custom Entry class used by EntryIterator.next(), that relays setValue changes to the
* underlying map.
*/
final class WriteThroughEntry extends AbstractMapEntry<K, V> {
final K key; // non-null
V value; // non-null
WriteThroughEntry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public boolean equals(@Nullable Object object) {
// Cannot use key and value equivalence
if (object instanceof Entry) {
Entry<?, ?> that = (Entry<?, ?>) object;
return key.equals(that.getKey()) && value.equals(that.getValue());
}
return false;
}
@Override
public int hashCode() {
// Cannot use key and value equivalence
return key.hashCode() ^ value.hashCode();
}
@Override
public V setValue(V newValue) {
V oldValue = put(key, newValue);
value = newValue; // only if put succeeds
return oldValue;
}
}
final class EntryIterator extends HashIterator<Entry<K, V>> {
@Override
public Entry<K, V> next() {
return nextEntry();
}
}
final class KeySet extends AbstractSet<K> {
@Override
public Iterator<K> iterator() {
return new KeyIterator();
}
@Override
public int size() {
return MapMakerInternalMap.this.size();
}
@Override
public boolean isEmpty() {
return MapMakerInternalMap.this.isEmpty();
}
@Override
public boolean contains(Object o) {
return MapMakerInternalMap.this.containsKey(o);
}
@Override
public boolean remove(Object o) {
return MapMakerInternalMap.this.remove(o) != null;
}
@Override
public void clear() {
MapMakerInternalMap.this.clear();
}
}
final class Values extends AbstractCollection<V> {
@Override
public Iterator<V> iterator() {
return new ValueIterator();
}
@Override
public int size() {
return MapMakerInternalMap.this.size();
}
@Override
public boolean isEmpty() {
return MapMakerInternalMap.this.isEmpty();
}
@Override
public boolean contains(Object o) {
return MapMakerInternalMap.this.containsValue(o);
}
@Override
public void clear() {
MapMakerInternalMap.this.clear();
}
}
final class EntrySet extends AbstractSet<Entry<K, V>> {
@Override
public Iterator<Entry<K, V>> iterator() {
return new EntryIterator();
}
@Override
public boolean contains(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry<?, ?> e = (Entry<?, ?>) o;
Object key = e.getKey();
if (key == null) {
return false;
}
V v = MapMakerInternalMap.this.get(key);
return v != null && valueEquivalence.equivalent(e.getValue(), v);
}
@Override
public boolean remove(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry<?, ?> e = (Entry<?, ?>) o;
Object key = e.getKey();
return key != null && MapMakerInternalMap.this.remove(key, e.getValue());
}
@Override
public int size() {
return MapMakerInternalMap.this.size();
}
@Override
public boolean isEmpty() {
return MapMakerInternalMap.this.isEmpty();
}
@Override
public void clear() {
MapMakerInternalMap.this.clear();
}
}
// Serialization Support
private static final long serialVersionUID = 5;
Object writeReplace() {
return new SerializationProxy<K, V>(keyStrength, valueStrength, keyEquivalence,
valueEquivalence, expireAfterWriteNanos, expireAfterAccessNanos, maximumSize,
concurrencyLevel, removalListener, this);
}
/**
* The actual object that gets serialized. Unfortunately, readResolve() doesn't get called when a
* circular dependency is present, so the proxy must be able to behave as the map itself.
*/
abstract static class AbstractSerializationProxy<K, V>
extends ForwardingConcurrentMap<K, V> implements Serializable {
private static final long serialVersionUID = 3;
final Strength keyStrength;
final Strength valueStrength;
final Equivalence<Object> keyEquivalence;
final Equivalence<Object> valueEquivalence;
final long expireAfterWriteNanos;
final long expireAfterAccessNanos;
final int maximumSize;
final int concurrencyLevel;
final RemovalListener<? super K, ? super V> removalListener;
transient ConcurrentMap<K, V> delegate;
AbstractSerializationProxy(Strength keyStrength, Strength valueStrength,
Equivalence<Object> keyEquivalence, Equivalence<Object> valueEquivalence,
long expireAfterWriteNanos, long expireAfterAccessNanos, int maximumSize,
int concurrencyLevel, RemovalListener<? super K, ? super V> removalListener,
ConcurrentMap<K, V> delegate) {
this.keyStrength = keyStrength;
this.valueStrength = valueStrength;
this.keyEquivalence = keyEquivalence;
this.valueEquivalence = valueEquivalence;
this.expireAfterWriteNanos = expireAfterWriteNanos;
this.expireAfterAccessNanos = expireAfterAccessNanos;
this.maximumSize = maximumSize;
this.concurrencyLevel = concurrencyLevel;
this.removalListener = removalListener;
this.delegate = delegate;
}
@Override
protected ConcurrentMap<K, V> delegate() {
return delegate;
}
void writeMapTo(ObjectOutputStream out) throws IOException {
out.writeInt(delegate.size());
for (Entry<K, V> entry : delegate.entrySet()) {
out.writeObject(entry.getKey());
out.writeObject(entry.getValue());
}
out.writeObject(null); // terminate entries
}
@SuppressWarnings("deprecation") // serialization of deprecated feature
MapMaker readMapMaker(ObjectInputStream in) throws IOException {
int size = in.readInt();
MapMaker mapMaker = new MapMaker()
.initialCapacity(size)
.setKeyStrength(keyStrength)
.setValueStrength(valueStrength)
.keyEquivalence(keyEquivalence)
.concurrencyLevel(concurrencyLevel);
mapMaker.removalListener(removalListener);
if (expireAfterWriteNanos > 0) {
mapMaker.expireAfterWrite(expireAfterWriteNanos, TimeUnit.NANOSECONDS);
}
if (expireAfterAccessNanos > 0) {
mapMaker.expireAfterAccess(expireAfterAccessNanos, TimeUnit.NANOSECONDS);
}
if (maximumSize != MapMaker.UNSET_INT) {
mapMaker.maximumSize(maximumSize);
}
return mapMaker;
}
@SuppressWarnings("unchecked")
void readEntries(ObjectInputStream in) throws IOException, ClassNotFoundException {
while (true) {
K key = (K) in.readObject();
if (key == null) {
break; // terminator
}
V value = (V) in.readObject();
delegate.put(key, value);
}
}
}
/**
* The actual object that gets serialized. Unfortunately, readResolve() doesn't get called when a
* circular dependency is present, so the proxy must be able to behave as the map itself.
*/
private static final class SerializationProxy<K, V> extends AbstractSerializationProxy<K, V> {
private static final long serialVersionUID = 3;
SerializationProxy(Strength keyStrength, Strength valueStrength,
Equivalence<Object> keyEquivalence, Equivalence<Object> valueEquivalence,
long expireAfterWriteNanos, long expireAfterAccessNanos, int maximumSize,
int concurrencyLevel, RemovalListener<? super K, ? super V> removalListener,
ConcurrentMap<K, V> delegate) {
super(keyStrength, valueStrength, keyEquivalence, valueEquivalence, expireAfterWriteNanos,
expireAfterAccessNanos, maximumSize, concurrencyLevel, removalListener, delegate);
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
writeMapTo(out);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
MapMaker mapMaker = readMapMaker(in);
delegate = mapMaker.makeMap();
readEntries(in);
}
private Object readResolve() {
return delegate;
}
}
}
| Java |
/*
* 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.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ObjectArrays.checkElementsNotNull;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Iterator;
import javax.annotation.Nullable;
/**
* An immutable collection. Does not permit null elements.
*
* <p>In addition to the {@link Collection} methods, this class has an {@link
* #asList()} method, which returns a list view of the collection's elements.
*
* <p><b>Note:</b> Although this class is not final, it cannot be subclassed
* outside of this package as it has no public or protected constructors. Thus,
* instances of this type are guaranteed to be immutable.
*
* @author Jesse Wilson
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
public abstract class ImmutableCollection<E> extends AbstractCollection<E>
implements Serializable {
ImmutableCollection() {}
/**
* Returns an unmodifiable iterator across the elements in this collection.
*/
@Override
public abstract UnmodifiableIterator<E> iterator();
@Override
public final Object[] toArray() {
int size = size();
if (size == 0) {
return ObjectArrays.EMPTY_ARRAY;
}
Object[] result = new Object[size()];
copyIntoArray(result, 0);
return result;
}
@Override
public final <T> T[] toArray(T[] other) {
checkNotNull(other);
int size = size();
if (other.length < size) {
other = ObjectArrays.newArray(other, size);
} else if (other.length > size) {
other[size] = null;
}
copyIntoArray(other, 0);
return other;
}
@Override
public boolean contains(@Nullable Object object) {
return object != null && super.contains(object);
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final boolean add(E e) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final boolean remove(Object object) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final boolean addAll(Collection<? extends E> newElements) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final boolean removeAll(Collection<?> oldElements) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final boolean retainAll(Collection<?> elementsToKeep) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final void clear() {
throw new UnsupportedOperationException();
}
/*
* TODO(kevinb): Restructure code so ImmutableList doesn't contain this
* variable, which it doesn't use.
*/
private transient ImmutableList<E> asList;
/**
* Returns a list view of the collection.
*
* @since 2.0
*/
public ImmutableList<E> asList() {
ImmutableList<E> list = asList;
return (list == null) ? (asList = createAsList()) : list;
}
ImmutableList<E> createAsList() {
switch (size()) {
case 0:
return ImmutableList.of();
case 1:
return ImmutableList.of(iterator().next());
default:
return new RegularImmutableAsList<E>(this, toArray());
}
}
/**
* Returns {@code true} if this immutable collection's implementation contains references to
* user-created objects that aren't accessible via this collection's methods. This is generally
* used to determine whether {@code copyOf} implementations should make an explicit copy to avoid
* memory leaks.
*/
abstract boolean isPartialView();
/**
* Copies the contents of this immutable collection into the specified array at the specified
* offset. Returns {@code offset + size()}.
*/
int copyIntoArray(Object[] dst, int offset) {
for (E e : this) {
dst[offset++] = e;
}
return offset;
}
Object writeReplace() {
// We serialize by default to ImmutableList, the simplest thing that works.
return new ImmutableList.SerializedForm(toArray());
}
/**
* Abstract base class for builders of {@link ImmutableCollection} types.
*
* @since 10.0
*/
public abstract static class Builder<E> {
static final int DEFAULT_INITIAL_CAPACITY = 4;
static int expandedCapacity(int oldCapacity, int minCapacity) {
if (minCapacity < 0) {
throw new AssertionError("cannot store more than MAX_VALUE elements");
}
// careful of overflow!
int newCapacity = oldCapacity + (oldCapacity >> 1) + 1;
if (newCapacity < minCapacity) {
newCapacity = Integer.highestOneBit(minCapacity - 1) << 1;
}
if (newCapacity < 0) {
newCapacity = Integer.MAX_VALUE;
// guaranteed to be >= newCapacity
}
return newCapacity;
}
Builder() {
}
/**
* Adds {@code element} to the {@code ImmutableCollection} being built.
*
* <p>Note that each builder class covariantly returns its own type from
* this method.
*
* @param element the element to add
* @return this {@code Builder} instance
* @throws NullPointerException if {@code element} is null
*/
public abstract Builder<E> add(E element);
/**
* Adds each element of {@code elements} to the {@code ImmutableCollection}
* being built.
*
* <p>Note that each builder class overrides this method in order to
* covariantly return its own type.
*
* @param elements the elements to add
* @return this {@code Builder} instance
* @throws NullPointerException if {@code elements} is null or contains a
* null element
*/
public Builder<E> add(E... elements) {
for (E element : elements) {
add(element);
}
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableCollection}
* being built.
*
* <p>Note that each builder class overrides this method in order to
* covariantly return its own type.
*
* @param elements the elements to add
* @return this {@code Builder} instance
* @throws NullPointerException if {@code elements} is null or contains a
* null element
*/
public Builder<E> addAll(Iterable<? extends E> elements) {
for (E element : elements) {
add(element);
}
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableCollection}
* being built.
*
* <p>Note that each builder class overrides this method in order to
* covariantly return its own type.
*
* @param elements the elements to add
* @return this {@code Builder} instance
* @throws NullPointerException if {@code elements} is null or contains a
* null element
*/
public Builder<E> addAll(Iterator<? extends E> elements) {
while (elements.hasNext()) {
add(elements.next());
}
return this;
}
/**
* Returns a newly-created {@code ImmutableCollection} of the appropriate
* type, containing the elements provided to this builder.
*
* <p>Note that each builder class covariantly returns the appropriate type
* of {@code ImmutableCollection} from this method.
*/
public abstract ImmutableCollection<E> build();
}
abstract static class ArrayBasedBuilder<E> extends ImmutableCollection.Builder<E> {
Object[] contents;
int size;
ArrayBasedBuilder(int initialCapacity) {
checkArgument(initialCapacity >= 0, "capacity must be >= 0 but was %s", initialCapacity);
this.contents = new Object[initialCapacity];
this.size = 0;
}
/**
* Expand the absolute capacity of the builder so it can accept at least
* the specified number of elements without being resized.
*/
private void ensureCapacity(int minCapacity) {
if (contents.length < minCapacity) {
this.contents = ObjectArrays.arraysCopyOf(
this.contents, expandedCapacity(contents.length, minCapacity));
}
}
@Override
public ArrayBasedBuilder<E> add(E element) {
checkNotNull(element);
ensureCapacity(size + 1);
contents[size++] = element;
return this;
}
@Override
public Builder<E> add(E... elements) {
checkElementsNotNull(elements);
ensureCapacity(size + elements.length);
System.arraycopy(elements, 0, contents, size, elements.length);
size += elements.length;
return this;
}
@Override
public Builder<E> addAll(Iterable<? extends E> elements) {
if (elements instanceof Collection) {
Collection<?> collection = (Collection<?>) elements;
ensureCapacity(size + collection.size());
}
super.addAll(elements);
return this;
}
}
}
| Java |
/*
* 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.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableMapEntry.TerminalEntry;
import java.io.Serializable;
import javax.annotation.Nullable;
/**
* Bimap with two or more mappings.
*
* @author Louis Wasserman
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
class RegularImmutableBiMap<K, V> extends ImmutableBiMap<K, V> {
static final double MAX_LOAD_FACTOR = 1.2;
private final transient ImmutableMapEntry<K, V>[] keyTable;
private final transient ImmutableMapEntry<K, V>[] valueTable;
private final transient ImmutableMapEntry<K, V>[] entries;
private final transient int mask;
private final transient int hashCode;
RegularImmutableBiMap(TerminalEntry<?, ?>... entriesToAdd) {
this(entriesToAdd.length, entriesToAdd);
}
/**
* Constructor for RegularImmutableBiMap that takes as input an array of {@code TerminalEntry}
* entries. Assumes that these entries have already been checked for null.
*
* <p>This allows reuse of the entry objects from the array in the actual implementation.
*/
RegularImmutableBiMap(int n, TerminalEntry<?, ?>[] entriesToAdd) {
int tableSize = Hashing.closedTableSize(n, MAX_LOAD_FACTOR);
this.mask = tableSize - 1;
ImmutableMapEntry<K, V>[] keyTable = createEntryArray(tableSize);
ImmutableMapEntry<K, V>[] valueTable = createEntryArray(tableSize);
ImmutableMapEntry<K, V>[] entries = createEntryArray(n);
int hashCode = 0;
for (int i = 0; i < n; i++) {
@SuppressWarnings("unchecked")
TerminalEntry<K, V> entry = (TerminalEntry<K, V>) entriesToAdd[i];
K key = entry.getKey();
V value = entry.getValue();
int keyHash = key.hashCode();
int valueHash = value.hashCode();
int keyBucket = Hashing.smear(keyHash) & mask;
int valueBucket = Hashing.smear(valueHash) & mask;
ImmutableMapEntry<K, V> nextInKeyBucket = keyTable[keyBucket];
for (ImmutableMapEntry<K, V> keyEntry = nextInKeyBucket; keyEntry != null;
keyEntry = keyEntry.getNextInKeyBucket()) {
checkNoConflict(!key.equals(keyEntry.getKey()), "key", entry, keyEntry);
}
ImmutableMapEntry<K, V> nextInValueBucket = valueTable[valueBucket];
for (ImmutableMapEntry<K, V> valueEntry = nextInValueBucket; valueEntry != null;
valueEntry = valueEntry.getNextInValueBucket()) {
checkNoConflict(!value.equals(valueEntry.getValue()), "value", entry, valueEntry);
}
ImmutableMapEntry<K, V> newEntry =
(nextInKeyBucket == null && nextInValueBucket == null)
? entry
: new NonTerminalBiMapEntry<K, V>(entry, nextInKeyBucket, nextInValueBucket);
keyTable[keyBucket] = newEntry;
valueTable[valueBucket] = newEntry;
entries[i] = newEntry;
hashCode += keyHash ^ valueHash;
}
this.keyTable = keyTable;
this.valueTable = valueTable;
this.entries = entries;
this.hashCode = hashCode;
}
/**
* Constructor for RegularImmutableBiMap that makes no assumptions about the input entries.
*/
RegularImmutableBiMap(Entry<?, ?>[] entriesToAdd) {
int n = entriesToAdd.length;
int tableSize = Hashing.closedTableSize(n, MAX_LOAD_FACTOR);
this.mask = tableSize - 1;
ImmutableMapEntry<K, V>[] keyTable = createEntryArray(tableSize);
ImmutableMapEntry<K, V>[] valueTable = createEntryArray(tableSize);
ImmutableMapEntry<K, V>[] entries = createEntryArray(n);
int hashCode = 0;
for (int i = 0; i < n; i++) {
@SuppressWarnings("unchecked")
Entry<K, V> entry = (Entry<K, V>) entriesToAdd[i];
K key = entry.getKey();
V value = entry.getValue();
checkEntryNotNull(key, value);
int keyHash = key.hashCode();
int valueHash = value.hashCode();
int keyBucket = Hashing.smear(keyHash) & mask;
int valueBucket = Hashing.smear(valueHash) & mask;
ImmutableMapEntry<K, V> nextInKeyBucket = keyTable[keyBucket];
for (ImmutableMapEntry<K, V> keyEntry = nextInKeyBucket; keyEntry != null;
keyEntry = keyEntry.getNextInKeyBucket()) {
checkNoConflict(!key.equals(keyEntry.getKey()), "key", entry, keyEntry);
}
ImmutableMapEntry<K, V> nextInValueBucket = valueTable[valueBucket];
for (ImmutableMapEntry<K, V> valueEntry = nextInValueBucket; valueEntry != null;
valueEntry = valueEntry.getNextInValueBucket()) {
checkNoConflict(!value.equals(valueEntry.getValue()), "value", entry, valueEntry);
}
ImmutableMapEntry<K, V> newEntry =
(nextInKeyBucket == null && nextInValueBucket == null)
? new TerminalEntry<K, V>(key, value)
: new NonTerminalBiMapEntry<K, V>(key, value, nextInKeyBucket, nextInValueBucket);
keyTable[keyBucket] = newEntry;
valueTable[valueBucket] = newEntry;
entries[i] = newEntry;
hashCode += keyHash ^ valueHash;
}
this.keyTable = keyTable;
this.valueTable = valueTable;
this.entries = entries;
this.hashCode = hashCode;
}
private static final class NonTerminalBiMapEntry<K, V> extends ImmutableMapEntry<K, V> {
@Nullable private final ImmutableMapEntry<K, V> nextInKeyBucket;
@Nullable private final ImmutableMapEntry<K, V> nextInValueBucket;
NonTerminalBiMapEntry(K key, V value, @Nullable ImmutableMapEntry<K, V> nextInKeyBucket,
@Nullable ImmutableMapEntry<K, V> nextInValueBucket) {
super(key, value);
this.nextInKeyBucket = nextInKeyBucket;
this.nextInValueBucket = nextInValueBucket;
}
NonTerminalBiMapEntry(ImmutableMapEntry<K, V> contents,
@Nullable ImmutableMapEntry<K, V> nextInKeyBucket,
@Nullable ImmutableMapEntry<K, V> nextInValueBucket) {
super(contents);
this.nextInKeyBucket = nextInKeyBucket;
this.nextInValueBucket = nextInValueBucket;
}
@Override
@Nullable
ImmutableMapEntry<K, V> getNextInKeyBucket() {
return nextInKeyBucket;
}
@Override
@Nullable
ImmutableMapEntry<K, V> getNextInValueBucket() {
return nextInValueBucket;
}
}
@SuppressWarnings("unchecked")
private static <K, V> ImmutableMapEntry<K, V>[] createEntryArray(int length) {
return new ImmutableMapEntry[length];
}
@Override
@Nullable
public V get(@Nullable Object key) {
if (key == null) {
return null;
}
int bucket = Hashing.smear(key.hashCode()) & mask;
for (ImmutableMapEntry<K, V> entry = keyTable[bucket]; entry != null;
entry = entry.getNextInKeyBucket()) {
if (key.equals(entry.getKey())) {
return entry.getValue();
}
}
return null;
}
@Override
ImmutableSet<Entry<K, V>> createEntrySet() {
return new ImmutableMapEntrySet<K, V>() {
@Override
ImmutableMap<K, V> map() {
return RegularImmutableBiMap.this;
}
@Override
public UnmodifiableIterator<Entry<K, V>> iterator() {
return asList().iterator();
}
@Override
ImmutableList<Entry<K, V>> createAsList() {
return new RegularImmutableAsList<Entry<K, V>>(this, entries);
}
@Override
boolean isHashCodeFast() {
return true;
}
@Override
public int hashCode() {
return hashCode;
}
};
}
@Override
boolean isPartialView() {
return false;
}
@Override
public int size() {
return entries.length;
}
private transient ImmutableBiMap<V, K> inverse;
@Override
public ImmutableBiMap<V, K> inverse() {
ImmutableBiMap<V, K> result = inverse;
return (result == null) ? inverse = new Inverse() : result;
}
private final class Inverse extends ImmutableBiMap<V, K> {
@Override
public int size() {
return inverse().size();
}
@Override
public ImmutableBiMap<K, V> inverse() {
return RegularImmutableBiMap.this;
}
@Override
public K get(@Nullable Object value) {
if (value == null) {
return null;
}
int bucket = Hashing.smear(value.hashCode()) & mask;
for (ImmutableMapEntry<K, V> entry = valueTable[bucket]; entry != null;
entry = entry.getNextInValueBucket()) {
if (value.equals(entry.getValue())) {
return entry.getKey();
}
}
return null;
}
@Override
ImmutableSet<Entry<V, K>> createEntrySet() {
return new InverseEntrySet();
}
final class InverseEntrySet extends ImmutableMapEntrySet<V, K> {
@Override
ImmutableMap<V, K> map() {
return Inverse.this;
}
@Override
boolean isHashCodeFast() {
return true;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public UnmodifiableIterator<Entry<V, K>> iterator() {
return asList().iterator();
}
@Override
ImmutableList<Entry<V, K>> createAsList() {
return new ImmutableAsList<Entry<V, K>>() {
@Override
public Entry<V, K> get(int index) {
Entry<K, V> entry = entries[index];
return Maps.immutableEntry(entry.getValue(), entry.getKey());
}
@Override
ImmutableCollection<Entry<V, K>> delegateCollection() {
return InverseEntrySet.this;
}
};
}
}
@Override
boolean isPartialView() {
return false;
}
@Override
Object writeReplace() {
return new InverseSerializedForm<K, V>(RegularImmutableBiMap.this);
}
}
private static class InverseSerializedForm<K, V> implements Serializable {
private final ImmutableBiMap<K, V> forward;
InverseSerializedForm(ImmutableBiMap<K, V> forward) {
this.forward = forward;
}
Object readResolve() {
return forward.inverse();
}
private static final long serialVersionUID = 1;
}
}
| Java |
/*
* Copyright (C) 2011 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.collect;
import static com.google.common.collect.BoundType.CLOSED;
import static com.google.common.collect.BoundType.OPEN;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.Multiset.Entry;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.NoSuchElementException;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Provides static utility methods for creating and working with
* {@link SortedMultiset} instances.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
final class SortedMultisets {
private SortedMultisets() {
}
/**
* A skeleton implementation for {@link SortedMultiset#elementSet}.
*/
static class ElementSet<E> extends Multisets.ElementSet<E> implements
SortedSet<E> {
private final SortedMultiset<E> multiset;
ElementSet(SortedMultiset<E> multiset) {
this.multiset = multiset;
}
@Override final SortedMultiset<E> multiset() {
return multiset;
}
@Override public Comparator<? super E> comparator() {
return multiset().comparator();
}
@Override public SortedSet<E> subSet(E fromElement, E toElement) {
return multiset().subMultiset(fromElement, CLOSED, toElement, OPEN).elementSet();
}
@Override public SortedSet<E> headSet(E toElement) {
return multiset().headMultiset(toElement, OPEN).elementSet();
}
@Override public SortedSet<E> tailSet(E fromElement) {
return multiset().tailMultiset(fromElement, CLOSED).elementSet();
}
@Override public E first() {
return getElementOrThrow(multiset().firstEntry());
}
@Override public E last() {
return getElementOrThrow(multiset().lastEntry());
}
}
/**
* A skeleton navigable implementation for {@link SortedMultiset#elementSet}.
*/
@GwtIncompatible("Navigable")
static class NavigableElementSet<E> extends ElementSet<E> implements NavigableSet<E> {
NavigableElementSet(SortedMultiset<E> multiset) {
super(multiset);
}
@Override
public E lower(E e) {
return getElementOrNull(multiset().headMultiset(e, OPEN).lastEntry());
}
@Override
public E floor(E e) {
return getElementOrNull(multiset().headMultiset(e, CLOSED).lastEntry());
}
@Override
public E ceiling(E e) {
return getElementOrNull(multiset().tailMultiset(e, CLOSED).firstEntry());
}
@Override
public E higher(E e) {
return getElementOrNull(multiset().tailMultiset(e, OPEN).firstEntry());
}
@Override
public NavigableSet<E> descendingSet() {
return new NavigableElementSet<E>(multiset().descendingMultiset());
}
@Override
public Iterator<E> descendingIterator() {
return descendingSet().iterator();
}
@Override
public E pollFirst() {
return getElementOrNull(multiset().pollFirstEntry());
}
@Override
public E pollLast() {
return getElementOrNull(multiset().pollLastEntry());
}
@Override
public NavigableSet<E> subSet(
E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
return new NavigableElementSet<E>(multiset().subMultiset(
fromElement, BoundType.forBoolean(fromInclusive),
toElement, BoundType.forBoolean(toInclusive)));
}
@Override
public NavigableSet<E> headSet(E toElement, boolean inclusive) {
return new NavigableElementSet<E>(
multiset().headMultiset(toElement, BoundType.forBoolean(inclusive)));
}
@Override
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
return new NavigableElementSet<E>(
multiset().tailMultiset(fromElement, BoundType.forBoolean(inclusive)));
}
}
private static <E> E getElementOrThrow(Entry<E> entry) {
if (entry == null) {
throw new NoSuchElementException();
}
return entry.getElement();
}
private static <E> E getElementOrNull(@Nullable Entry<E> entry) {
return (entry == null) ? null : entry.getElement();
}
}
| Java |
/*
* Copyright (C) 2012 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.collect;
import java.util.Collection;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.TimeUnit;
/**
* A {@link BlockingDeque} which forwards all its method calls to another {@code BlockingDeque}.
* Subclasses should override one or more methods to modify the behavior of the backing deque as
* desired per the <a href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p><b>Warning:</b> The methods of {@code ForwardingBlockingDeque} forward
* <b>indiscriminately</b> to the methods of the delegate. For example, overriding {@link #add}
* alone <b>will not</b> change the behaviour of {@link #offer} which can lead to unexpected
* behaviour. In this case, you should override {@code offer} as well, either providing your own
* implementation, or delegating to the provided {@code standardOffer} method.
*
* <p>
* The {@code standard} methods are not guaranteed to be thread-safe, even when all of the methods
* that they depend on are thread-safe.
*
* @author Emily Soldal
* @since 14.0
*/
public abstract class ForwardingBlockingDeque<E>
extends ForwardingDeque<E> implements BlockingDeque<E> {
/** Constructor for use by subclasses. */
protected ForwardingBlockingDeque() {}
@Override protected abstract BlockingDeque<E> delegate();
@Override
public int remainingCapacity() {
return delegate().remainingCapacity();
}
@Override
public void putFirst(E e) throws InterruptedException {
delegate().putFirst(e);
}
@Override
public void putLast(E e) throws InterruptedException {
delegate().putLast(e);
}
@Override
public boolean offerFirst(E e, long timeout, TimeUnit unit) throws InterruptedException {
return delegate().offerFirst(e, timeout, unit);
}
@Override
public boolean offerLast(E e, long timeout, TimeUnit unit) throws InterruptedException {
return delegate().offerLast(e, timeout, unit);
}
@Override
public E takeFirst() throws InterruptedException {
return delegate().takeFirst();
}
@Override
public E takeLast() throws InterruptedException {
return delegate().takeLast();
}
@Override
public E pollFirst(long timeout, TimeUnit unit) throws InterruptedException {
return delegate().pollFirst(timeout, unit);
}
@Override
public E pollLast(long timeout, TimeUnit unit) throws InterruptedException {
return delegate().pollLast(timeout, unit);
}
@Override
public void put(E e) throws InterruptedException {
delegate().put(e);
}
@Override
public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException {
return delegate().offer(e, timeout, unit);
}
@Override
public E take() throws InterruptedException {
return delegate().take();
}
@Override
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
return delegate().poll(timeout, unit);
}
@Override
public int drainTo(Collection<? super E> c) {
return delegate().drainTo(c);
}
@Override
public int drainTo(Collection<? super E> c, int maxElements) {
return delegate().drainTo(c, maxElements);
}
}
| Java |
/*
* Copyright (C) 2012 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.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Optional;
import java.util.ArrayDeque;
import java.util.BitSet;
import java.util.Deque;
import java.util.Iterator;
/**
* A variant of {@link TreeTraverser} for binary trees, providing additional traversals specific to
* binary trees.
*
* @author Louis Wasserman
* @since 15.0
*/
@Beta
@GwtCompatible(emulated = true)
public abstract class BinaryTreeTraverser<T> extends TreeTraverser<T> {
// TODO(user): make this GWT-compatible when we've checked in ArrayDeque and BitSet emulation
/**
* Returns the left child of the specified node, or {@link Optional#absent()} if the specified
* node has no left child.
*/
public abstract Optional<T> leftChild(T root);
/**
* Returns the right child of the specified node, or {@link Optional#absent()} if the specified
* node has no right child.
*/
public abstract Optional<T> rightChild(T root);
/**
* Returns the children of this node, in left-to-right order.
*/
@Override
public final Iterable<T> children(final T root) {
checkNotNull(root);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return new AbstractIterator<T>() {
boolean doneLeft;
boolean doneRight;
@Override
protected T computeNext() {
if (!doneLeft) {
doneLeft = true;
Optional<T> left = leftChild(root);
if (left.isPresent()) {
return left.get();
}
}
if (!doneRight) {
doneRight = true;
Optional<T> right = rightChild(root);
if (right.isPresent()) {
return right.get();
}
}
return endOfData();
}
};
}
};
}
@Override
UnmodifiableIterator<T> preOrderIterator(T root) {
return new PreOrderIterator(root);
}
/*
* Optimized implementation of preOrderIterator for binary trees.
*/
private final class PreOrderIterator extends UnmodifiableIterator<T>
implements PeekingIterator<T> {
private final Deque<T> stack;
PreOrderIterator(T root) {
this.stack = new ArrayDeque<T>();
stack.addLast(root);
}
@Override
public boolean hasNext() {
return !stack.isEmpty();
}
@Override
public T next() {
T result = stack.removeLast();
pushIfPresent(stack, rightChild(result));
pushIfPresent(stack, leftChild(result));
return result;
}
@Override
public T peek() {
return stack.getLast();
}
}
@Override
UnmodifiableIterator<T> postOrderIterator(T root) {
return new PostOrderIterator(root);
}
/*
* Optimized implementation of postOrderIterator for binary trees.
*/
private final class PostOrderIterator extends UnmodifiableIterator<T> {
private final Deque<T> stack;
private final BitSet hasExpanded;
PostOrderIterator(T root) {
this.stack = new ArrayDeque<T>();
stack.addLast(root);
this.hasExpanded = new BitSet();
}
@Override
public boolean hasNext() {
return !stack.isEmpty();
}
@Override
public T next() {
while (true) {
T node = stack.getLast();
boolean expandedNode = hasExpanded.get(stack.size() - 1);
if (expandedNode) {
stack.removeLast();
hasExpanded.clear(stack.size());
return node;
} else {
hasExpanded.set(stack.size() - 1);
pushIfPresent(stack, rightChild(node));
pushIfPresent(stack, leftChild(node));
}
}
}
}
// TODO(user): see if any significant optimizations are possible for breadthFirstIterator
public final FluentIterable<T> inOrderTraversal(final T root) {
checkNotNull(root);
return new FluentIterable<T>() {
@Override
public UnmodifiableIterator<T> iterator() {
return new InOrderIterator(root);
}
};
}
private final class InOrderIterator extends AbstractIterator<T> {
private final Deque<T> stack;
private final BitSet hasExpandedLeft;
InOrderIterator(T root) {
this.stack = new ArrayDeque<T>();
this.hasExpandedLeft = new BitSet();
stack.addLast(root);
}
@Override
protected T computeNext() {
while (!stack.isEmpty()) {
T node = stack.getLast();
if (hasExpandedLeft.get(stack.size() - 1)) {
stack.removeLast();
hasExpandedLeft.clear(stack.size());
pushIfPresent(stack, rightChild(node));
return node;
} else {
hasExpandedLeft.set(stack.size() - 1);
pushIfPresent(stack, leftChild(node));
}
}
return endOfData();
}
}
private static <T> void pushIfPresent(Deque<T> stack, Optional<T> node) {
if (node.isPresent()) {
stack.addLast(node.get());
}
}
}
| Java |
/*
* Copyright (C) 2007 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.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* A {@code SetMultimap} whose set of values for a given key are kept sorted;
* that is, they comprise a {@link SortedSet}. It cannot hold duplicate
* key-value pairs; adding a key-value pair that's already in the multimap has
* no effect. This interface does not specify the ordering of the multimap's
* keys. See the {@link Multimap} documentation for information common to all
* multimaps.
*
* <p>The {@link #get}, {@link #removeAll}, and {@link #replaceValues} methods
* each return a {@link SortedSet} of values, while {@link Multimap#entries()}
* returns a {@link Set} of map entries. Though the method signature doesn't say
* so explicitly, the map returned by {@link #asMap} has {@code SortedSet}
* values.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap">
* {@code Multimap}</a>.
*
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public interface SortedSetMultimap<K, V> extends SetMultimap<K, V> {
// Following Javadoc copied from Multimap.
/**
* Returns a collection view of all values associated with a key. If no
* mappings in the multimap have the provided key, an empty collection is
* returned.
*
* <p>Changes to the returned collection will update the underlying multimap,
* and vice versa.
*
* <p>Because a {@code SortedSetMultimap} has unique sorted values for a given
* key, this method returns a {@link SortedSet}, instead of the
* {@link java.util.Collection} specified in the {@link Multimap} interface.
*/
@Override
SortedSet<V> get(@Nullable K key);
/**
* Removes all values associated with a given key.
*
* <p>Because a {@code SortedSetMultimap} has unique sorted values for a given
* key, this method returns a {@link SortedSet}, instead of the
* {@link java.util.Collection} specified in the {@link Multimap} interface.
*/
@Override
SortedSet<V> removeAll(@Nullable Object key);
/**
* Stores a collection of values with the same key, replacing any existing
* values for that key.
*
* <p>Because a {@code SortedSetMultimap} has unique sorted values for a given
* key, this method returns a {@link SortedSet}, instead of the
* {@link java.util.Collection} specified in the {@link Multimap} interface.
*
* <p>Any duplicates in {@code values} will be stored in the multimap once.
*/
@Override
SortedSet<V> replaceValues(K key, Iterable<? extends V> values);
/**
* Returns a map view that associates each key with the corresponding values
* in the multimap. Changes to the returned map, such as element removal, will
* update the underlying multimap. The map does not support {@code setValue()}
* on its entries, {@code put}, or {@code putAll}.
*
* <p>When passed a key that is present in the map, {@code
* asMap().get(Object)} has the same behavior as {@link #get}, returning a
* live collection. When passed a key that is not present, however, {@code
* asMap().get(Object)} returns {@code null} instead of an empty collection.
*
* <p><b>Note:</b> The returned map's values are guaranteed to be of type
* {@link SortedSet}. To obtain this map with the more specific generic type
* {@code Map<K, SortedSet<V>>}, call
* {@link Multimaps#asMap(SortedSetMultimap)} instead.
*/
@Override Map<K, Collection<V>> asMap();
/**
* Returns the comparator that orders the multimap values, with {@code null}
* indicating that natural ordering is used.
*/
Comparator<? super V> valueComparator();
}
| Java |
/*
* Copyright (C) 2007 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.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.ListIterator;
/**
* A list iterator which forwards all its method calls to another list
* iterator. Subclasses should override one or more methods to modify the
* behavior of the backing iterator as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* @author Mike Bostock
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public abstract class ForwardingListIterator<E> extends ForwardingIterator<E>
implements ListIterator<E> {
/** Constructor for use by subclasses. */
protected ForwardingListIterator() {}
@Override protected abstract ListIterator<E> delegate();
@Override
public void add(E element) {
delegate().add(element);
}
@Override
public boolean hasPrevious() {
return delegate().hasPrevious();
}
@Override
public int nextIndex() {
return delegate().nextIndex();
}
@Override
public E previous() {
return delegate().previous();
}
@Override
public int previousIndex() {
return delegate().previousIndex();
}
@Override
public void set(E element) {
delegate().set(element);
}
}
| Java |
/*
* Copyright (C) 2010 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.collect;
import com.google.common.annotations.GwtCompatible;
/**
* Dummy class that makes the GWT serialization policy happy. It isn't used
* on the server-side.
*
* @author Hayward Chan
*/
@GwtCompatible(emulated = true)
class ForwardingImmutableCollection {
private ForwardingImmutableCollection() {}
}
| Java |
/*
* Copyright (C) 2012 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.collect;
import static com.google.common.base.Preconditions.checkElementIndex;
import com.google.common.annotations.GwtCompatible;
import com.google.common.math.IntMath;
import java.util.AbstractList;
import java.util.List;
import java.util.ListIterator;
import javax.annotation.Nullable;
/**
* Implementation of {@link Lists#cartesianProduct(List)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
final class CartesianList<E> extends AbstractList<List<E>> {
private transient final ImmutableList<List<E>> axes;
private transient final int[] axesSizeProduct;
static <E> List<List<E>> create(List<? extends List<? extends E>> lists) {
ImmutableList.Builder<List<E>> axesBuilder =
new ImmutableList.Builder<List<E>>(lists.size());
for (List<? extends E> list : lists) {
List<E> copy = ImmutableList.copyOf(list);
if (copy.isEmpty()) {
return ImmutableList.of();
}
axesBuilder.add(copy);
}
return new CartesianList<E>(axesBuilder.build());
}
CartesianList(ImmutableList<List<E>> axes) {
this.axes = axes;
int[] axesSizeProduct = new int[axes.size() + 1];
axesSizeProduct[axes.size()] = 1;
try {
for (int i = axes.size() - 1; i >= 0; i--) {
axesSizeProduct[i] =
IntMath.checkedMultiply(axesSizeProduct[i + 1], axes.get(i).size());
}
} catch (ArithmeticException e) {
throw new IllegalArgumentException(
"Cartesian product too large; must have size at most Integer.MAX_VALUE");
}
this.axesSizeProduct = axesSizeProduct;
}
private int getAxisIndexForProductIndex(int index, int axis) {
return (index / axesSizeProduct[axis + 1]) % axes.get(axis).size();
}
@Override
public ImmutableList<E> get(final int index) {
checkElementIndex(index, size());
return new ImmutableList<E>() {
@Override
public int size() {
return axes.size();
}
@Override
public E get(int axis) {
checkElementIndex(axis, size());
int axisIndex = getAxisIndexForProductIndex(index, axis);
return axes.get(axis).get(axisIndex);
}
@Override
boolean isPartialView() {
return true;
}
};
}
@Override
public int size() {
return axesSizeProduct[0];
}
@Override
public boolean contains(@Nullable Object o) {
if (!(o instanceof List)) {
return false;
}
List<?> list = (List<?>) o;
if (list.size() != axes.size()) {
return false;
}
ListIterator<?> itr = list.listIterator();
while (itr.hasNext()) {
int index = itr.nextIndex();
if (!axes.get(index).contains(itr.next())) {
return false;
}
}
return true;
}
}
| Java |
/*
* Copyright (C) 2012 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.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A skeleton {@code Multimap} implementation, not necessarily in terms of a {@code Map}.
*
* @author Louis Wasserman
*/
@GwtCompatible
abstract class AbstractMultimap<K, V> implements Multimap<K, V> {
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public boolean containsValue(@Nullable Object value) {
for (Collection<V> collection : asMap().values()) {
if (collection.contains(value)) {
return true;
}
}
return false;
}
@Override
public boolean containsEntry(@Nullable Object key, @Nullable Object value) {
Collection<V> collection = asMap().get(key);
return collection != null && collection.contains(value);
}
@Override
public boolean remove(@Nullable Object key, @Nullable Object value) {
Collection<V> collection = asMap().get(key);
return collection != null && collection.remove(value);
}
@Override
public boolean put(@Nullable K key, @Nullable V value) {
return get(key).add(value);
}
@Override
public boolean putAll(@Nullable K key, Iterable<? extends V> values) {
checkNotNull(values);
// make sure we only call values.iterator() once
// and we only call get(key) if values is nonempty
if (values instanceof Collection) {
Collection<? extends V> valueCollection = (Collection<? extends V>) values;
return !valueCollection.isEmpty() && get(key).addAll(valueCollection);
} else {
Iterator<? extends V> valueItr = values.iterator();
return valueItr.hasNext() && Iterators.addAll(get(key), valueItr);
}
}
@Override
public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
boolean changed = false;
for (Map.Entry<? extends K, ? extends V> entry : multimap.entries()) {
changed |= put(entry.getKey(), entry.getValue());
}
return changed;
}
@Override
public Collection<V> replaceValues(@Nullable K key, Iterable<? extends V> values) {
checkNotNull(values);
Collection<V> result = removeAll(key);
putAll(key, values);
return result;
}
private transient Collection<Entry<K, V>> entries;
@Override
public Collection<Entry<K, V>> entries() {
Collection<Entry<K, V>> result = entries;
return (result == null) ? entries = createEntries() : result;
}
Collection<Entry<K, V>> createEntries() {
if (this instanceof SetMultimap) {
return new EntrySet();
} else {
return new Entries();
}
}
private class Entries extends Multimaps.Entries<K, V> {
@Override
Multimap<K, V> multimap() {
return AbstractMultimap.this;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return entryIterator();
}
}
private class EntrySet extends Entries implements Set<Entry<K, V>> {
@Override
public int hashCode() {
return Sets.hashCodeImpl(this);
}
@Override
public boolean equals(@Nullable Object obj) {
return Sets.equalsImpl(this, obj);
}
}
abstract Iterator<Entry<K, V>> entryIterator();
private transient Set<K> keySet;
@Override
public Set<K> keySet() {
Set<K> result = keySet;
return (result == null) ? keySet = createKeySet() : result;
}
Set<K> createKeySet() {
return new Maps.KeySet<K, Collection<V>>(asMap());
}
private transient Multiset<K> keys;
@Override
public Multiset<K> keys() {
Multiset<K> result = keys;
return (result == null) ? keys = createKeys() : result;
}
Multiset<K> createKeys() {
return new Multimaps.Keys<K, V>(this);
}
private transient Collection<V> values;
@Override
public Collection<V> values() {
Collection<V> result = values;
return (result == null) ? values = createValues() : result;
}
Collection<V> createValues() {
return new Values();
}
class Values extends AbstractCollection<V> {
@Override public Iterator<V> iterator() {
return valueIterator();
}
@Override public int size() {
return AbstractMultimap.this.size();
}
@Override public boolean contains(@Nullable Object o) {
return AbstractMultimap.this.containsValue(o);
}
@Override public void clear() {
AbstractMultimap.this.clear();
}
}
Iterator<V> valueIterator() {
return Maps.valueIterator(entries().iterator());
}
private transient Map<K, Collection<V>> asMap;
@Override
public Map<K, Collection<V>> asMap() {
Map<K, Collection<V>> result = asMap;
return (result == null) ? asMap = createAsMap() : result;
}
abstract Map<K, Collection<V>> createAsMap();
// Comparison and hashing
@Override public boolean equals(@Nullable Object object) {
return Multimaps.equalsImpl(this, object);
}
/**
* Returns the hash code for this multimap.
*
* <p>The hash code of a multimap is defined as the hash code of the map view,
* as returned by {@link Multimap#asMap}.
*
* @see Map#hashCode
*/
@Override public int hashCode() {
return asMap().hashCode();
}
/**
* Returns a string representation of the multimap, generated by calling
* {@code toString} on the map returned by {@link Multimap#asMap}.
*
* @return a string representation of the multimap
*/
@Override
public String toString() {
return asMap().toString();
}
}
| Java |
/*
* 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.collect;
import com.google.common.annotations.GwtCompatible;
import javax.annotation.Nullable;
/**
* Implementation of {@link ImmutableMap} with exactly one entry.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
final class SingletonImmutableBiMap<K, V> extends ImmutableBiMap<K, V> {
final transient K singleKey;
final transient V singleValue;
SingletonImmutableBiMap(K singleKey, V singleValue) {
checkEntryNotNull(singleKey, singleValue);
this.singleKey = singleKey;
this.singleValue = singleValue;
}
private SingletonImmutableBiMap(K singleKey, V singleValue,
ImmutableBiMap<V, K> inverse) {
this.singleKey = singleKey;
this.singleValue = singleValue;
this.inverse = inverse;
}
SingletonImmutableBiMap(Entry<? extends K, ? extends V> entry) {
this(entry.getKey(), entry.getValue());
}
@Override public V get(@Nullable Object key) {
return singleKey.equals(key) ? singleValue : null;
}
@Override
public int size() {
return 1;
}
@Override public boolean containsKey(@Nullable Object key) {
return singleKey.equals(key);
}
@Override public boolean containsValue(@Nullable Object value) {
return singleValue.equals(value);
}
@Override boolean isPartialView() {
return false;
}
@Override
ImmutableSet<Entry<K, V>> createEntrySet() {
return ImmutableSet.of(Maps.immutableEntry(singleKey, singleValue));
}
@Override
ImmutableSet<K> createKeySet() {
return ImmutableSet.of(singleKey);
}
transient ImmutableBiMap<V, K> inverse;
@Override
public ImmutableBiMap<V, K> inverse() {
// racy single-check idiom
ImmutableBiMap<V, K> result = inverse;
if (result == null) {
return inverse = new SingletonImmutableBiMap<V, K>(
singleValue, singleKey, this);
} else {
return result;
}
}
}
| Java |
/*
* Copyright (C) 2010 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.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.NoSuchElementException;
import javax.annotation.Nullable;
/**
* This class provides a skeletal implementation of the {@code Iterator}
* interface for sequences whose next element can always be derived from the
* previous element. Null elements are not supported, nor is the
* {@link #remove()} method.
*
* <p>Example: <pre> {@code
*
* Iterator<Integer> powersOfTwo =
* new AbstractSequentialIterator<Integer>(1) {
* protected Integer computeNext(Integer previous) {
* return (previous == 1 << 30) ? null : previous * 2;
* }
* };}</pre>
*
* @author Chris Povirk
* @since 12.0 (in Guava as {@code AbstractLinkedIterator} since 8.0)
*/
@GwtCompatible
public abstract class AbstractSequentialIterator<T>
extends UnmodifiableIterator<T> {
private T nextOrNull;
/**
* Creates a new iterator with the given first element, or, if {@code
* firstOrNull} is null, creates a new empty iterator.
*/
protected AbstractSequentialIterator(@Nullable T firstOrNull) {
this.nextOrNull = firstOrNull;
}
/**
* Returns the element that follows {@code previous}, or returns {@code null}
* if no elements remain. This method is invoked during each call to
* {@link #next()} in order to compute the result of a <i>future</i> call to
* {@code next()}.
*/
protected abstract T computeNext(T previous);
@Override
public final boolean hasNext() {
return nextOrNull != null;
}
@Override
public final T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
try {
return nextOrNull;
} finally {
nextOrNull = computeNext(nextOrNull);
}
}
}
| Java |
/*
* Copyright (C) 2012 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.collect;
import static com.google.common.collect.Maps.keyOrNull;
import com.google.common.annotations.Beta;
import java.util.Iterator;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.NoSuchElementException;
import java.util.SortedMap;
/**
* A navigable map which forwards all its method calls to another navigable map. Subclasses should
* override one or more methods to modify the behavior of the backing map as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p><i>Warning:</i> The methods of {@code ForwardingNavigableMap} forward <i>indiscriminately</i>
* to the methods of the delegate. For example, overriding {@link #put} alone <i>will not</i>
* change the behavior of {@link #putAll}, which can lead to unexpected behavior. In this case, you
* should override {@code putAll} as well, either providing your own implementation, or delegating
* to the provided {@code standardPutAll} method.
*
* <p>Each of the {@code standard} methods uses the map's comparator (or the natural ordering of
* the elements, if there is no comparator) to test element equality. As a result, if the comparator
* is not consistent with equals, some of the standard implementations may violate the {@code Map}
* contract.
*
* <p>The {@code standard} methods and the collection views they return are not guaranteed to be
* thread-safe, even when all of the methods that they depend on are thread-safe.
*
* @author Louis Wasserman
* @since 12.0
*/
public abstract class ForwardingNavigableMap<K, V>
extends ForwardingSortedMap<K, V> implements NavigableMap<K, V> {
/** Constructor for use by subclasses. */
protected ForwardingNavigableMap() {}
@Override
protected abstract NavigableMap<K, V> delegate();
@Override
public Entry<K, V> lowerEntry(K key) {
return delegate().lowerEntry(key);
}
/**
* A sensible definition of {@link #lowerEntry} in terms of the {@code lastEntry()} of
* {@link #headMap(Object, boolean)}. If you override {@code headMap}, you may wish to override
* {@code lowerEntry} to forward to this implementation.
*/
protected Entry<K, V> standardLowerEntry(K key) {
return headMap(key, false).lastEntry();
}
@Override
public K lowerKey(K key) {
return delegate().lowerKey(key);
}
/**
* A sensible definition of {@link #lowerKey} in terms of {@code lowerEntry}. If you override
* {@link #lowerEntry}, you may wish to override {@code lowerKey} to forward to this
* implementation.
*/
protected K standardLowerKey(K key) {
return keyOrNull(lowerEntry(key));
}
@Override
public Entry<K, V> floorEntry(K key) {
return delegate().floorEntry(key);
}
/**
* A sensible definition of {@link #floorEntry} in terms of the {@code lastEntry()} of
* {@link #headMap(Object, boolean)}. If you override {@code headMap}, you may wish to override
* {@code floorEntry} to forward to this implementation.
*/
protected Entry<K, V> standardFloorEntry(K key) {
return headMap(key, true).lastEntry();
}
@Override
public K floorKey(K key) {
return delegate().floorKey(key);
}
/**
* A sensible definition of {@link #floorKey} in terms of {@code floorEntry}. If you override
* {@code floorEntry}, you may wish to override {@code floorKey} to forward to this
* implementation.
*/
protected K standardFloorKey(K key) {
return keyOrNull(floorEntry(key));
}
@Override
public Entry<K, V> ceilingEntry(K key) {
return delegate().ceilingEntry(key);
}
/**
* A sensible definition of {@link #ceilingEntry} in terms of the {@code firstEntry()} of
* {@link #tailMap(Object, boolean)}. If you override {@code tailMap}, you may wish to override
* {@code ceilingEntry} to forward to this implementation.
*/
protected Entry<K, V> standardCeilingEntry(K key) {
return tailMap(key, true).firstEntry();
}
@Override
public K ceilingKey(K key) {
return delegate().ceilingKey(key);
}
/**
* A sensible definition of {@link #ceilingKey} in terms of {@code ceilingEntry}. If you override
* {@code ceilingEntry}, you may wish to override {@code ceilingKey} to forward to this
* implementation.
*/
protected K standardCeilingKey(K key) {
return keyOrNull(ceilingEntry(key));
}
@Override
public Entry<K, V> higherEntry(K key) {
return delegate().higherEntry(key);
}
/**
* A sensible definition of {@link #higherEntry} in terms of the {@code firstEntry()} of
* {@link #tailMap(Object, boolean)}. If you override {@code tailMap}, you may wish to override
* {@code higherEntry} to forward to this implementation.
*/
protected Entry<K, V> standardHigherEntry(K key) {
return tailMap(key, false).firstEntry();
}
@Override
public K higherKey(K key) {
return delegate().higherKey(key);
}
/**
* A sensible definition of {@link #higherKey} in terms of {@code higherEntry}. If you override
* {@code higherEntry}, you may wish to override {@code higherKey} to forward to this
* implementation.
*/
protected K standardHigherKey(K key) {
return keyOrNull(higherEntry(key));
}
@Override
public Entry<K, V> firstEntry() {
return delegate().firstEntry();
}
/**
* A sensible definition of {@link #firstEntry} in terms of the {@code iterator()} of
* {@link #entrySet}. If you override {@code entrySet}, you may wish to override
* {@code firstEntry} to forward to this implementation.
*/
protected Entry<K, V> standardFirstEntry() {
return Iterables.getFirst(entrySet(), null);
}
/**
* A sensible definition of {@link #firstKey} in terms of {@code firstEntry}. If you override
* {@code firstEntry}, you may wish to override {@code firstKey} to forward to this
* implementation.
*/
protected K standardFirstKey() {
Entry<K, V> entry = firstEntry();
if (entry == null) {
throw new NoSuchElementException();
} else {
return entry.getKey();
}
}
@Override
public Entry<K, V> lastEntry() {
return delegate().lastEntry();
}
/**
* A sensible definition of {@link #lastEntry} in terms of the {@code iterator()} of the
* {@link #entrySet} of {@link #descendingMap}. If you override {@code descendingMap}, you may
* wish to override {@code lastEntry} to forward to this implementation.
*/
protected Entry<K, V> standardLastEntry() {
return Iterables.getFirst(descendingMap().entrySet(), null);
}
/**
* A sensible definition of {@link #lastKey} in terms of {@code lastEntry}. If you override
* {@code lastEntry}, you may wish to override {@code lastKey} to forward to this implementation.
*/
protected K standardLastKey() {
Entry<K, V> entry = lastEntry();
if (entry == null) {
throw new NoSuchElementException();
} else {
return entry.getKey();
}
}
@Override
public Entry<K, V> pollFirstEntry() {
return delegate().pollFirstEntry();
}
/**
* A sensible definition of {@link #pollFirstEntry} in terms of the {@code iterator} of
* {@code entrySet}. If you override {@code entrySet}, you may wish to override
* {@code pollFirstEntry} to forward to this implementation.
*/
protected Entry<K, V> standardPollFirstEntry() {
return Iterators.pollNext(entrySet().iterator());
}
@Override
public Entry<K, V> pollLastEntry() {
return delegate().pollLastEntry();
}
/**
* A sensible definition of {@link #pollFirstEntry} in terms of the {@code iterator} of the
* {@code entrySet} of {@code descendingMap}. If you override {@code descendingMap}, you may wish
* to override {@code pollFirstEntry} to forward to this implementation.
*/
protected Entry<K, V> standardPollLastEntry() {
return Iterators.pollNext(descendingMap().entrySet().iterator());
}
@Override
public NavigableMap<K, V> descendingMap() {
return delegate().descendingMap();
}
/**
* A sensible implementation of {@link NavigableMap#descendingMap} in terms of the methods of
* this {@code NavigableMap}. In many cases, you may wish to override
* {@link ForwardingNavigableMap#descendingMap} to forward to this implementation or a subclass
* thereof.
*
* <p>In particular, this map iterates over entries with repeated calls to
* {@link NavigableMap#lowerEntry}. If a more efficient means of iteration is available, you may
* wish to override the {@code entryIterator()} method of this class.
*
* @since 12.0
*/
@Beta
protected class StandardDescendingMap extends Maps.DescendingMap<K, V> {
/** Constructor for use by subclasses. */
public StandardDescendingMap() {}
@Override
NavigableMap<K, V> forward() {
return ForwardingNavigableMap.this;
}
@Override
protected Iterator<Entry<K, V>> entryIterator() {
return new Iterator<Entry<K, V>>() {
private Entry<K, V> toRemove = null;
private Entry<K, V> nextOrNull = forward().lastEntry();
@Override
public boolean hasNext() {
return nextOrNull != null;
}
@Override
public java.util.Map.Entry<K, V> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
try {
return nextOrNull;
} finally {
toRemove = nextOrNull;
nextOrNull = forward().lowerEntry(nextOrNull.getKey());
}
}
@Override
public void remove() {
Iterators.checkRemove(toRemove != null);
forward().remove(toRemove.getKey());
toRemove = null;
}
};
}
}
@Override
public NavigableSet<K> navigableKeySet() {
return delegate().navigableKeySet();
}
/**
* A sensible implementation of {@link NavigableMap#navigableKeySet} in terms of the methods of
* this {@code NavigableMap}. In many cases, you may wish to override
* {@link ForwardingNavigableMap#navigableKeySet} to forward to this implementation or a subclass
* thereof.
*
* @since 12.0
*/
@Beta
protected class StandardNavigableKeySet extends Maps.NavigableKeySet<K, V> {
/** Constructor for use by subclasses. */
public StandardNavigableKeySet() {
super(ForwardingNavigableMap.this);
}
}
@Override
public NavigableSet<K> descendingKeySet() {
return delegate().descendingKeySet();
}
/**
* A sensible definition of {@link #descendingKeySet} as the {@code navigableKeySet} of
* {@link #descendingMap}. (The {@link StandardDescendingMap} implementation implements
* {@code navigableKeySet} on its own, so as not to cause an infinite loop.) If you override
* {@code descendingMap}, you may wish to override {@code descendingKeySet} to forward to this
* implementation.
*/
@Beta
protected NavigableSet<K> standardDescendingKeySet() {
return descendingMap().navigableKeySet();
}
/**
* A sensible definition of {@link #subMap(Object, Object)} in terms of
* {@link #subMap(Object, boolean, Object, boolean)}. If you override
* {@code subMap(K, boolean, K, boolean)}, you may wish to override {@code subMap} to forward to
* this implementation.
*/
@Override
protected SortedMap<K, V> standardSubMap(K fromKey, K toKey) {
return subMap(fromKey, true, toKey, false);
}
@Override
public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
return delegate().subMap(fromKey, fromInclusive, toKey, toInclusive);
}
@Override
public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
return delegate().headMap(toKey, inclusive);
}
@Override
public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
return delegate().tailMap(fromKey, inclusive);
}
/**
* A sensible definition of {@link #headMap(Object)} in terms of
* {@link #headMap(Object, boolean)}. If you override {@code headMap(K, boolean)}, you may wish
* to override {@code headMap} to forward to this implementation.
*/
protected SortedMap<K, V> standardHeadMap(K toKey) {
return headMap(toKey, false);
}
/**
* A sensible definition of {@link #tailMap(Object)} in terms of
* {@link #tailMap(Object, boolean)}. If you override {@code tailMap(K, boolean)}, you may wish
* to override {@code tailMap} to forward to this implementation.
*/
protected SortedMap<K, V> standardTailMap(K fromKey) {
return tailMap(fromKey, true);
}
}
| Java |
/*
* Copyright (C) 2007 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.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.Maps.ImprovedAbstractMap;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.RandomAccess;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Basic implementation of the {@link Multimap} interface. This class represents
* a multimap as a map that associates each key with a collection of values. All
* methods of {@link Multimap} are supported, including those specified as
* optional in the interface.
*
* <p>To implement a multimap, a subclass must define the method {@link
* #createCollection()}, which creates an empty collection of values for a key.
*
* <p>The multimap constructor takes a map that has a single entry for each
* distinct key. When you insert a key-value pair with a key that isn't already
* in the multimap, {@code AbstractMapBasedMultimap} calls {@link #createCollection()}
* to create the collection of values for that key. The subclass should not call
* {@link #createCollection()} directly, and a new instance should be created
* every time the method is called.
*
* <p>For example, the subclass could pass a {@link java.util.TreeMap} during
* construction, and {@link #createCollection()} could return a {@link
* java.util.TreeSet}, in which case the multimap's iterators would propagate
* through the keys and values in sorted order.
*
* <p>Keys and values may be null, as long as the underlying collection classes
* support null elements.
*
* <p>The collections created by {@link #createCollection()} may or may not
* allow duplicates. If the collection, such as a {@link Set}, does not support
* duplicates, an added key-value pair will replace an existing pair with the
* same key and value, if such a pair is present. With collections like {@link
* List} that allow duplicates, the collection will keep the existing key-value
* pairs while adding a new pair.
*
* <p>This class is not threadsafe when any concurrent operations update the
* multimap, even if the underlying map and {@link #createCollection()} method
* return threadsafe classes. Concurrent read operations will work correctly. To
* allow concurrent update operations, wrap your multimap with a call to {@link
* Multimaps#synchronizedMultimap}.
*
* <p>For serialization to work, the subclass must specify explicit
* {@code readObject} and {@code writeObject} methods.
*
* @author Jared Levy
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
abstract class AbstractMapBasedMultimap<K, V> extends AbstractMultimap<K, V>
implements Serializable {
/*
* Here's an outline of the overall design.
*
* The map variable contains the collection of values associated with each
* key. When a key-value pair is added to a multimap that didn't previously
* contain any values for that key, a new collection generated by
* createCollection is added to the map. That same collection instance
* remains in the map as long as the multimap has any values for the key. If
* all values for the key are removed, the key and collection are removed
* from the map.
*
* The get method returns a WrappedCollection, which decorates the collection
* in the map (if the key is present) or an empty collection (if the key is
* not present). When the collection delegate in the WrappedCollection is
* empty, the multimap may contain subsequently added values for that key. To
* handle that situation, the WrappedCollection checks whether map contains
* an entry for the provided key, and if so replaces the delegate.
*/
private transient Map<K, Collection<V>> map;
private transient int totalSize;
/**
* Creates a new multimap that uses the provided map.
*
* @param map place to store the mapping from each key to its corresponding
* values
* @throws IllegalArgumentException if {@code map} is not empty
*/
protected AbstractMapBasedMultimap(Map<K, Collection<V>> map) {
checkArgument(map.isEmpty());
this.map = map;
}
/** Used during deserialization only. */
final void setMap(Map<K, Collection<V>> map) {
this.map = map;
totalSize = 0;
for (Collection<V> values : map.values()) {
checkArgument(!values.isEmpty());
totalSize += values.size();
}
}
/**
* Creates an unmodifiable, empty collection of values.
*
* <p>This is used in {@link #removeAll} on an empty key.
*/
Collection<V> createUnmodifiableEmptyCollection() {
return unmodifiableCollectionSubclass(createCollection());
}
/**
* Creates the collection of values for a single key.
*
* <p>Collections with weak, soft, or phantom references are not supported.
* Each call to {@code createCollection} should create a new instance.
*
* <p>The returned collection class determines whether duplicate key-value
* pairs are allowed.
*
* @return an empty collection of values
*/
abstract Collection<V> createCollection();
/**
* Creates the collection of values for an explicitly provided key. By
* default, it simply calls {@link #createCollection()}, which is the correct
* behavior for most implementations. The {@link LinkedHashMultimap} class
* overrides it.
*
* @param key key to associate with values in the collection
* @return an empty collection of values
*/
Collection<V> createCollection(@Nullable K key) {
return createCollection();
}
Map<K, Collection<V>> backingMap() {
return map;
}
// Query Operations
@Override
public int size() {
return totalSize;
}
@Override
public boolean containsKey(@Nullable Object key) {
return map.containsKey(key);
}
// Modification Operations
@Override
public boolean put(@Nullable K key, @Nullable V value) {
Collection<V> collection = map.get(key);
if (collection == null) {
collection = createCollection(key);
if (collection.add(value)) {
totalSize++;
map.put(key, collection);
return true;
} else {
throw new AssertionError("New Collection violated the Collection spec");
}
} else if (collection.add(value)) {
totalSize++;
return true;
} else {
return false;
}
}
private Collection<V> getOrCreateCollection(@Nullable K key) {
Collection<V> collection = map.get(key);
if (collection == null) {
collection = createCollection(key);
map.put(key, collection);
}
return collection;
}
// Bulk Operations
/**
* {@inheritDoc}
*
* <p>The returned collection is immutable.
*/
@Override
public Collection<V> replaceValues(@Nullable K key, Iterable<? extends V> values) {
Iterator<? extends V> iterator = values.iterator();
if (!iterator.hasNext()) {
return removeAll(key);
}
// TODO(user): investigate atomic failure?
Collection<V> collection = getOrCreateCollection(key);
Collection<V> oldValues = createCollection();
oldValues.addAll(collection);
totalSize -= collection.size();
collection.clear();
while (iterator.hasNext()) {
if (collection.add(iterator.next())) {
totalSize++;
}
}
return unmodifiableCollectionSubclass(oldValues);
}
/**
* {@inheritDoc}
*
* <p>The returned collection is immutable.
*/
@Override
public Collection<V> removeAll(@Nullable Object key) {
Collection<V> collection = map.remove(key);
if (collection == null) {
return createUnmodifiableEmptyCollection();
}
Collection<V> output = createCollection();
output.addAll(collection);
totalSize -= collection.size();
collection.clear();
return unmodifiableCollectionSubclass(output);
}
Collection<V> unmodifiableCollectionSubclass(Collection<V> collection) {
// We don't deal with NavigableSet here yet for GWT reasons -- instead,
// non-GWT TreeMultimap explicitly overrides this and uses NavigableSet.
if (collection instanceof SortedSet) {
return Collections.unmodifiableSortedSet((SortedSet<V>) collection);
} else if (collection instanceof Set) {
return Collections.unmodifiableSet((Set<V>) collection);
} else if (collection instanceof List) {
return Collections.unmodifiableList((List<V>) collection);
} else {
return Collections.unmodifiableCollection(collection);
}
}
@Override
public void clear() {
// Clear each collection, to make previously returned collections empty.
for (Collection<V> collection : map.values()) {
collection.clear();
}
map.clear();
totalSize = 0;
}
// Views
/**
* {@inheritDoc}
*
* <p>The returned collection is not serializable.
*/
@Override
public Collection<V> get(@Nullable K key) {
Collection<V> collection = map.get(key);
if (collection == null) {
collection = createCollection(key);
}
return wrapCollection(key, collection);
}
/**
* Generates a decorated collection that remains consistent with the values in
* the multimap for the provided key. Changes to the multimap may alter the
* returned collection, and vice versa.
*/
Collection<V> wrapCollection(@Nullable K key, Collection<V> collection) {
// We don't deal with NavigableSet here yet for GWT reasons -- instead,
// non-GWT TreeMultimap explicitly overrides this and uses NavigableSet.
if (collection instanceof SortedSet) {
return new WrappedSortedSet(key, (SortedSet<V>) collection, null);
} else if (collection instanceof Set) {
return new WrappedSet(key, (Set<V>) collection);
} else if (collection instanceof List) {
return wrapList(key, (List<V>) collection, null);
} else {
return new WrappedCollection(key, collection, null);
}
}
private List<V> wrapList(
@Nullable K key, List<V> list, @Nullable WrappedCollection ancestor) {
return (list instanceof RandomAccess)
? new RandomAccessWrappedList(key, list, ancestor)
: new WrappedList(key, list, ancestor);
}
/**
* Collection decorator that stays in sync with the multimap values for a key.
* There are two kinds of wrapped collections: full and subcollections. Both
* have a delegate pointing to the underlying collection class.
*
* <p>Full collections, identified by a null ancestor field, contain all
* multimap values for a given key. Its delegate is a value in {@link
* AbstractMapBasedMultimap#map} whenever the delegate is non-empty. The {@code
* refreshIfEmpty}, {@code removeIfEmpty}, and {@code addToMap} methods ensure
* that the {@code WrappedCollection} and map remain consistent.
*
* <p>A subcollection, such as a sublist, contains some of the values for a
* given key. Its ancestor field points to the full wrapped collection with
* all values for the key. The subcollection {@code refreshIfEmpty}, {@code
* removeIfEmpty}, and {@code addToMap} methods call the corresponding methods
* of the full wrapped collection.
*/
private class WrappedCollection extends AbstractCollection<V> {
final K key;
Collection<V> delegate;
final WrappedCollection ancestor;
final Collection<V> ancestorDelegate;
WrappedCollection(@Nullable K key, Collection<V> delegate,
@Nullable WrappedCollection ancestor) {
this.key = key;
this.delegate = delegate;
this.ancestor = ancestor;
this.ancestorDelegate
= (ancestor == null) ? null : ancestor.getDelegate();
}
/**
* If the delegate collection is empty, but the multimap has values for the
* key, replace the delegate with the new collection for the key.
*
* <p>For a subcollection, refresh its ancestor and validate that the
* ancestor delegate hasn't changed.
*/
void refreshIfEmpty() {
if (ancestor != null) {
ancestor.refreshIfEmpty();
if (ancestor.getDelegate() != ancestorDelegate) {
throw new ConcurrentModificationException();
}
} else if (delegate.isEmpty()) {
Collection<V> newDelegate = map.get(key);
if (newDelegate != null) {
delegate = newDelegate;
}
}
}
/**
* If collection is empty, remove it from {@code AbstractMapBasedMultimap.this.map}.
* For subcollections, check whether the ancestor collection is empty.
*/
void removeIfEmpty() {
if (ancestor != null) {
ancestor.removeIfEmpty();
} else if (delegate.isEmpty()) {
map.remove(key);
}
}
K getKey() {
return key;
}
/**
* Add the delegate to the map. Other {@code WrappedCollection} methods
* should call this method after adding elements to a previously empty
* collection.
*
* <p>Subcollection add the ancestor's delegate instead.
*/
void addToMap() {
if (ancestor != null) {
ancestor.addToMap();
} else {
map.put(key, delegate);
}
}
@Override public int size() {
refreshIfEmpty();
return delegate.size();
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
refreshIfEmpty();
return delegate.equals(object);
}
@Override public int hashCode() {
refreshIfEmpty();
return delegate.hashCode();
}
@Override public String toString() {
refreshIfEmpty();
return delegate.toString();
}
Collection<V> getDelegate() {
return delegate;
}
@Override public Iterator<V> iterator() {
refreshIfEmpty();
return new WrappedIterator();
}
/** Collection iterator for {@code WrappedCollection}. */
class WrappedIterator implements Iterator<V> {
final Iterator<V> delegateIterator;
final Collection<V> originalDelegate = delegate;
WrappedIterator() {
delegateIterator = iteratorOrListIterator(delegate);
}
WrappedIterator(Iterator<V> delegateIterator) {
this.delegateIterator = delegateIterator;
}
/**
* If the delegate changed since the iterator was created, the iterator is
* no longer valid.
*/
void validateIterator() {
refreshIfEmpty();
if (delegate != originalDelegate) {
throw new ConcurrentModificationException();
}
}
@Override
public boolean hasNext() {
validateIterator();
return delegateIterator.hasNext();
}
@Override
public V next() {
validateIterator();
return delegateIterator.next();
}
@Override
public void remove() {
delegateIterator.remove();
totalSize--;
removeIfEmpty();
}
Iterator<V> getDelegateIterator() {
validateIterator();
return delegateIterator;
}
}
@Override public boolean add(V value) {
refreshIfEmpty();
boolean wasEmpty = delegate.isEmpty();
boolean changed = delegate.add(value);
if (changed) {
totalSize++;
if (wasEmpty) {
addToMap();
}
}
return changed;
}
WrappedCollection getAncestor() {
return ancestor;
}
// The following methods are provided for better performance.
@Override public boolean addAll(Collection<? extends V> collection) {
if (collection.isEmpty()) {
return false;
}
int oldSize = size(); // calls refreshIfEmpty
boolean changed = delegate.addAll(collection);
if (changed) {
int newSize = delegate.size();
totalSize += (newSize - oldSize);
if (oldSize == 0) {
addToMap();
}
}
return changed;
}
@Override public boolean contains(Object o) {
refreshIfEmpty();
return delegate.contains(o);
}
@Override public boolean containsAll(Collection<?> c) {
refreshIfEmpty();
return delegate.containsAll(c);
}
@Override public void clear() {
int oldSize = size(); // calls refreshIfEmpty
if (oldSize == 0) {
return;
}
delegate.clear();
totalSize -= oldSize;
removeIfEmpty(); // maybe shouldn't be removed if this is a sublist
}
@Override public boolean remove(Object o) {
refreshIfEmpty();
boolean changed = delegate.remove(o);
if (changed) {
totalSize--;
removeIfEmpty();
}
return changed;
}
@Override public boolean removeAll(Collection<?> c) {
if (c.isEmpty()) {
return false;
}
int oldSize = size(); // calls refreshIfEmpty
boolean changed = delegate.removeAll(c);
if (changed) {
int newSize = delegate.size();
totalSize += (newSize - oldSize);
removeIfEmpty();
}
return changed;
}
@Override public boolean retainAll(Collection<?> c) {
checkNotNull(c);
int oldSize = size(); // calls refreshIfEmpty
boolean changed = delegate.retainAll(c);
if (changed) {
int newSize = delegate.size();
totalSize += (newSize - oldSize);
removeIfEmpty();
}
return changed;
}
}
private Iterator<V> iteratorOrListIterator(Collection<V> collection) {
return (collection instanceof List)
? ((List<V>) collection).listIterator()
: collection.iterator();
}
/** Set decorator that stays in sync with the multimap values for a key. */
private class WrappedSet extends WrappedCollection implements Set<V> {
WrappedSet(@Nullable K key, Set<V> delegate) {
super(key, delegate, null);
}
@Override
public boolean removeAll(Collection<?> c) {
if (c.isEmpty()) {
return false;
}
int oldSize = size(); // calls refreshIfEmpty
// Guava issue 1013: AbstractSet and most JDK set implementations are
// susceptible to quadratic removeAll performance on lists;
// use a slightly smarter implementation here
boolean changed = Sets.removeAllImpl((Set<V>) delegate, c);
if (changed) {
int newSize = delegate.size();
totalSize += (newSize - oldSize);
removeIfEmpty();
}
return changed;
}
}
/**
* SortedSet decorator that stays in sync with the multimap values for a key.
*/
private class WrappedSortedSet extends WrappedCollection
implements SortedSet<V> {
WrappedSortedSet(@Nullable K key, SortedSet<V> delegate,
@Nullable WrappedCollection ancestor) {
super(key, delegate, ancestor);
}
SortedSet<V> getSortedSetDelegate() {
return (SortedSet<V>) getDelegate();
}
@Override
public Comparator<? super V> comparator() {
return getSortedSetDelegate().comparator();
}
@Override
public V first() {
refreshIfEmpty();
return getSortedSetDelegate().first();
}
@Override
public V last() {
refreshIfEmpty();
return getSortedSetDelegate().last();
}
@Override
public SortedSet<V> headSet(V toElement) {
refreshIfEmpty();
return new WrappedSortedSet(
getKey(), getSortedSetDelegate().headSet(toElement),
(getAncestor() == null) ? this : getAncestor());
}
@Override
public SortedSet<V> subSet(V fromElement, V toElement) {
refreshIfEmpty();
return new WrappedSortedSet(
getKey(), getSortedSetDelegate().subSet(fromElement, toElement),
(getAncestor() == null) ? this : getAncestor());
}
@Override
public SortedSet<V> tailSet(V fromElement) {
refreshIfEmpty();
return new WrappedSortedSet(
getKey(), getSortedSetDelegate().tailSet(fromElement),
(getAncestor() == null) ? this : getAncestor());
}
}
@GwtIncompatible("NavigableSet")
class WrappedNavigableSet extends WrappedSortedSet implements NavigableSet<V> {
WrappedNavigableSet(
@Nullable K key, NavigableSet<V> delegate, @Nullable WrappedCollection ancestor) {
super(key, delegate, ancestor);
}
@Override
NavigableSet<V> getSortedSetDelegate() {
return (NavigableSet<V>) super.getSortedSetDelegate();
}
@Override
public V lower(V v) {
return getSortedSetDelegate().lower(v);
}
@Override
public V floor(V v) {
return getSortedSetDelegate().floor(v);
}
@Override
public V ceiling(V v) {
return getSortedSetDelegate().ceiling(v);
}
@Override
public V higher(V v) {
return getSortedSetDelegate().higher(v);
}
@Override
public V pollFirst() {
return Iterators.pollNext(iterator());
}
@Override
public V pollLast() {
return Iterators.pollNext(descendingIterator());
}
private NavigableSet<V> wrap(NavigableSet<V> wrapped) {
return new WrappedNavigableSet(key, wrapped,
(getAncestor() == null) ? this : getAncestor());
}
@Override
public NavigableSet<V> descendingSet() {
return wrap(getSortedSetDelegate().descendingSet());
}
@Override
public Iterator<V> descendingIterator() {
return new WrappedIterator(getSortedSetDelegate().descendingIterator());
}
@Override
public NavigableSet<V> subSet(
V fromElement, boolean fromInclusive, V toElement, boolean toInclusive) {
return wrap(
getSortedSetDelegate().subSet(fromElement, fromInclusive, toElement, toInclusive));
}
@Override
public NavigableSet<V> headSet(V toElement, boolean inclusive) {
return wrap(getSortedSetDelegate().headSet(toElement, inclusive));
}
@Override
public NavigableSet<V> tailSet(V fromElement, boolean inclusive) {
return wrap(getSortedSetDelegate().tailSet(fromElement, inclusive));
}
}
/** List decorator that stays in sync with the multimap values for a key. */
private class WrappedList extends WrappedCollection implements List<V> {
WrappedList(@Nullable K key, List<V> delegate,
@Nullable WrappedCollection ancestor) {
super(key, delegate, ancestor);
}
List<V> getListDelegate() {
return (List<V>) getDelegate();
}
@Override
public boolean addAll(int index, Collection<? extends V> c) {
if (c.isEmpty()) {
return false;
}
int oldSize = size(); // calls refreshIfEmpty
boolean changed = getListDelegate().addAll(index, c);
if (changed) {
int newSize = getDelegate().size();
totalSize += (newSize - oldSize);
if (oldSize == 0) {
addToMap();
}
}
return changed;
}
@Override
public V get(int index) {
refreshIfEmpty();
return getListDelegate().get(index);
}
@Override
public V set(int index, V element) {
refreshIfEmpty();
return getListDelegate().set(index, element);
}
@Override
public void add(int index, V element) {
refreshIfEmpty();
boolean wasEmpty = getDelegate().isEmpty();
getListDelegate().add(index, element);
totalSize++;
if (wasEmpty) {
addToMap();
}
}
@Override
public V remove(int index) {
refreshIfEmpty();
V value = getListDelegate().remove(index);
totalSize--;
removeIfEmpty();
return value;
}
@Override
public int indexOf(Object o) {
refreshIfEmpty();
return getListDelegate().indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
refreshIfEmpty();
return getListDelegate().lastIndexOf(o);
}
@Override
public ListIterator<V> listIterator() {
refreshIfEmpty();
return new WrappedListIterator();
}
@Override
public ListIterator<V> listIterator(int index) {
refreshIfEmpty();
return new WrappedListIterator(index);
}
@Override
public List<V> subList(int fromIndex, int toIndex) {
refreshIfEmpty();
return wrapList(getKey(),
getListDelegate().subList(fromIndex, toIndex),
(getAncestor() == null) ? this : getAncestor());
}
/** ListIterator decorator. */
private class WrappedListIterator extends WrappedIterator
implements ListIterator<V> {
WrappedListIterator() {}
public WrappedListIterator(int index) {
super(getListDelegate().listIterator(index));
}
private ListIterator<V> getDelegateListIterator() {
return (ListIterator<V>) getDelegateIterator();
}
@Override
public boolean hasPrevious() {
return getDelegateListIterator().hasPrevious();
}
@Override
public V previous() {
return getDelegateListIterator().previous();
}
@Override
public int nextIndex() {
return getDelegateListIterator().nextIndex();
}
@Override
public int previousIndex() {
return getDelegateListIterator().previousIndex();
}
@Override
public void set(V value) {
getDelegateListIterator().set(value);
}
@Override
public void add(V value) {
boolean wasEmpty = isEmpty();
getDelegateListIterator().add(value);
totalSize++;
if (wasEmpty) {
addToMap();
}
}
}
}
/**
* List decorator that stays in sync with the multimap values for a key and
* supports rapid random access.
*/
private class RandomAccessWrappedList extends WrappedList
implements RandomAccess {
RandomAccessWrappedList(@Nullable K key, List<V> delegate,
@Nullable WrappedCollection ancestor) {
super(key, delegate, ancestor);
}
}
@Override
Set<K> createKeySet() {
// TreeMultimap uses NavigableKeySet explicitly, but we don't handle that here for GWT
// compatibility reasons
return (map instanceof SortedMap)
? new SortedKeySet((SortedMap<K, Collection<V>>) map) : new KeySet(map);
}
private class KeySet extends Maps.KeySet<K, Collection<V>> {
KeySet(final Map<K, Collection<V>> subMap) {
super(subMap);
}
@Override public Iterator<K> iterator() {
final Iterator<Map.Entry<K, Collection<V>>> entryIterator
= map().entrySet().iterator();
return new Iterator<K>() {
Map.Entry<K, Collection<V>> entry;
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public K next() {
entry = entryIterator.next();
return entry.getKey();
}
@Override
public void remove() {
Iterators.checkRemove(entry != null);
Collection<V> collection = entry.getValue();
entryIterator.remove();
totalSize -= collection.size();
collection.clear();
}
};
}
// The following methods are included for better performance.
@Override public boolean remove(Object key) {
int count = 0;
Collection<V> collection = map().remove(key);
if (collection != null) {
count = collection.size();
collection.clear();
totalSize -= count;
}
return count > 0;
}
@Override
public void clear() {
Iterators.clear(iterator());
}
@Override public boolean containsAll(Collection<?> c) {
return map().keySet().containsAll(c);
}
@Override public boolean equals(@Nullable Object object) {
return this == object || this.map().keySet().equals(object);
}
@Override public int hashCode() {
return map().keySet().hashCode();
}
}
private class SortedKeySet extends KeySet implements SortedSet<K> {
SortedKeySet(SortedMap<K, Collection<V>> subMap) {
super(subMap);
}
SortedMap<K, Collection<V>> sortedMap() {
return (SortedMap<K, Collection<V>>) super.map();
}
@Override
public Comparator<? super K> comparator() {
return sortedMap().comparator();
}
@Override
public K first() {
return sortedMap().firstKey();
}
@Override
public SortedSet<K> headSet(K toElement) {
return new SortedKeySet(sortedMap().headMap(toElement));
}
@Override
public K last() {
return sortedMap().lastKey();
}
@Override
public SortedSet<K> subSet(K fromElement, K toElement) {
return new SortedKeySet(sortedMap().subMap(fromElement, toElement));
}
@Override
public SortedSet<K> tailSet(K fromElement) {
return new SortedKeySet(sortedMap().tailMap(fromElement));
}
}
@GwtIncompatible("NavigableSet")
class NavigableKeySet extends SortedKeySet implements NavigableSet<K> {
NavigableKeySet(NavigableMap<K, Collection<V>> subMap) {
super(subMap);
}
@Override
NavigableMap<K, Collection<V>> sortedMap() {
return (NavigableMap<K, Collection<V>>) super.sortedMap();
}
@Override
public K lower(K k) {
return sortedMap().lowerKey(k);
}
@Override
public K floor(K k) {
return sortedMap().floorKey(k);
}
@Override
public K ceiling(K k) {
return sortedMap().ceilingKey(k);
}
@Override
public K higher(K k) {
return sortedMap().higherKey(k);
}
@Override
public K pollFirst() {
return Iterators.pollNext(iterator());
}
@Override
public K pollLast() {
return Iterators.pollNext(descendingIterator());
}
@Override
public NavigableSet<K> descendingSet() {
return new NavigableKeySet(sortedMap().descendingMap());
}
@Override
public Iterator<K> descendingIterator() {
return descendingSet().iterator();
}
@Override
public NavigableSet<K> headSet(K toElement) {
return headSet(toElement, false);
}
@Override
public NavigableSet<K> headSet(K toElement, boolean inclusive) {
return new NavigableKeySet(sortedMap().headMap(toElement, inclusive));
}
@Override
public NavigableSet<K> subSet(K fromElement, K toElement) {
return subSet(fromElement, true, toElement, false);
}
@Override
public NavigableSet<K> subSet(
K fromElement, boolean fromInclusive, K toElement, boolean toInclusive) {
return new NavigableKeySet(
sortedMap().subMap(fromElement, fromInclusive, toElement, toInclusive));
}
@Override
public NavigableSet<K> tailSet(K fromElement) {
return tailSet(fromElement, true);
}
@Override
public NavigableSet<K> tailSet(K fromElement, boolean inclusive) {
return new NavigableKeySet(sortedMap().tailMap(fromElement, inclusive));
}
}
/**
* Removes all values for the provided key. Unlike {@link #removeAll}, it
* returns the number of removed mappings.
*/
private int removeValuesForKey(Object key) {
Collection<V> collection = Maps.safeRemove(map, key);
int count = 0;
if (collection != null) {
count = collection.size();
collection.clear();
totalSize -= count;
}
return count;
}
private abstract class Itr<T> implements Iterator<T> {
final Iterator<Map.Entry<K, Collection<V>>> keyIterator;
K key;
Collection<V> collection;
Iterator<V> valueIterator;
Itr() {
keyIterator = map.entrySet().iterator();
key = null;
collection = null;
valueIterator = Iterators.emptyModifiableIterator();
}
abstract T output(K key, V value);
@Override
public boolean hasNext() {
return keyIterator.hasNext() || valueIterator.hasNext();
}
@Override
public T next() {
if (!valueIterator.hasNext()) {
Map.Entry<K, Collection<V>> mapEntry = keyIterator.next();
key = mapEntry.getKey();
collection = mapEntry.getValue();
valueIterator = collection.iterator();
}
return output(key, valueIterator.next());
}
@Override
public void remove() {
valueIterator.remove();
if (collection.isEmpty()) {
keyIterator.remove();
}
totalSize--;
}
}
/**
* {@inheritDoc}
*
* <p>The iterator generated by the returned collection traverses the values
* for one key, followed by the values of a second key, and so on.
*/
@Override public Collection<V> values() {
return super.values();
}
@Override
Iterator<V> valueIterator() {
return new Itr<V>() {
@Override
V output(K key, V value) {
return value;
}
};
}
/*
* TODO(kevinb): should we copy this javadoc to each concrete class, so that
* classes like LinkedHashMultimap that need to say something different are
* still able to {@inheritDoc} all the way from Multimap?
*/
/**
* {@inheritDoc}
*
* <p>The iterator generated by the returned collection traverses the values
* for one key, followed by the values of a second key, and so on.
*
* <p>Each entry is an immutable snapshot of a key-value mapping in the
* multimap, taken at the time the entry is returned by a method call to the
* collection or its iterator.
*/
@Override
public Collection<Map.Entry<K, V>> entries() {
return super.entries();
}
/**
* Returns an iterator across all key-value map entries, used by {@code
* entries().iterator()} and {@code values().iterator()}. The default
* behavior, which traverses the values for one key, the values for a second
* key, and so on, suffices for most {@code AbstractMapBasedMultimap} implementations.
*
* @return an iterator across map entries
*/
@Override
Iterator<Map.Entry<K, V>> entryIterator() {
return new Itr<Map.Entry<K, V>>() {
@Override
Entry<K, V> output(K key, V value) {
return Maps.immutableEntry(key, value);
}
};
}
@Override
Map<K, Collection<V>> createAsMap() {
// TreeMultimap uses NavigableAsMap explicitly, but we don't handle that here for GWT
// compatibility reasons
return (map instanceof SortedMap)
? new SortedAsMap((SortedMap<K, Collection<V>>) map) : new AsMap(map);
}
private class AsMap extends ImprovedAbstractMap<K, Collection<V>> {
/**
* Usually the same as map, but smaller for the headMap(), tailMap(), or
* subMap() of a SortedAsMap.
*/
final transient Map<K, Collection<V>> submap;
AsMap(Map<K, Collection<V>> submap) {
this.submap = submap;
}
@Override
protected Set<Entry<K, Collection<V>>> createEntrySet() {
return new AsMapEntries();
}
// The following methods are included for performance.
@Override public boolean containsKey(Object key) {
return Maps.safeContainsKey(submap, key);
}
@Override public Collection<V> get(Object key) {
Collection<V> collection = Maps.safeGet(submap, key);
if (collection == null) {
return null;
}
@SuppressWarnings("unchecked")
K k = (K) key;
return wrapCollection(k, collection);
}
@Override public Set<K> keySet() {
return AbstractMapBasedMultimap.this.keySet();
}
@Override
public int size() {
return submap.size();
}
@Override public Collection<V> remove(Object key) {
Collection<V> collection = submap.remove(key);
if (collection == null) {
return null;
}
Collection<V> output = createCollection();
output.addAll(collection);
totalSize -= collection.size();
collection.clear();
return output;
}
@Override public boolean equals(@Nullable Object object) {
return this == object || submap.equals(object);
}
@Override public int hashCode() {
return submap.hashCode();
}
@Override public String toString() {
return submap.toString();
}
@Override
public void clear() {
if (submap == map) {
AbstractMapBasedMultimap.this.clear();
} else {
Iterators.clear(new AsMapIterator());
}
}
Entry<K, Collection<V>> wrapEntry(Entry<K, Collection<V>> entry) {
K key = entry.getKey();
return Maps.immutableEntry(key, wrapCollection(key, entry.getValue()));
}
class AsMapEntries extends Maps.EntrySet<K, Collection<V>> {
@Override
Map<K, Collection<V>> map() {
return AsMap.this;
}
@Override public Iterator<Map.Entry<K, Collection<V>>> iterator() {
return new AsMapIterator();
}
// The following methods are included for performance.
@Override public boolean contains(Object o) {
return Collections2.safeContains(submap.entrySet(), o);
}
@Override public boolean remove(Object o) {
if (!contains(o)) {
return false;
}
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
removeValuesForKey(entry.getKey());
return true;
}
}
/** Iterator across all keys and value collections. */
class AsMapIterator implements Iterator<Map.Entry<K, Collection<V>>> {
final Iterator<Map.Entry<K, Collection<V>>> delegateIterator
= submap.entrySet().iterator();
Collection<V> collection;
@Override
public boolean hasNext() {
return delegateIterator.hasNext();
}
@Override
public Map.Entry<K, Collection<V>> next() {
Map.Entry<K, Collection<V>> entry = delegateIterator.next();
collection = entry.getValue();
return wrapEntry(entry);
}
@Override
public void remove() {
delegateIterator.remove();
totalSize -= collection.size();
collection.clear();
}
}
}
private class SortedAsMap extends AsMap
implements SortedMap<K, Collection<V>> {
SortedAsMap(SortedMap<K, Collection<V>> submap) {
super(submap);
}
SortedMap<K, Collection<V>> sortedMap() {
return (SortedMap<K, Collection<V>>) submap;
}
@Override
public Comparator<? super K> comparator() {
return sortedMap().comparator();
}
@Override
public K firstKey() {
return sortedMap().firstKey();
}
@Override
public K lastKey() {
return sortedMap().lastKey();
}
@Override
public SortedMap<K, Collection<V>> headMap(K toKey) {
return new SortedAsMap(sortedMap().headMap(toKey));
}
@Override
public SortedMap<K, Collection<V>> subMap(K fromKey, K toKey) {
return new SortedAsMap(sortedMap().subMap(fromKey, toKey));
}
@Override
public SortedMap<K, Collection<V>> tailMap(K fromKey) {
return new SortedAsMap(sortedMap().tailMap(fromKey));
}
SortedSet<K> sortedKeySet;
// returns a SortedSet, even though returning a Set would be sufficient to
// satisfy the SortedMap.keySet() interface
@Override public SortedSet<K> keySet() {
SortedSet<K> result = sortedKeySet;
return (result == null) ? sortedKeySet = createKeySet() : result;
}
@Override
SortedSet<K> createKeySet() {
return new SortedKeySet(sortedMap());
}
}
@GwtIncompatible("NavigableAsMap")
class NavigableAsMap extends SortedAsMap implements NavigableMap<K, Collection<V>> {
NavigableAsMap(NavigableMap<K, Collection<V>> submap) {
super(submap);
}
@Override
NavigableMap<K, Collection<V>> sortedMap() {
return (NavigableMap<K, Collection<V>>) super.sortedMap();
}
@Override
public Entry<K, Collection<V>> lowerEntry(K key) {
Entry<K, Collection<V>> entry = sortedMap().lowerEntry(key);
return (entry == null) ? null : wrapEntry(entry);
}
@Override
public K lowerKey(K key) {
return sortedMap().lowerKey(key);
}
@Override
public Entry<K, Collection<V>> floorEntry(K key) {
Entry<K, Collection<V>> entry = sortedMap().floorEntry(key);
return (entry == null) ? null : wrapEntry(entry);
}
@Override
public K floorKey(K key) {
return sortedMap().floorKey(key);
}
@Override
public Entry<K, Collection<V>> ceilingEntry(K key) {
Entry<K, Collection<V>> entry = sortedMap().ceilingEntry(key);
return (entry == null) ? null : wrapEntry(entry);
}
@Override
public K ceilingKey(K key) {
return sortedMap().ceilingKey(key);
}
@Override
public Entry<K, Collection<V>> higherEntry(K key) {
Entry<K, Collection<V>> entry = sortedMap().higherEntry(key);
return (entry == null) ? null : wrapEntry(entry);
}
@Override
public K higherKey(K key) {
return sortedMap().higherKey(key);
}
@Override
public Entry<K, Collection<V>> firstEntry() {
Entry<K, Collection<V>> entry = sortedMap().firstEntry();
return (entry == null) ? null : wrapEntry(entry);
}
@Override
public Entry<K, Collection<V>> lastEntry() {
Entry<K, Collection<V>> entry = sortedMap().lastEntry();
return (entry == null) ? null : wrapEntry(entry);
}
@Override
public Entry<K, Collection<V>> pollFirstEntry() {
return pollAsMapEntry(entrySet().iterator());
}
@Override
public Entry<K, Collection<V>> pollLastEntry() {
return pollAsMapEntry(descendingMap().entrySet().iterator());
}
Map.Entry<K, Collection<V>> pollAsMapEntry(Iterator<Entry<K, Collection<V>>> entryIterator) {
if (!entryIterator.hasNext()) {
return null;
}
Entry<K, Collection<V>> entry = entryIterator.next();
Collection<V> output = createCollection();
output.addAll(entry.getValue());
entryIterator.remove();
return Maps.immutableEntry(entry.getKey(), unmodifiableCollectionSubclass(output));
}
@Override
public NavigableMap<K, Collection<V>> descendingMap() {
return new NavigableAsMap(sortedMap().descendingMap());
}
@Override
public NavigableSet<K> keySet() {
return (NavigableSet<K>) super.keySet();
}
@Override
NavigableSet<K> createKeySet() {
return new NavigableKeySet(sortedMap());
}
@Override
public NavigableSet<K> navigableKeySet() {
return keySet();
}
@Override
public NavigableSet<K> descendingKeySet() {
return descendingMap().navigableKeySet();
}
@Override
public NavigableMap<K, Collection<V>> subMap(K fromKey, K toKey) {
return subMap(fromKey, true, toKey, false);
}
@Override
public NavigableMap<K, Collection<V>> subMap(
K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
return new NavigableAsMap(sortedMap().subMap(fromKey, fromInclusive, toKey, toInclusive));
}
@Override
public NavigableMap<K, Collection<V>> headMap(K toKey) {
return headMap(toKey, false);
}
@Override
public NavigableMap<K, Collection<V>> headMap(K toKey, boolean inclusive) {
return new NavigableAsMap(sortedMap().headMap(toKey, inclusive));
}
@Override
public NavigableMap<K, Collection<V>> tailMap(K fromKey) {
return tailMap(fromKey, true);
}
@Override
public NavigableMap<K, Collection<V>> tailMap(K fromKey, boolean inclusive) {
return new NavigableAsMap(sortedMap().tailMap(fromKey, inclusive));
}
}
private static final long serialVersionUID = 2447537837011683357L;
}
| Java |
/*
* Copyright (C) 2011 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.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
import java.util.SortedSet;
/**
* Utilities for dealing with sorted collections of all types.
*
* @author Louis Wasserman
*/
@GwtCompatible
final class SortedIterables {
private SortedIterables() {}
/**
* Returns {@code true} if {@code elements} is a sorted collection using an ordering equivalent
* to {@code comparator}.
*/
public static boolean hasSameComparator(Comparator<?> comparator, Iterable<?> elements) {
checkNotNull(comparator);
checkNotNull(elements);
Comparator<?> comparator2;
if (elements instanceof SortedSet) {
comparator2 = comparator((SortedSet<?>) elements);
} else if (elements instanceof SortedIterable) {
comparator2 = ((SortedIterable<?>) elements).comparator();
} else {
return false;
}
return comparator.equals(comparator2);
}
@SuppressWarnings("unchecked")
// if sortedSet.comparator() is null, the set must be naturally ordered
public static <E> Comparator<? super E> comparator(SortedSet<E> sortedSet) {
Comparator<? super E> result = sortedSet.comparator();
if (result == null) {
result = (Comparator<? super E>) Ordering.natural();
}
return result;
}
}
| Java |
/*
* Copyright (C) 2007 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.collect;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
/**
* An ordering that uses the natural order of the string representation of the
* values.
*/
@GwtCompatible(serializable = true)
final class UsingToStringOrdering
extends Ordering<Object> implements Serializable {
static final UsingToStringOrdering INSTANCE = new UsingToStringOrdering();
@Override public int compare(Object left, Object right) {
return left.toString().compareTo(right.toString());
}
// preserve singleton-ness, so equals() and hashCode() work correctly
private Object readResolve() {
return INSTANCE;
}
@Override public String toString() {
return "Ordering.usingToString()";
}
private UsingToStringOrdering() {}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2007 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.collect;
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.checkPositionIndex;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.math.IntMath;
import com.google.common.primitives.Ints;
import java.io.Serializable;
import java.math.RoundingMode;
import java.util.AbstractList;
import java.util.AbstractSequentialList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.RandomAccess;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to {@link List} instances. Also see this
* class's counterparts {@link Sets}, {@link Maps} and {@link Queues}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Lists">
* {@code Lists}</a>.
*
* @author Kevin Bourrillion
* @author Mike Bostock
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class Lists {
private Lists() {}
// ArrayList
/**
* Creates a <i>mutable</i>, empty {@code ArrayList} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableList#of()} instead.
*
* @return a new, empty {@code ArrayList}
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList() {
return new ArrayList<E>();
}
/**
* Creates a <i>mutable</i> {@code ArrayList} instance containing the given
* elements.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use an overload of {@link ImmutableList#of()} (for varargs) or
* {@link ImmutableList#copyOf(Object[])} (for an array) instead.
*
* @param elements the elements that the list should contain, in order
* @return a new {@code ArrayList} containing those elements
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList(E... elements) {
checkNotNull(elements); // for GWT
// Avoid integer overflow when a large array is passed in
int capacity = computeArrayListCapacity(elements.length);
ArrayList<E> list = new ArrayList<E>(capacity);
Collections.addAll(list, elements);
return list;
}
@VisibleForTesting static int computeArrayListCapacity(int arraySize) {
checkArgument(arraySize >= 0);
// TODO(kevinb): Figure out the right behavior, and document it
return Ints.saturatedCast(5L + arraySize + (arraySize / 10));
}
/**
* Creates a <i>mutable</i> {@code ArrayList} instance containing the given
* elements.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use {@link ImmutableList#copyOf(Iterator)} instead.
*
* @param elements the elements that the list should contain, in order
* @return a new {@code ArrayList} containing those elements
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList(Iterable<? extends E> elements) {
checkNotNull(elements); // for GWT
// Let ArrayList's sizing logic work, if possible
return (elements instanceof Collection)
? new ArrayList<E>(Collections2.cast(elements))
: newArrayList(elements.iterator());
}
/**
* Creates a <i>mutable</i> {@code ArrayList} instance containing the given
* elements.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use {@link ImmutableList#copyOf(Iterator)} instead.
*
* @param elements the elements that the list should contain, in order
* @return a new {@code ArrayList} containing those elements
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList(Iterator<? extends E> elements) {
ArrayList<E> list = newArrayList();
Iterators.addAll(list, elements);
return list;
}
/**
* Creates an {@code ArrayList} instance backed by an array of the
* <i>exact</i> size specified; equivalent to
* {@link ArrayList#ArrayList(int)}.
*
* <p><b>Note:</b> if you know the exact size your list will be, consider
* using a fixed-size list ({@link Arrays#asList(Object[])}) or an {@link
* ImmutableList} instead of a growable {@link ArrayList}.
*
* <p><b>Note:</b> If you have only an <i>estimate</i> of the eventual size of
* the list, consider padding this estimate by a suitable amount, or simply
* use {@link #newArrayListWithExpectedSize(int)} instead.
*
* @param initialArraySize the exact size of the initial backing array for
* the returned array list ({@code ArrayList} documentation calls this
* value the "capacity")
* @return a new, empty {@code ArrayList} which is guaranteed not to resize
* itself unless its size reaches {@code initialArraySize + 1}
* @throws IllegalArgumentException if {@code initialArraySize} is negative
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayListWithCapacity(
int initialArraySize) {
checkArgument(initialArraySize >= 0); // for GWT.
return new ArrayList<E>(initialArraySize);
}
/**
* Creates an {@code ArrayList} instance sized appropriately to hold an
* <i>estimated</i> number of elements without resizing. A small amount of
* padding is added in case the estimate is low.
*
* <p><b>Note:</b> If you know the <i>exact</i> number of elements the list
* will hold, or prefer to calculate your own amount of padding, refer to
* {@link #newArrayListWithCapacity(int)}.
*
* @param estimatedSize an estimate of the eventual {@link List#size()} of
* the new list
* @return a new, empty {@code ArrayList}, sized appropriately to hold the
* estimated number of elements
* @throws IllegalArgumentException if {@code estimatedSize} is negative
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayListWithExpectedSize(
int estimatedSize) {
return new ArrayList<E>(computeArrayListCapacity(estimatedSize));
}
// LinkedList
/**
* Creates an empty {@code LinkedList} instance.
*
* <p><b>Note:</b> if you need an immutable empty {@link List}, use
* {@link ImmutableList#of()} instead.
*
* @return a new, empty {@code LinkedList}
*/
@GwtCompatible(serializable = true)
public static <E> LinkedList<E> newLinkedList() {
return new LinkedList<E>();
}
/**
* Creates a {@code LinkedList} instance containing the given elements.
*
* @param elements the elements that the list should contain, in order
* @return a new {@code LinkedList} containing those elements
*/
@GwtCompatible(serializable = true)
public static <E> LinkedList<E> newLinkedList(
Iterable<? extends E> elements) {
LinkedList<E> list = newLinkedList();
Iterables.addAll(list, elements);
return list;
}
/**
* Creates an empty {@code CopyOnWriteArrayList} instance.
*
* <p><b>Note:</b> if you need an immutable empty {@link List}, use
* {@link Collections#emptyList} instead.
*
* @return a new, empty {@code CopyOnWriteArrayList}
* @since 12.0
*/
@GwtIncompatible("CopyOnWriteArrayList")
public static <E> CopyOnWriteArrayList<E> newCopyOnWriteArrayList() {
return new CopyOnWriteArrayList<E>();
}
/**
* Creates a {@code CopyOnWriteArrayList} instance containing the given elements.
*
* @param elements the elements that the list should contain, in order
* @return a new {@code CopyOnWriteArrayList} containing those elements
* @since 12.0
*/
@GwtIncompatible("CopyOnWriteArrayList")
public static <E> CopyOnWriteArrayList<E> newCopyOnWriteArrayList(
Iterable<? extends E> elements) {
// We copy elements to an ArrayList first, rather than incurring the
// quadratic cost of adding them to the COWAL directly.
Collection<? extends E> elementsCollection = (elements instanceof Collection)
? Collections2.cast(elements)
: newArrayList(elements);
return new CopyOnWriteArrayList<E>(elementsCollection);
}
/**
* Returns an unmodifiable list containing the specified first element and
* backed by the specified array of additional elements. Changes to the {@code
* rest} array will be reflected in the returned list. Unlike {@link
* Arrays#asList}, the returned list is unmodifiable.
*
* <p>This is useful when a varargs method needs to use a signature such as
* {@code (Foo firstFoo, Foo... moreFoos)}, in order to avoid overload
* ambiguity or to enforce a minimum argument count.
*
* <p>The returned list is serializable and implements {@link RandomAccess}.
*
* @param first the first element
* @param rest an array of additional elements, possibly empty
* @return an unmodifiable list containing the specified elements
*/
public static <E> List<E> asList(@Nullable E first, E[] rest) {
return new OnePlusArrayList<E>(first, rest);
}
/** @see Lists#asList(Object, Object[]) */
private static class OnePlusArrayList<E> extends AbstractList<E>
implements Serializable, RandomAccess {
final E first;
final E[] rest;
OnePlusArrayList(@Nullable E first, E[] rest) {
this.first = first;
this.rest = checkNotNull(rest);
}
@Override public int size() {
return rest.length + 1;
}
@Override public E get(int index) {
// check explicitly so the IOOBE will have the right message
checkElementIndex(index, size());
return (index == 0) ? first : rest[index - 1];
}
private static final long serialVersionUID = 0;
}
/**
* Returns an unmodifiable list containing the specified first and second
* element, and backed by the specified array of additional elements. Changes
* to the {@code rest} array will be reflected in the returned list. Unlike
* {@link Arrays#asList}, the returned list is unmodifiable.
*
* <p>This is useful when a varargs method needs to use a signature such as
* {@code (Foo firstFoo, Foo secondFoo, Foo... moreFoos)}, in order to avoid
* overload ambiguity or to enforce a minimum argument count.
*
* <p>The returned list is serializable and implements {@link RandomAccess}.
*
* @param first the first element
* @param second the second element
* @param rest an array of additional elements, possibly empty
* @return an unmodifiable list containing the specified elements
*/
public static <E> List<E> asList(
@Nullable E first, @Nullable E second, E[] rest) {
return new TwoPlusArrayList<E>(first, second, rest);
}
/** @see Lists#asList(Object, Object, Object[]) */
private static class TwoPlusArrayList<E> extends AbstractList<E>
implements Serializable, RandomAccess {
final E first;
final E second;
final E[] rest;
TwoPlusArrayList(@Nullable E first, @Nullable E second, E[] rest) {
this.first = first;
this.second = second;
this.rest = checkNotNull(rest);
}
@Override public int size() {
return rest.length + 2;
}
@Override public E get(int index) {
switch (index) {
case 0:
return first;
case 1:
return second;
default:
// check explicitly so the IOOBE will have the right message
checkElementIndex(index, size());
return rest[index - 2];
}
}
private static final long serialVersionUID = 0;
}
/**
* Returns every possible list that can be formed by choosing one element
* from each of the given lists in order; the "n-ary
* <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
* product</a>" of the lists. For example: <pre> {@code
*
* Lists.cartesianProduct(ImmutableList.of(
* ImmutableList.of(1, 2),
* ImmutableList.of("A", "B", "C")))}</pre>
*
* <p>returns a list containing six lists in the following order:
*
* <ul>
* <li>{@code ImmutableList.of(1, "A")}
* <li>{@code ImmutableList.of(1, "B")}
* <li>{@code ImmutableList.of(1, "C")}
* <li>{@code ImmutableList.of(2, "A")}
* <li>{@code ImmutableList.of(2, "B")}
* <li>{@code ImmutableList.of(2, "C")}
* </ul>
*
* <p>The result is guaranteed to be in the "traditional", lexicographical
* order for Cartesian products that you would get from nesting for loops:
* <pre> {@code
*
* for (B b0 : lists.get(0)) {
* for (B b1 : lists.get(1)) {
* ...
* ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
* // operate on tuple
* }
* }}</pre>
*
* <p>Note that if any input list is empty, the Cartesian product will also be
* empty. If no lists at all are provided (an empty list), the resulting
* Cartesian product has one element, an empty list (counter-intuitive, but
* mathematically consistent).
*
* <p><i>Performance notes:</i> while the cartesian product of lists of size
* {@code m, n, p} is a list of size {@code m x n x p}, its actual memory
* consumption is much smaller. When the cartesian product is constructed, the
* input lists are merely copied. Only as the resulting list is iterated are
* the individual lists created, and these are not retained after iteration.
*
* @param lists the lists to choose elements from, in the order that
* the elements chosen from those lists should appear in the resulting
* lists
* @param <B> any common base class shared by all axes (often just {@link
* Object})
* @return the Cartesian product, as an immutable list containing immutable
* lists
* @throws IllegalArgumentException if the size of the cartesian product would
* be greater than {@link Integer#MAX_VALUE}
* @throws NullPointerException if {@code lists}, any one of the {@code lists},
* or any element of a provided list is null
*/ static <B> List<List<B>>
cartesianProduct(List<? extends List<? extends B>> lists) {
return CartesianList.create(lists);
}
/**
* Returns every possible list that can be formed by choosing one element
* from each of the given lists in order; the "n-ary
* <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
* product</a>" of the lists. For example: <pre> {@code
*
* Lists.cartesianProduct(ImmutableList.of(
* ImmutableList.of(1, 2),
* ImmutableList.of("A", "B", "C")))}</pre>
*
* <p>returns a list containing six lists in the following order:
*
* <ul>
* <li>{@code ImmutableList.of(1, "A")}
* <li>{@code ImmutableList.of(1, "B")}
* <li>{@code ImmutableList.of(1, "C")}
* <li>{@code ImmutableList.of(2, "A")}
* <li>{@code ImmutableList.of(2, "B")}
* <li>{@code ImmutableList.of(2, "C")}
* </ul>
*
* <p>The result is guaranteed to be in the "traditional", lexicographical
* order for Cartesian products that you would get from nesting for loops:
* <pre> {@code
*
* for (B b0 : lists.get(0)) {
* for (B b1 : lists.get(1)) {
* ...
* ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
* // operate on tuple
* }
* }}</pre>
*
* <p>Note that if any input list is empty, the Cartesian product will also be
* empty. If no lists at all are provided (an empty list), the resulting
* Cartesian product has one element, an empty list (counter-intuitive, but
* mathematically consistent).
*
* <p><i>Performance notes:</i> while the cartesian product of lists of size
* {@code m, n, p} is a list of size {@code m x n x p}, its actual memory
* consumption is much smaller. When the cartesian product is constructed, the
* input lists are merely copied. Only as the resulting list is iterated are
* the individual lists created, and these are not retained after iteration.
*
* @param lists the lists to choose elements from, in the order that
* the elements chosen from those lists should appear in the resulting
* lists
* @param <B> any common base class shared by all axes (often just {@link
* Object})
* @return the Cartesian product, as an immutable list containing immutable
* lists
* @throws IllegalArgumentException if the size of the cartesian product would
* be greater than {@link Integer#MAX_VALUE}
* @throws NullPointerException if {@code lists}, any one of the
* {@code lists}, or any element of a provided list is null
*/ static <B> List<List<B>>
cartesianProduct(List<? extends B>... lists) {
return cartesianProduct(Arrays.asList(lists));
}
/**
* Returns a list that applies {@code function} to each element of {@code
* fromList}. The returned list is a transformed view of {@code fromList};
* changes to {@code fromList} will be reflected in the returned list and vice
* versa.
*
* <p>Since functions are not reversible, the transform is one-way and new
* items cannot be stored in the returned list. The {@code add},
* {@code addAll} and {@code set} methods are unsupported in the returned
* list.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned list to be a view, but it means that the function will be
* applied many times for bulk operations like {@link List#contains} and
* {@link List#hashCode}. For this to perform well, {@code function} should be
* fast. To avoid lazy evaluation when the returned list doesn't need to be a
* view, copy the returned list into a new list of your choosing.
*
* <p>If {@code fromList} implements {@link RandomAccess}, so will the
* returned list. The returned list is threadsafe if the supplied list and
* function are.
*
* <p>If only a {@code Collection} or {@code Iterable} input is available, use
* {@link Collections2#transform} or {@link Iterables#transform}.
*
* <p><b>Note:</b> serializing the returned list is implemented by serializing
* {@code fromList}, its contents, and {@code function} -- <i>not</i> by
* serializing the transformed values. This can lead to surprising behavior,
* so serializing the returned list is <b>not recommended</b>. Instead,
* copy the list using {@link ImmutableList#copyOf(Collection)} (for example),
* then serialize the copy. Other methods similar to this do not implement
* serialization at all for this reason.
*/
public static <F, T> List<T> transform(
List<F> fromList, Function<? super F, ? extends T> function) {
return (fromList instanceof RandomAccess)
? new TransformingRandomAccessList<F, T>(fromList, function)
: new TransformingSequentialList<F, T>(fromList, function);
}
/**
* Implementation of a sequential transforming list.
*
* @see Lists#transform
*/
private static class TransformingSequentialList<F, T>
extends AbstractSequentialList<T> implements Serializable {
final List<F> fromList;
final Function<? super F, ? extends T> function;
TransformingSequentialList(
List<F> fromList, Function<? super F, ? extends T> function) {
this.fromList = checkNotNull(fromList);
this.function = checkNotNull(function);
}
/**
* The default implementation inherited is based on iteration and removal of
* each element which can be overkill. That's why we forward this call
* directly to the backing list.
*/
@Override public void clear() {
fromList.clear();
}
@Override public int size() {
return fromList.size();
}
@Override public ListIterator<T> listIterator(final int index) {
return new TransformedListIterator<F, T>(fromList.listIterator(index)) {
@Override
T transform(F from) {
return function.apply(from);
}
};
}
private static final long serialVersionUID = 0;
}
/**
* Implementation of a transforming random access list. We try to make as many
* of these methods pass-through to the source list as possible so that the
* performance characteristics of the source list and transformed list are
* similar.
*
* @see Lists#transform
*/
private static class TransformingRandomAccessList<F, T>
extends AbstractList<T> implements RandomAccess, Serializable {
final List<F> fromList;
final Function<? super F, ? extends T> function;
TransformingRandomAccessList(
List<F> fromList, Function<? super F, ? extends T> function) {
this.fromList = checkNotNull(fromList);
this.function = checkNotNull(function);
}
@Override public void clear() {
fromList.clear();
}
@Override public T get(int index) {
return function.apply(fromList.get(index));
}
@Override public boolean isEmpty() {
return fromList.isEmpty();
}
@Override public T remove(int index) {
return function.apply(fromList.remove(index));
}
@Override public int size() {
return fromList.size();
}
private static final long serialVersionUID = 0;
}
/**
* Returns consecutive {@linkplain List#subList(int, int) sublists} of a list,
* each of the same size (the final list may be smaller). For example,
* partitioning a list containing {@code [a, b, c, d, e]} with a partition
* size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer list containing
* two inner lists of three and two elements, all in the original order.
*
* <p>The outer list is unmodifiable, but reflects the latest state of the
* source list. The inner lists are sublist views of the original list,
* produced on demand using {@link List#subList(int, int)}, and are subject
* to all the usual caveats about modification as explained in that API.
*
* @param list the list to return consecutive sublists of
* @param size the desired size of each sublist (the last may be
* smaller)
* @return a list of consecutive sublists
* @throws IllegalArgumentException if {@code partitionSize} is nonpositive
*/
public static <T> List<List<T>> partition(List<T> list, int size) {
checkNotNull(list);
checkArgument(size > 0);
return (list instanceof RandomAccess)
? new RandomAccessPartition<T>(list, size)
: new Partition<T>(list, size);
}
private static class Partition<T> extends AbstractList<List<T>> {
final List<T> list;
final int size;
Partition(List<T> list, int size) {
this.list = list;
this.size = size;
}
@Override public List<T> get(int index) {
checkElementIndex(index, size());
int start = index * size;
int end = Math.min(start + size, list.size());
return list.subList(start, end);
}
@Override public int size() {
return IntMath.divide(list.size(), size, RoundingMode.CEILING);
}
@Override public boolean isEmpty() {
return list.isEmpty();
}
}
private static class RandomAccessPartition<T> extends Partition<T>
implements RandomAccess {
RandomAccessPartition(List<T> list, int size) {
super(list, size);
}
}
/**
* Returns a view of the specified string as an immutable list of {@code
* Character} values.
*
* @since 7.0
*/
@Beta public static ImmutableList<Character> charactersOf(String string) {
return new StringAsImmutableList(checkNotNull(string));
}
@SuppressWarnings("serial") // serialized using ImmutableList serialization
private static final class StringAsImmutableList
extends ImmutableList<Character> {
private final String string;
StringAsImmutableList(String string) {
this.string = string;
}
@Override public int indexOf(@Nullable Object object) {
return (object instanceof Character)
? string.indexOf((Character) object) : -1;
}
@Override public int lastIndexOf(@Nullable Object object) {
return (object instanceof Character)
? string.lastIndexOf((Character) object) : -1;
}
@Override public ImmutableList<Character> subList(
int fromIndex, int toIndex) {
checkPositionIndexes(fromIndex, toIndex, size()); // for GWT
return charactersOf(string.substring(fromIndex, toIndex));
}
@Override boolean isPartialView() {
return false;
}
@Override public Character get(int index) {
checkElementIndex(index, size()); // for GWT
return string.charAt(index);
}
@Override public int size() {
return string.length();
}
}
/**
* Returns a view of the specified {@code CharSequence} as a {@code
* List<Character>}, viewing {@code sequence} as a sequence of Unicode code
* units. The view does not support any modification operations, but reflects
* any changes to the underlying character sequence.
*
* @param sequence the character sequence to view as a {@code List} of
* characters
* @return an {@code List<Character>} view of the character sequence
* @since 7.0
*/
@Beta public static List<Character> charactersOf(CharSequence sequence) {
return new CharSequenceAsList(checkNotNull(sequence));
}
private static final class CharSequenceAsList
extends AbstractList<Character> {
private final CharSequence sequence;
CharSequenceAsList(CharSequence sequence) {
this.sequence = sequence;
}
@Override public Character get(int index) {
checkElementIndex(index, size()); // for GWT
return sequence.charAt(index);
}
@Override public int size() {
return sequence.length();
}
}
/**
* Returns a reversed view of the specified list. For example, {@code
* Lists.reverse(Arrays.asList(1, 2, 3))} returns a list containing {@code 3,
* 2, 1}. The returned list is backed by this list, so changes in the returned
* list are reflected in this list, and vice-versa. The returned list supports
* all of the optional list operations supported by this list.
*
* <p>The returned list is random-access if the specified list is random
* access.
*
* @since 7.0
*/
public static <T> List<T> reverse(List<T> list) {
if (list instanceof ImmutableList) {
return ((ImmutableList<T>) list).reverse();
} else if (list instanceof ReverseList) {
return ((ReverseList<T>) list).getForwardList();
} else if (list instanceof RandomAccess) {
return new RandomAccessReverseList<T>(list);
} else {
return new ReverseList<T>(list);
}
}
private static class ReverseList<T> extends AbstractList<T> {
private final List<T> forwardList;
ReverseList(List<T> forwardList) {
this.forwardList = checkNotNull(forwardList);
}
List<T> getForwardList() {
return forwardList;
}
private int reverseIndex(int index) {
int size = size();
checkElementIndex(index, size);
return (size - 1) - index;
}
private int reversePosition(int index) {
int size = size();
checkPositionIndex(index, size);
return size - index;
}
@Override public void add(int index, @Nullable T element) {
forwardList.add(reversePosition(index), element);
}
@Override public void clear() {
forwardList.clear();
}
@Override public T remove(int index) {
return forwardList.remove(reverseIndex(index));
}
@Override protected void removeRange(int fromIndex, int toIndex) {
subList(fromIndex, toIndex).clear();
}
@Override public T set(int index, @Nullable T element) {
return forwardList.set(reverseIndex(index), element);
}
@Override public T get(int index) {
return forwardList.get(reverseIndex(index));
}
@Override public int size() {
return forwardList.size();
}
@Override public List<T> subList(int fromIndex, int toIndex) {
checkPositionIndexes(fromIndex, toIndex, size());
return reverse(forwardList.subList(
reversePosition(toIndex), reversePosition(fromIndex)));
}
@Override public Iterator<T> iterator() {
return listIterator();
}
@Override public ListIterator<T> listIterator(int index) {
int start = reversePosition(index);
final ListIterator<T> forwardIterator = forwardList.listIterator(start);
return new ListIterator<T>() {
boolean canRemoveOrSet;
@Override public void add(T e) {
forwardIterator.add(e);
forwardIterator.previous();
canRemoveOrSet = false;
}
@Override public boolean hasNext() {
return forwardIterator.hasPrevious();
}
@Override public boolean hasPrevious() {
return forwardIterator.hasNext();
}
@Override public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
canRemoveOrSet = true;
return forwardIterator.previous();
}
@Override public int nextIndex() {
return reversePosition(forwardIterator.nextIndex());
}
@Override public T previous() {
if (!hasPrevious()) {
throw new NoSuchElementException();
}
canRemoveOrSet = true;
return forwardIterator.next();
}
@Override public int previousIndex() {
return nextIndex() - 1;
}
@Override public void remove() {
Iterators.checkRemove(canRemoveOrSet);
forwardIterator.remove();
canRemoveOrSet = false;
}
@Override public void set(T e) {
checkState(canRemoveOrSet);
forwardIterator.set(e);
}
};
}
}
private static class RandomAccessReverseList<T> extends ReverseList<T>
implements RandomAccess {
RandomAccessReverseList(List<T> forwardList) {
super(forwardList);
}
}
/**
* An implementation of {@link List#hashCode()}.
*/
static int hashCodeImpl(List<?> list) {
// TODO(user): worth optimizing for RandomAccess?
int hashCode = 1;
for (Object o : list) {
hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode());
hashCode = ~~hashCode;
// needed to deal with GWT integer overflow
}
return hashCode;
}
/**
* An implementation of {@link List#equals(Object)}.
*/
static boolean equalsImpl(List<?> list, @Nullable Object object) {
if (object == checkNotNull(list)) {
return true;
}
if (!(object instanceof List)) {
return false;
}
List<?> o = (List<?>) object;
return list.size() == o.size()
&& Iterators.elementsEqual(list.iterator(), o.iterator());
}
/**
* An implementation of {@link List#addAll(int, Collection)}.
*/
static <E> boolean addAllImpl(
List<E> list, int index, Iterable<? extends E> elements) {
boolean changed = false;
ListIterator<E> listIterator = list.listIterator(index);
for (E e : elements) {
listIterator.add(e);
changed = true;
}
return changed;
}
/**
* An implementation of {@link List#indexOf(Object)}.
*/
static int indexOfImpl(List<?> list, @Nullable Object element) {
ListIterator<?> listIterator = list.listIterator();
while (listIterator.hasNext()) {
if (Objects.equal(element, listIterator.next())) {
return listIterator.previousIndex();
}
}
return -1;
}
/**
* An implementation of {@link List#lastIndexOf(Object)}.
*/
static int lastIndexOfImpl(List<?> list, @Nullable Object element) {
ListIterator<?> listIterator = list.listIterator(list.size());
while (listIterator.hasPrevious()) {
if (Objects.equal(element, listIterator.previous())) {
return listIterator.nextIndex();
}
}
return -1;
}
/**
* Returns an implementation of {@link List#listIterator(int)}.
*/
static <E> ListIterator<E> listIteratorImpl(List<E> list, int index) {
return new AbstractListWrapper<E>(list).listIterator(index);
}
/**
* An implementation of {@link List#subList(int, int)}.
*/
static <E> List<E> subListImpl(
final List<E> list, int fromIndex, int toIndex) {
List<E> wrapper;
if (list instanceof RandomAccess) {
wrapper = new RandomAccessListWrapper<E>(list) {
@Override public ListIterator<E> listIterator(int index) {
return backingList.listIterator(index);
}
private static final long serialVersionUID = 0;
};
} else {
wrapper = new AbstractListWrapper<E>(list) {
@Override public ListIterator<E> listIterator(int index) {
return backingList.listIterator(index);
}
private static final long serialVersionUID = 0;
};
}
return wrapper.subList(fromIndex, toIndex);
}
private static class AbstractListWrapper<E> extends AbstractList<E> {
final List<E> backingList;
AbstractListWrapper(List<E> backingList) {
this.backingList = checkNotNull(backingList);
}
@Override public void add(int index, E element) {
backingList.add(index, element);
}
@Override public boolean addAll(int index, Collection<? extends E> c) {
return backingList.addAll(index, c);
}
@Override public E get(int index) {
return backingList.get(index);
}
@Override public E remove(int index) {
return backingList.remove(index);
}
@Override public E set(int index, E element) {
return backingList.set(index, element);
}
@Override public boolean contains(Object o) {
return backingList.contains(o);
}
@Override public int size() {
return backingList.size();
}
}
private static class RandomAccessListWrapper<E>
extends AbstractListWrapper<E> implements RandomAccess {
RandomAccessListWrapper(List<E> backingList) {
super(backingList);
}
}
/**
* Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
*/
static <T> List<T> cast(Iterable<T> iterable) {
return (List<T>) iterable;
}
}
| Java |
/*
* Copyright (C) 2007 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.collect;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.EnumMap;
import java.util.Iterator;
/**
* Multiset implementation backed by an {@link EnumMap}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset">
* {@code Multiset}</a>.
*
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class EnumMultiset<E extends Enum<E>> extends AbstractMapBasedMultiset<E> {
/** Creates an empty {@code EnumMultiset}. */
public static <E extends Enum<E>> EnumMultiset<E> create(Class<E> type) {
return new EnumMultiset<E>(type);
}
/**
* Creates a new {@code EnumMultiset} containing the specified elements.
*
* <p>This implementation is highly efficient when {@code elements} is itself a {@link
* Multiset}.
*
* @param elements the elements that the multiset should contain
* @throws IllegalArgumentException if {@code elements} is empty
*/
public static <E extends Enum<E>> EnumMultiset<E> create(Iterable<E> elements) {
Iterator<E> iterator = elements.iterator();
checkArgument(iterator.hasNext(), "EnumMultiset constructor passed empty Iterable");
EnumMultiset<E> multiset = new EnumMultiset<E>(iterator.next().getDeclaringClass());
Iterables.addAll(multiset, elements);
return multiset;
}
/**
* Returns a new {@code EnumMultiset} instance containing the given elements. Unlike
* {@link EnumMultiset#create(Iterable)}, this method does not produce an exception on an empty
* iterable.
*
* @since 14.0
*/
public static <E extends Enum<E>> EnumMultiset<E> create(Iterable<E> elements, Class<E> type) {
EnumMultiset<E> result = create(type);
Iterables.addAll(result, elements);
return result;
}
private transient Class<E> type;
/** Creates an empty {@code EnumMultiset}. */
private EnumMultiset(Class<E> type) {
super(WellBehavedMap.wrap(new EnumMap<E, Count>(type)));
this.type = type;
}
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(type);
Serialization.writeMultiset(this, stream);
}
/**
* @serialData the {@code Class<E>} for the enum type, the number of distinct
* elements, the first element, its count, the second element, its
* count, and so on
*/
@GwtIncompatible("java.io.ObjectInputStream")
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@SuppressWarnings("unchecked") // reading data stored by writeObject
Class<E> localType = (Class<E>) stream.readObject();
type = localType;
setBackingMap(WellBehavedMap.wrap(new EnumMap<E, Count>(type)));
Serialization.populateMultiset(this, stream);
}
@GwtIncompatible("Not needed in emulated source")
private static final long serialVersionUID = 0;
}
| Java |
/*
* 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.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Supplier;
import com.google.common.collect.Table.Cell;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Provides static methods that involve a {@code Table}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Tables">
* {@code Tables}</a>.
*
* @author Jared Levy
* @author Louis Wasserman
* @since 7.0
*/
@GwtCompatible
public final class Tables {
private Tables() {}
/**
* Returns an immutable cell with the specified row key, column key, and
* value.
*
* <p>The returned cell is serializable.
*
* @param rowKey the row key to be associated with the returned cell
* @param columnKey the column key to be associated with the returned cell
* @param value the value to be associated with the returned cell
*/
public static <R, C, V> Cell<R, C, V> immutableCell(
@Nullable R rowKey, @Nullable C columnKey, @Nullable V value) {
return new ImmutableCell<R, C, V>(rowKey, columnKey, value);
}
static final class ImmutableCell<R, C, V>
extends AbstractCell<R, C, V> implements Serializable {
private final R rowKey;
private final C columnKey;
private final V value;
ImmutableCell(
@Nullable R rowKey, @Nullable C columnKey, @Nullable V value) {
this.rowKey = rowKey;
this.columnKey = columnKey;
this.value = value;
}
@Override
public R getRowKey() {
return rowKey;
}
@Override
public C getColumnKey() {
return columnKey;
}
@Override
public V getValue() {
return value;
}
private static final long serialVersionUID = 0;
}
abstract static class AbstractCell<R, C, V> implements Cell<R, C, V> {
// needed for serialization
AbstractCell() {}
@Override public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Cell) {
Cell<?, ?, ?> other = (Cell<?, ?, ?>) obj;
return Objects.equal(getRowKey(), other.getRowKey())
&& Objects.equal(getColumnKey(), other.getColumnKey())
&& Objects.equal(getValue(), other.getValue());
}
return false;
}
@Override public int hashCode() {
return Objects.hashCode(getRowKey(), getColumnKey(), getValue());
}
@Override public String toString() {
return "(" + getRowKey() + "," + getColumnKey() + ")=" + getValue();
}
}
/**
* Creates a transposed view of a given table that flips its row and column
* keys. In other words, calling {@code get(columnKey, rowKey)} on the
* generated table always returns the same value as calling {@code
* get(rowKey, columnKey)} on the original table. Updating the original table
* changes the contents of the transposed table and vice versa.
*
* <p>The returned table supports update operations as long as the input table
* supports the analogous operation with swapped rows and columns. For
* example, in a {@link HashBasedTable} instance, {@code
* rowKeySet().iterator()} supports {@code remove()} but {@code
* columnKeySet().iterator()} doesn't. With a transposed {@link
* HashBasedTable}, it's the other way around.
*/
public static <R, C, V> Table<C, R, V> transpose(Table<R, C, V> table) {
return (table instanceof TransposeTable)
? ((TransposeTable<R, C, V>) table).original
: new TransposeTable<C, R, V>(table);
}
private static class TransposeTable<C, R, V> extends AbstractTable<C, R, V> {
final Table<R, C, V> original;
TransposeTable(Table<R, C, V> original) {
this.original = checkNotNull(original);
}
@Override
public void clear() {
original.clear();
}
@Override
public Map<C, V> column(R columnKey) {
return original.row(columnKey);
}
@Override
public Set<R> columnKeySet() {
return original.rowKeySet();
}
@Override
public Map<R, Map<C, V>> columnMap() {
return original.rowMap();
}
@Override
public boolean contains(
@Nullable Object rowKey, @Nullable Object columnKey) {
return original.contains(columnKey, rowKey);
}
@Override
public boolean containsColumn(@Nullable Object columnKey) {
return original.containsRow(columnKey);
}
@Override
public boolean containsRow(@Nullable Object rowKey) {
return original.containsColumn(rowKey);
}
@Override
public boolean containsValue(@Nullable Object value) {
return original.containsValue(value);
}
@Override
public V get(@Nullable Object rowKey, @Nullable Object columnKey) {
return original.get(columnKey, rowKey);
}
@Override
public V put(C rowKey, R columnKey, V value) {
return original.put(columnKey, rowKey, value);
}
@Override
public void putAll(Table<? extends C, ? extends R, ? extends V> table) {
original.putAll(transpose(table));
}
@Override
public V remove(@Nullable Object rowKey, @Nullable Object columnKey) {
return original.remove(columnKey, rowKey);
}
@Override
public Map<R, V> row(C rowKey) {
return original.column(rowKey);
}
@Override
public Set<C> rowKeySet() {
return original.columnKeySet();
}
@Override
public Map<C, Map<R, V>> rowMap() {
return original.columnMap();
}
@Override
public int size() {
return original.size();
}
@Override
public Collection<V> values() {
return original.values();
}
// Will cast TRANSPOSE_CELL to a type that always succeeds
private static final Function<Cell<?, ?, ?>, Cell<?, ?, ?>> TRANSPOSE_CELL =
new Function<Cell<?, ?, ?>, Cell<?, ?, ?>>() {
@Override
public Cell<?, ?, ?> apply(Cell<?, ?, ?> cell) {
return immutableCell(
cell.getColumnKey(), cell.getRowKey(), cell.getValue());
}
};
@SuppressWarnings("unchecked")
@Override
Iterator<Cell<C, R, V>> cellIterator() {
return Iterators.transform(original.cellSet().iterator(), (Function) TRANSPOSE_CELL);
}
}
/**
* Creates a table that uses the specified backing map and factory. It can
* generate a table based on arbitrary {@link Map} classes.
*
* <p>The {@code factory}-generated and {@code backingMap} classes determine
* the table iteration order. However, the table's {@code row()} method
* returns instances of a different class than {@code factory.get()} does.
*
* <p>Call this method only when the simpler factory methods in classes like
* {@link HashBasedTable} and {@link TreeBasedTable} won't suffice.
*
* <p>The views returned by the {@code Table} methods {@link Table#column},
* {@link Table#columnKeySet}, and {@link Table#columnMap} have iterators that
* don't support {@code remove()}. Otherwise, all optional operations are
* supported. Null row keys, columns keys, and values are not supported.
*
* <p>Lookups by row key are often faster than lookups by column key, because
* the data is stored in a {@code Map<R, Map<C, V>>}. A method call like
* {@code column(columnKey).get(rowKey)} still runs quickly, since the row key
* is provided. However, {@code column(columnKey).size()} takes longer, since
* an iteration across all row keys occurs.
*
* <p>Note that this implementation is not synchronized. If multiple threads
* access this table concurrently and one of the threads modifies the table,
* it must be synchronized externally.
*
* <p>The table is serializable if {@code backingMap}, {@code factory}, the
* maps generated by {@code factory}, and the table contents are all
* serializable.
*
* <p>Note: the table assumes complete ownership over of {@code backingMap}
* and the maps returned by {@code factory}. Those objects should not be
* manually updated and they should not use soft, weak, or phantom references.
*
* @param backingMap place to store the mapping from each row key to its
* corresponding column key / value map
* @param factory supplier of new, empty maps that will each hold all column
* key / value mappings for a given row key
* @throws IllegalArgumentException if {@code backingMap} is not empty
* @since 10.0
*/
@Beta
public static <R, C, V> Table<R, C, V> newCustomTable(
Map<R, Map<C, V>> backingMap, Supplier<? extends Map<C, V>> factory) {
checkArgument(backingMap.isEmpty());
checkNotNull(factory);
// TODO(jlevy): Wrap factory to validate that the supplied maps are empty?
return new StandardTable<R, C, V>(backingMap, factory);
}
/**
* Returns a view of a table where each value is transformed by a function.
* All other properties of the table, such as iteration order, are left
* intact.
*
* <p>Changes in the underlying table are reflected in this view. Conversely,
* this view supports removal operations, and these are reflected in the
* underlying table.
*
* <p>It's acceptable for the underlying table to contain null keys, and even
* null values provided that the function is capable of accepting null input.
* The transformed table might contain null values, if the function sometimes
* gives a null result.
*
* <p>The returned table is not thread-safe or serializable, even if the
* underlying table is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned table to be a view, but it means that the function will be
* applied many times for bulk operations like {@link Table#containsValue} and
* {@code Table.toString()}. For this to perform well, {@code function} should
* be fast. To avoid lazy evaluation when the returned table doesn't need to
* be a view, copy the returned table into a new table of your choosing.
*
* @since 10.0
*/
@Beta
public static <R, C, V1, V2> Table<R, C, V2> transformValues(
Table<R, C, V1> fromTable, Function<? super V1, V2> function) {
return new TransformedTable<R, C, V1, V2>(fromTable, function);
}
private static class TransformedTable<R, C, V1, V2>
extends AbstractTable<R, C, V2> {
final Table<R, C, V1> fromTable;
final Function<? super V1, V2> function;
TransformedTable(
Table<R, C, V1> fromTable, Function<? super V1, V2> function) {
this.fromTable = checkNotNull(fromTable);
this.function = checkNotNull(function);
}
@Override public boolean contains(Object rowKey, Object columnKey) {
return fromTable.contains(rowKey, columnKey);
}
@Override public V2 get(Object rowKey, Object columnKey) {
// The function is passed a null input only when the table contains a null
// value.
return contains(rowKey, columnKey)
? function.apply(fromTable.get(rowKey, columnKey)) : null;
}
@Override public int size() {
return fromTable.size();
}
@Override public void clear() {
fromTable.clear();
}
@Override public V2 put(R rowKey, C columnKey, V2 value) {
throw new UnsupportedOperationException();
}
@Override public void putAll(
Table<? extends R, ? extends C, ? extends V2> table) {
throw new UnsupportedOperationException();
}
@Override public V2 remove(Object rowKey, Object columnKey) {
return contains(rowKey, columnKey)
? function.apply(fromTable.remove(rowKey, columnKey)) : null;
}
@Override public Map<C, V2> row(R rowKey) {
return Maps.transformValues(fromTable.row(rowKey), function);
}
@Override public Map<R, V2> column(C columnKey) {
return Maps.transformValues(fromTable.column(columnKey), function);
}
Function<Cell<R, C, V1>, Cell<R, C, V2>> cellFunction() {
return new Function<Cell<R, C, V1>, Cell<R, C, V2>>() {
@Override public Cell<R, C, V2> apply(Cell<R, C, V1> cell) {
return immutableCell(
cell.getRowKey(), cell.getColumnKey(),
function.apply(cell.getValue()));
}
};
}
@Override
Iterator<Cell<R, C, V2>> cellIterator() {
return Iterators.transform(fromTable.cellSet().iterator(), cellFunction());
}
@Override public Set<R> rowKeySet() {
return fromTable.rowKeySet();
}
@Override public Set<C> columnKeySet() {
return fromTable.columnKeySet();
}
@Override
Collection<V2> createValues() {
return Collections2.transform(fromTable.values(), function);
}
@Override public Map<R, Map<C, V2>> rowMap() {
Function<Map<C, V1>, Map<C, V2>> rowFunction =
new Function<Map<C, V1>, Map<C, V2>>() {
@Override public Map<C, V2> apply(Map<C, V1> row) {
return Maps.transformValues(row, function);
}
};
return Maps.transformValues(fromTable.rowMap(), rowFunction);
}
@Override public Map<C, Map<R, V2>> columnMap() {
Function<Map<R, V1>, Map<R, V2>> columnFunction =
new Function<Map<R, V1>, Map<R, V2>>() {
@Override public Map<R, V2> apply(Map<R, V1> column) {
return Maps.transformValues(column, function);
}
};
return Maps.transformValues(fromTable.columnMap(), columnFunction);
}
}
/**
* Returns an unmodifiable view of the specified table. This method allows modules to provide
* users with "read-only" access to internal tables. Query operations on the returned table
* "read through" to the specified table, and attempts to modify the returned table, whether
* direct or via its collection views, result in an {@code UnsupportedOperationException}.
*
* <p>The returned table will be serializable if the specified table is serializable.
*
* <p>Consider using an {@link ImmutableTable}, which is guaranteed never to change.
*
* @param table
* the table for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified table
* @since 11.0
*/
public static <R, C, V> Table<R, C, V> unmodifiableTable(
Table<? extends R, ? extends C, ? extends V> table) {
return new UnmodifiableTable<R, C, V>(table);
}
private static class UnmodifiableTable<R, C, V>
extends ForwardingTable<R, C, V> implements Serializable {
final Table<? extends R, ? extends C, ? extends V> delegate;
UnmodifiableTable(Table<? extends R, ? extends C, ? extends V> delegate) {
this.delegate = checkNotNull(delegate);
}
@SuppressWarnings("unchecked") // safe, covariant cast
@Override
protected Table<R, C, V> delegate() {
return (Table<R, C, V>) delegate;
}
@Override
public Set<Cell<R, C, V>> cellSet() {
return Collections.unmodifiableSet(super.cellSet());
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public Map<R, V> column(@Nullable C columnKey) {
return Collections.unmodifiableMap(super.column(columnKey));
}
@Override
public Set<C> columnKeySet() {
return Collections.unmodifiableSet(super.columnKeySet());
}
@Override
public Map<C, Map<R, V>> columnMap() {
Function<Map<R, V>, Map<R, V>> wrapper = unmodifiableWrapper();
return Collections.unmodifiableMap(Maps.transformValues(super.columnMap(), wrapper));
}
@Override
public V put(@Nullable R rowKey, @Nullable C columnKey, @Nullable V value) {
throw new UnsupportedOperationException();
}
@Override
public void putAll(Table<? extends R, ? extends C, ? extends V> table) {
throw new UnsupportedOperationException();
}
@Override
public V remove(@Nullable Object rowKey, @Nullable Object columnKey) {
throw new UnsupportedOperationException();
}
@Override
public Map<C, V> row(@Nullable R rowKey) {
return Collections.unmodifiableMap(super.row(rowKey));
}
@Override
public Set<R> rowKeySet() {
return Collections.unmodifiableSet(super.rowKeySet());
}
@Override
public Map<R, Map<C, V>> rowMap() {
Function<Map<C, V>, Map<C, V>> wrapper = unmodifiableWrapper();
return Collections.unmodifiableMap(Maps.transformValues(super.rowMap(), wrapper));
}
@Override
public Collection<V> values() {
return Collections.unmodifiableCollection(super.values());
}
private static final long serialVersionUID = 0;
}
/**
* Returns an unmodifiable view of the specified row-sorted table. This method allows modules to
* provide users with "read-only" access to internal tables. Query operations on the returned
* table "read through" to the specified table, and attemps to modify the returned table, whether
* direct or via its collection views, result in an {@code UnsupportedOperationException}.
*
* <p>The returned table will be serializable if the specified table is serializable.
*
* @param table the row-sorted table for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified table
* @since 11.0
*/
@Beta
public static <R, C, V> RowSortedTable<R, C, V> unmodifiableRowSortedTable(
RowSortedTable<R, ? extends C, ? extends V> table) {
/*
* It's not ? extends R, because it's technically not covariant in R. Specifically,
* table.rowMap().comparator() could return a comparator that only works for the ? extends R.
* Collections.unmodifiableSortedMap makes the same distinction.
*/
return new UnmodifiableRowSortedMap<R, C, V>(table);
}
static final class UnmodifiableRowSortedMap<R, C, V> extends UnmodifiableTable<R, C, V>
implements RowSortedTable<R, C, V> {
public UnmodifiableRowSortedMap(RowSortedTable<R, ? extends C, ? extends V> delegate) {
super(delegate);
}
@Override
protected RowSortedTable<R, C, V> delegate() {
return (RowSortedTable<R, C, V>) super.delegate();
}
@Override
public SortedMap<R, Map<C, V>> rowMap() {
Function<Map<C, V>, Map<C, V>> wrapper = unmodifiableWrapper();
return Collections.unmodifiableSortedMap(Maps.transformValues(delegate().rowMap(), wrapper));
}
@Override
public SortedSet<R> rowKeySet() {
return Collections.unmodifiableSortedSet(delegate().rowKeySet());
}
private static final long serialVersionUID = 0;
}
@SuppressWarnings("unchecked")
private static <K, V> Function<Map<K, V>, Map<K, V>> unmodifiableWrapper() {
return (Function) UNMODIFIABLE_WRAPPER;
}
private static final Function<? extends Map<?, ?>, ? extends Map<?, ?>> UNMODIFIABLE_WRAPPER =
new Function<Map<Object, Object>, Map<Object, Object>>() {
@Override
public Map<Object, Object> apply(Map<Object, Object> input) {
return Collections.unmodifiableMap(input);
}
};
static boolean equalsImpl(Table<?, ?, ?> table, @Nullable Object obj) {
if (obj == table) {
return true;
} else if (obj instanceof Table) {
Table<?, ?, ?> that = (Table<?, ?, ?>) obj;
return table.cellSet().equals(that.cellSet());
} else {
return false;
}
}
}
| Java |
/*
* Copyright (C) 2009 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.collect;
import com.google.common.annotations.GwtCompatible;
/**
* "Overrides" the {@link ImmutableSet} static methods that lack
* {@link ImmutableSortedSet} equivalents with deprecated, exception-throwing
* versions. This prevents accidents like the following: <pre> {@code
*
* List<Object> objects = ...;
* // Sort them:
* Set<Object> sorted = ImmutableSortedSet.copyOf(objects);
* // BAD CODE! The returned set is actually an unsorted ImmutableSet!}</pre>
*
* <p>While we could put the overrides in {@link ImmutableSortedSet} itself, it
* seems clearer to separate these "do not call" methods from those intended for
* normal use.
*
* @author Chris Povirk
*/
@GwtCompatible
abstract class ImmutableSortedSetFauxverideShim<E> extends ImmutableSet<E> {
/**
* Not supported. Use {@link ImmutableSortedSet#naturalOrder}, which offers
* better type-safety, instead. This method exists only to hide
* {@link ImmutableSet#builder} from consumers of {@code ImmutableSortedSet}.
*
* @throws UnsupportedOperationException always
* @deprecated Use {@link ImmutableSortedSet#naturalOrder}, which offers
* better type-safety.
*/
@Deprecated public static <E> ImmutableSortedSet.Builder<E> builder() {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a set that may contain a
* non-{@code Comparable} element.</b> Proper calls will resolve to the
* version in {@code ImmutableSortedSet}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass a parameter of type {@code Comparable} to use {@link
* ImmutableSortedSet#of(Comparable)}.</b>
*/
@Deprecated public static <E> ImmutableSortedSet<E> of(E element) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a set that may contain a
* non-{@code Comparable} element.</b> Proper calls will resolve to the
* version in {@code ImmutableSortedSet}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
* ImmutableSortedSet#of(Comparable, Comparable)}.</b>
*/
@Deprecated public static <E> ImmutableSortedSet<E> of(E e1, E e2) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a set that may contain a
* non-{@code Comparable} element.</b> Proper calls will resolve to the
* version in {@code ImmutableSortedSet}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
* ImmutableSortedSet#of(Comparable, Comparable, Comparable)}.</b>
*/
@Deprecated public static <E> ImmutableSortedSet<E> of(E e1, E e2, E e3) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a set that may contain a
* non-{@code Comparable} element.</b> Proper calls will resolve to the
* version in {@code ImmutableSortedSet}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
* ImmutableSortedSet#of(Comparable, Comparable, Comparable, Comparable)}.
* </b>
*/
@Deprecated public static <E> ImmutableSortedSet<E> of(
E e1, E e2, E e3, E e4) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a set that may contain a
* non-{@code Comparable} element.</b> Proper calls will resolve to the
* version in {@code ImmutableSortedSet}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
* ImmutableSortedSet#of(
* Comparable, Comparable, Comparable, Comparable, Comparable)}. </b>
*/
@Deprecated public static <E> ImmutableSortedSet<E> of(
E e1, E e2, E e3, E e4, E e5) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a set that may contain a
* non-{@code Comparable} element.</b> Proper calls will resolve to the
* version in {@code ImmutableSortedSet}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link
* ImmutableSortedSet#of(Comparable, Comparable, Comparable, Comparable,
* Comparable, Comparable, Comparable...)}. </b>
*/
@Deprecated public static <E> ImmutableSortedSet<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E... remaining) {
throw new UnsupportedOperationException();
}
/**
* Not supported. <b>You are attempting to create a set that may contain
* non-{@code Comparable} elements.</b> Proper calls will resolve to the
* version in {@code ImmutableSortedSet}, not this dummy version.
*
* @throws UnsupportedOperationException always
* @deprecated <b>Pass parameters of type {@code Comparable} to use {@link
* ImmutableSortedSet#copyOf(Comparable[])}.</b>
*/
@Deprecated public static <E> ImmutableSortedSet<E> copyOf(E[] elements) {
throw new UnsupportedOperationException();
}
/*
* We would like to include an unsupported "<E> copyOf(Iterable<E>)" here,
* providing only the properly typed
* "<E extends Comparable<E>> copyOf(Iterable<E>)" in ImmutableSortedSet (and
* likewise for the Iterator equivalent). However, due to a change in Sun's
* interpretation of the JLS (as described at
* http://bugs.sun.com/view_bug.do?bug_id=6182950), the OpenJDK 7 compiler
* available as of this writing rejects our attempts. To maintain
* compatibility with that version and with any other compilers that interpret
* the JLS similarly, there is no definition of copyOf() here, and the
* definition in ImmutableSortedSet matches that in ImmutableSet.
*
* The result is that ImmutableSortedSet.copyOf() may be called on
* non-Comparable elements. We have not discovered a better solution. In
* retrospect, the static factory methods should have gone in a separate class
* so that ImmutableSortedSet wouldn't "inherit" too-permissive factory
* methods from ImmutableSet.
*/
}
| Java |
/*
* 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.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.Serializable;
import java.util.Map.Entry;
import javax.annotation.Nullable;
/**
* {@code values()} implementation for {@link ImmutableMap}.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
final class ImmutableMapValues<K, V> extends ImmutableCollection<V> {
private final ImmutableMap<K, V> map;
ImmutableMapValues(ImmutableMap<K, V> map) {
this.map = map;
}
@Override
public int size() {
return map.size();
}
@Override
public UnmodifiableIterator<V> iterator() {
return Maps.valueIterator(map.entrySet().iterator());
}
@Override
public boolean contains(@Nullable Object object) {
return object != null && Iterators.contains(iterator(), object);
}
@Override
boolean isPartialView() {
return true;
}
@Override
ImmutableList<V> createAsList() {
final ImmutableList<Entry<K, V>> entryList = map.entrySet().asList();
return new ImmutableAsList<V>() {
@Override
public V get(int index) {
return entryList.get(index).getValue();
}
@Override
ImmutableCollection<V> delegateCollection() {
return ImmutableMapValues.this;
}
};
}
@GwtIncompatible("serialization")
@Override Object writeReplace() {
return new SerializedForm<V>(map);
}
@GwtIncompatible("serialization")
private static class SerializedForm<V> implements Serializable {
final ImmutableMap<?, V> map;
SerializedForm(ImmutableMap<?, V> map) {
this.map = map;
}
Object readResolve() {
return map.values();
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* Copyright (C) 2007 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.collect;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A map which forwards all its method calls to another map. Subclasses should
* override one or more methods to modify the behavior of the backing map as
* desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p><i>Warning:</i> The methods of {@code ForwardingMap} forward
* <i>indiscriminately</i> to the methods of the delegate. For example,
* overriding {@link #put} alone <i>will not</i> change the behavior of {@link
* #putAll}, which can lead to unexpected behavior. In this case, you should
* override {@code putAll} as well, either providing your own implementation, or
* delegating to the provided {@code standardPutAll} method.
*
* <p>Each of the {@code standard} methods, where appropriate, use {@link
* Objects#equal} to test equality for both keys and values. This may not be
* the desired behavior for map implementations that use non-standard notions of
* key equality, such as a {@code SortedMap} whose comparator is not consistent
* with {@code equals}.
*
* <p>The {@code standard} methods and the collection views they return are not
* guaranteed to be thread-safe, even when all of the methods that they depend
* on are thread-safe.
*
* @author Kevin Bourrillion
* @author Jared Levy
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public abstract class ForwardingMap<K, V> extends ForwardingObject
implements Map<K, V> {
// TODO(user): identify places where thread safety is actually lost
/** Constructor for use by subclasses. */
protected ForwardingMap() {}
@Override protected abstract Map<K, V> delegate();
@Override
public int size() {
return delegate().size();
}
@Override
public boolean isEmpty() {
return delegate().isEmpty();
}
@Override
public V remove(Object object) {
return delegate().remove(object);
}
@Override
public void clear() {
delegate().clear();
}
@Override
public boolean containsKey(@Nullable Object key) {
return delegate().containsKey(key);
}
@Override
public boolean containsValue(@Nullable Object value) {
return delegate().containsValue(value);
}
@Override
public V get(@Nullable Object key) {
return delegate().get(key);
}
@Override
public V put(K key, V value) {
return delegate().put(key, value);
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
delegate().putAll(map);
}
@Override
public Set<K> keySet() {
return delegate().keySet();
}
@Override
public Collection<V> values() {
return delegate().values();
}
@Override
public Set<Entry<K, V>> entrySet() {
return delegate().entrySet();
}
@Override public boolean equals(@Nullable Object object) {
return object == this || delegate().equals(object);
}
@Override public int hashCode() {
return delegate().hashCode();
}
/**
* A sensible definition of {@link #putAll(Map)} in terms of {@link
* #put(Object, Object)}. If you override {@link #put(Object, Object)}, you
* may wish to override {@link #putAll(Map)} to forward to this
* implementation.
*
* @since 7.0
*/
protected void standardPutAll(Map<? extends K, ? extends V> map) {
Maps.putAllImpl(this, map);
}
/**
* A sensible, albeit inefficient, definition of {@link #remove} in terms of
* the {@code iterator} method of {@link #entrySet}. If you override {@link
* #entrySet}, you may wish to override {@link #remove} to forward to this
* implementation.
*
* <p>Alternately, you may wish to override {@link #remove} with {@code
* keySet().remove}, assuming that approach would not lead to an infinite
* loop.
*
* @since 7.0
*/
@Beta protected V standardRemove(@Nullable Object key) {
Iterator<Entry<K, V>> entryIterator = entrySet().iterator();
while (entryIterator.hasNext()) {
Entry<K, V> entry = entryIterator.next();
if (Objects.equal(entry.getKey(), key)) {
V value = entry.getValue();
entryIterator.remove();
return value;
}
}
return null;
}
/**
* A sensible definition of {@link #clear} in terms of the {@code iterator}
* method of {@link #entrySet}. In many cases, you may wish to override
* {@link #clear} to forward to this implementation.
*
* @since 7.0
*/
protected void standardClear() {
Iterators.clear(entrySet().iterator());
}
/**
* A sensible implementation of {@link Map#keySet} in terms of the following
* methods: {@link ForwardingMap#clear}, {@link ForwardingMap#containsKey},
* {@link ForwardingMap#isEmpty}, {@link ForwardingMap#remove}, {@link
* ForwardingMap#size}, and the {@link Set#iterator} method of {@link
* ForwardingMap#entrySet}. In many cases, you may wish to override {@link
* ForwardingMap#keySet} to forward to this implementation or a subclass
* thereof.
*
* @since 10.0
*/
@Beta
protected class StandardKeySet extends Maps.KeySet<K, V> {
/** Constructor for use by subclasses. */
public StandardKeySet() {
super(ForwardingMap.this);
}
}
/**
* A sensible, albeit inefficient, definition of {@link #containsKey} in terms
* of the {@code iterator} method of {@link #entrySet}. If you override {@link
* #entrySet}, you may wish to override {@link #containsKey} to forward to
* this implementation.
*
* @since 7.0
*/
@Beta protected boolean standardContainsKey(@Nullable Object key) {
return Maps.containsKeyImpl(this, key);
}
/**
* A sensible implementation of {@link Map#values} in terms of the following
* methods: {@link ForwardingMap#clear}, {@link ForwardingMap#containsValue},
* {@link ForwardingMap#isEmpty}, {@link ForwardingMap#size}, and the {@link
* Set#iterator} method of {@link ForwardingMap#entrySet}. In many cases, you
* may wish to override {@link ForwardingMap#values} to forward to this
* implementation or a subclass thereof.
*
* @since 10.0
*/
@Beta
protected class StandardValues extends Maps.Values<K, V> {
/** Constructor for use by subclasses. */
public StandardValues() {
super(ForwardingMap.this);
}
}
/**
* A sensible definition of {@link #containsValue} in terms of the {@code
* iterator} method of {@link #entrySet}. If you override {@link #entrySet},
* you may wish to override {@link #containsValue} to forward to this
* implementation.
*
* @since 7.0
*/
protected boolean standardContainsValue(@Nullable Object value) {
return Maps.containsValueImpl(this, value);
}
/**
* A sensible implementation of {@link Map#entrySet} in terms of the following
* methods: {@link ForwardingMap#clear}, {@link ForwardingMap#containsKey},
* {@link ForwardingMap#get}, {@link ForwardingMap#isEmpty}, {@link
* ForwardingMap#remove}, and {@link ForwardingMap#size}. In many cases, you
* may wish to override {@link #entrySet} to forward to this implementation
* or a subclass thereof.
*
* @since 10.0
*/
@Beta
protected abstract class StandardEntrySet extends Maps.EntrySet<K, V> {
/** Constructor for use by subclasses. */
public StandardEntrySet() {}
@Override
Map<K, V> map() {
return ForwardingMap.this;
}
}
/**
* A sensible definition of {@link #isEmpty} in terms of the {@code iterator}
* method of {@link #entrySet}. If you override {@link #entrySet}, you may
* wish to override {@link #isEmpty} to forward to this implementation.
*
* @since 7.0
*/
protected boolean standardIsEmpty() {
return !entrySet().iterator().hasNext();
}
/**
* A sensible definition of {@link #equals} in terms of the {@code equals}
* method of {@link #entrySet}. If you override {@link #entrySet}, you may
* wish to override {@link #equals} to forward to this implementation.
*
* @since 7.0
*/
protected boolean standardEquals(@Nullable Object object) {
return Maps.equalsImpl(this, object);
}
/**
* A sensible definition of {@link #hashCode} in terms of the {@code iterator}
* method of {@link #entrySet}. If you override {@link #entrySet}, you may
* wish to override {@link #hashCode} to forward to this implementation.
*
* @since 7.0
*/
protected int standardHashCode() {
return Sets.hashCodeImpl(entrySet());
}
/**
* A sensible definition of {@link #toString} in terms of the {@code iterator}
* method of {@link #entrySet}. If you override {@link #entrySet}, you may
* wish to override {@link #toString} to forward to this implementation.
*
* @since 7.0
*/
protected String standardToString() {
return Maps.toStringImpl(this);
}
}
| Java |
/*
* 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.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
/**
* {@code FluentIterable} provides a rich interface for manipulating {@code Iterable} instances in a
* chained fashion. A {@code FluentIterable} can be created from an {@code Iterable}, or from a set
* of elements. The following types of methods are provided on {@code FluentIterable}:
* <ul>
* <li>chained methods which return a new {@code FluentIterable} based in some way on the contents
* of the current one (for example {@link #transform})
* <li>conversion methods which copy the {@code FluentIterable}'s contents into a new collection or
* array (for example {@link #toList})
* <li>element extraction methods which facilitate the retrieval of certain elements (for example
* {@link #last})
* <li>query methods which answer questions about the {@code FluentIterable}'s contents (for example
* {@link #anyMatch})
* </ul>
*
* <p>Here is an example that merges the lists returned by two separate database calls, transforms
* it by invoking {@code toString()} on each element, and returns the first 10 elements as an
* {@code ImmutableList}: <pre> {@code
*
* FluentIterable
* .from(database.getClientList())
* .filter(activeInLastMonth())
* .transform(Functions.toStringFunction())
* .limit(10)
* .toList();}</pre>
*
* <p>Anything which can be done using {@code FluentIterable} could be done in a different fashion
* (often with {@link Iterables}), however the use of {@code FluentIterable} makes many sets of
* operations significantly more concise.
*
* @author Marcin Mikosik
* @since 12.0
*/
@GwtCompatible(emulated = true)
public abstract class FluentIterable<E> implements Iterable<E> {
// We store 'iterable' and use it instead of 'this' to allow Iterables to perform instanceof
// checks on the _original_ iterable when FluentIterable.from is used.
private final Iterable<E> iterable;
/** Constructor for use by subclasses. */
protected FluentIterable() {
this.iterable = this;
}
FluentIterable(Iterable<E> iterable) {
this.iterable = checkNotNull(iterable);
}
/**
* Returns a fluent iterable that wraps {@code iterable}, or {@code iterable} itself if it
* is already a {@code FluentIterable}.
*/
public static <E> FluentIterable<E> from(final Iterable<E> iterable) {
return (iterable instanceof FluentIterable) ? (FluentIterable<E>) iterable
: new FluentIterable<E>(iterable) {
@Override
public Iterator<E> iterator() {
return iterable.iterator();
}
};
}
/**
* Construct a fluent iterable from another fluent iterable. This is obviously never necessary,
* but is intended to help call out cases where one migration from {@code Iterable} to
* {@code FluentIterable} has obviated the need to explicitly convert to a {@code FluentIterable}.
*
* @deprecated instances of {@code FluentIterable} don't need to be converted to
* {@code FluentIterable}
*/
@Deprecated
public static <E> FluentIterable<E> from(FluentIterable<E> iterable) {
return checkNotNull(iterable);
}
/**
* Returns a string representation of this fluent iterable, with the format
* {@code [e1, e2, ..., en]}.
*/
@Override
public String toString() {
return Iterables.toString(iterable);
}
/**
* Returns the number of elements in this fluent iterable.
*/
public final int size() {
return Iterables.size(iterable);
}
/**
* Returns {@code true} if this fluent iterable contains any object for which
* {@code equals(element)} is true.
*/
public final boolean contains(@Nullable Object element) {
return Iterables.contains(iterable, element);
}
/**
* Returns a fluent iterable whose {@code Iterator} cycles indefinitely over the elements of
* this fluent iterable.
*
* <p>That iterator supports {@code remove()} if {@code iterable.iterator()} does. After
* {@code remove()} is called, subsequent cycles omit the removed element, which is no longer in
* this fluent iterable. The iterator's {@code hasNext()} method returns {@code true} until
* this fluent iterable is empty.
*
* <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You
* should use an explicit {@code break} or be certain that you will eventually remove all the
* elements.
*/
@CheckReturnValue
public final FluentIterable<E> cycle() {
return from(Iterables.cycle(iterable));
}
/**
* Returns the elements from this fluent iterable that satisfy a predicate. The
* resulting fluent iterable's iterator does not support {@code remove()}.
*/
@CheckReturnValue
public final FluentIterable<E> filter(Predicate<? super E> predicate) {
return from(Iterables.filter(iterable, predicate));
}
/**
* Returns the elements from this fluent iterable that are instances of class {@code type}.
*
* @param type the type of elements desired
*/
@GwtIncompatible("Class.isInstance")
@CheckReturnValue
public final <T> FluentIterable<T> filter(Class<T> type) {
return from(Iterables.filter(iterable, type));
}
/**
* Returns {@code true} if any element in this fluent iterable satisfies the predicate.
*/
public final boolean anyMatch(Predicate<? super E> predicate) {
return Iterables.any(iterable, predicate);
}
/**
* Returns {@code true} if every element in this fluent iterable satisfies the predicate.
* If this fluent iterable is empty, {@code true} is returned.
*/
public final boolean allMatch(Predicate<? super E> predicate) {
return Iterables.all(iterable, predicate);
}
/**
* Returns an {@link Optional} containing the first element in this fluent iterable that
* satisfies the given predicate, if such an element exists.
*
* <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code null}. If {@code null}
* is matched in this fluent iterable, a {@link NullPointerException} will be thrown.
*/
public final Optional<E> firstMatch(Predicate<? super E> predicate) {
return Iterables.tryFind(iterable, predicate);
}
/**
* Returns a fluent iterable that applies {@code function} to each element of this
* fluent iterable.
*
* <p>The returned fluent iterable's iterator supports {@code remove()} if this iterable's
* iterator does. After a successful {@code remove()} call, this fluent iterable no longer
* contains the corresponding element.
*/
public final <T> FluentIterable<T> transform(Function<? super E, T> function) {
return from(Iterables.transform(iterable, function));
}
/**
* Applies {@code function} to each element of this fluent iterable and returns
* a fluent iterable with the concatenated combination of results. {@code function}
* returns an Iterable of results.
*
* <p>The returned fluent iterable's iterator supports {@code remove()} if this
* function-returned iterables' iterator does. After a successful {@code remove()} call,
* the returned fluent iterable no longer contains the corresponding element.
*
* @since 13.0 (required {@code Function<E, Iterable<T>>} until 14.0)
*/
public <T> FluentIterable<T> transformAndConcat(
Function<? super E, ? extends Iterable<? extends T>> function) {
return from(Iterables.concat(transform(function)));
}
/**
* Returns an {@link Optional} containing the first element in this fluent iterable.
* If the iterable is empty, {@code Optional.absent()} is returned.
*
* @throws NullPointerException if the first element is null; if this is a possibility, use
* {@code iterator().next()} or {@link Iterables#getFirst} instead.
*/
public final Optional<E> first() {
Iterator<E> iterator = iterable.iterator();
return iterator.hasNext()
? Optional.of(iterator.next())
: Optional.<E>absent();
}
/**
* Returns an {@link Optional} containing the last element in this fluent iterable.
* If the iterable is empty, {@code Optional.absent()} is returned.
*
* @throws NullPointerException if the last element is null; if this is a possibility, use
* {@link Iterables#getLast} instead.
*/
public final Optional<E> last() {
// Iterables#getLast was inlined here so we don't have to throw/catch a NSEE
// TODO(kevinb): Support a concurrently modified collection?
if (iterable instanceof List) {
List<E> list = (List<E>) iterable;
if (list.isEmpty()) {
return Optional.absent();
}
return Optional.of(list.get(list.size() - 1));
}
Iterator<E> iterator = iterable.iterator();
if (!iterator.hasNext()) {
return Optional.absent();
}
/*
* TODO(kevinb): consider whether this "optimization" is worthwhile. Users
* with SortedSets tend to know they are SortedSets and probably would not
* call this method.
*/
if (iterable instanceof SortedSet) {
SortedSet<E> sortedSet = (SortedSet<E>) iterable;
return Optional.of(sortedSet.last());
}
while (true) {
E current = iterator.next();
if (!iterator.hasNext()) {
return Optional.of(current);
}
}
}
/**
* Returns a view of this fluent iterable that skips its first {@code numberToSkip}
* elements. If this fluent iterable contains fewer than {@code numberToSkip} elements,
* the returned fluent iterable skips all of its elements.
*
* <p>Modifications to this fluent iterable before a call to {@code iterator()} are
* reflected in the returned fluent iterable. That is, the its iterator skips the first
* {@code numberToSkip} elements that exist when the iterator is created, not when {@code skip()}
* is called.
*
* <p>The returned fluent iterable's iterator supports {@code remove()} if the
* {@code Iterator} of this fluent iterable supports it. Note that it is <i>not</i>
* possible to delete the last skipped element by immediately calling {@code remove()} on the
* returned fluent iterable's iterator, as the {@code Iterator} contract states that a call
* to {@code * remove()} before a call to {@code next()} will throw an
* {@link IllegalStateException}.
*/
@CheckReturnValue
public final FluentIterable<E> skip(int numberToSkip) {
return from(Iterables.skip(iterable, numberToSkip));
}
/**
* Creates a fluent iterable with the first {@code size} elements of this
* fluent iterable. If this fluent iterable does not contain that many elements,
* the returned fluent iterable will have the same behavior as this fluent iterable.
* The returned fluent iterable's iterator supports {@code remove()} if this
* fluent iterable's iterator does.
*
* @param size the maximum number of elements in the returned fluent iterable
* @throws IllegalArgumentException if {@code size} is negative
*/
@CheckReturnValue
public final FluentIterable<E> limit(int size) {
return from(Iterables.limit(iterable, size));
}
/**
* Determines whether this fluent iterable is empty.
*/
public final boolean isEmpty() {
return !iterable.iterator().hasNext();
}
/**
* Returns an {@code ImmutableList} containing all of the elements from this fluent iterable in
* proper sequence.
*
* @since 14.0 (since 12.0 as {@code toImmutableList()}).
*/
public final ImmutableList<E> toList() {
return ImmutableList.copyOf(iterable);
}
/**
* Returns an {@code ImmutableList} containing all of the elements from this {@code
* FluentIterable} in the order specified by {@code comparator}. To produce an {@code
* ImmutableList} sorted by its natural ordering, use {@code toSortedList(Ordering.natural())}.
*
* @param comparator the function by which to sort list elements
* @throws NullPointerException if any element is null
* @since 14.0 (since 13.0 as {@code toSortedImmutableList()}).
*/
@Beta
public final ImmutableList<E> toSortedList(Comparator<? super E> comparator) {
return Ordering.from(comparator).immutableSortedCopy(iterable);
}
/**
* Returns an {@code ImmutableSet} containing all of the elements from this fluent iterable with
* duplicates removed.
*
* @since 14.0 (since 12.0 as {@code toImmutableSet()}).
*/
public final ImmutableSet<E> toSet() {
return ImmutableSet.copyOf(iterable);
}
/**
* Returns an {@code ImmutableSortedSet} containing all of the elements from this {@code
* FluentIterable} in the order specified by {@code comparator}, with duplicates (determined by
* {@code comparator.compare(x, y) == 0}) removed. To produce an {@code ImmutableSortedSet} sorted
* by its natural ordering, use {@code toSortedSet(Ordering.natural())}.
*
* @param comparator the function by which to sort set elements
* @throws NullPointerException if any element is null
* @since 14.0 (since 12.0 as {@code toImmutableSortedSet()}).
*/
public final ImmutableSortedSet<E> toSortedSet(Comparator<? super E> comparator) {
return ImmutableSortedSet.copyOf(comparator, iterable);
}
/**
* Returns an immutable map for which the elements of this {@code FluentIterable} are the keys in
* the same order, mapped to values by the given function. If this iterable contains duplicate
* elements, the returned map will contain each distinct element once in the order it first
* appears.
*
* @throws NullPointerException if any element of this iterable is {@code null}, or if {@code
* valueFunction} produces {@code null} for any key
* @since 14.0
*/
public final <V> ImmutableMap<E, V> toMap(Function<? super E, V> valueFunction) {
return Maps.toMap(iterable, valueFunction);
}
/**
* Creates an index {@code ImmutableListMultimap} that contains the results of applying a
* specified function to each item in this {@code FluentIterable} of values. Each element of this
* iterable will be stored as a value in the resulting multimap, yielding a multimap with the same
* size as this iterable. The key used to store that value in the multimap will be the result of
* calling the function on that value. The resulting multimap is created as an immutable snapshot.
* In the returned multimap, keys appear in the order they are first encountered, and the values
* corresponding to each key appear in the same order as they are encountered.
*
* @param keyFunction the function used to produce the key for each value
* @throws NullPointerException if any of the following cases is true:
* <ul>
* <li>{@code keyFunction} is null
* <li>An element in this fluent iterable is null
* <li>{@code keyFunction} returns {@code null} for any element of this iterable
* </ul>
* @since 14.0
*/
public final <K> ImmutableListMultimap<K, E> index(Function<? super E, K> keyFunction) {
return Multimaps.index(iterable, keyFunction);
}
/**
* Returns an immutable map for which the {@link java.util.Map#values} are the elements of this
* {@code FluentIterable} in the given order, and each key is the product of invoking a supplied
* function on its corresponding value.
*
* @param keyFunction the function used to produce the key for each value
* @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one
* value in this fluent iterable
* @throws NullPointerException if any element of this fluent iterable is null, or if
* {@code keyFunction} produces {@code null} for any value
* @since 14.0
*/
public final <K> ImmutableMap<K, E> uniqueIndex(Function<? super E, K> keyFunction) {
return Maps.uniqueIndex(iterable, keyFunction);
}
/**
* Returns an array containing all of the elements from this fluent iterable in iteration order.
*
* @param type the type of the elements
* @return a newly-allocated array into which all the elements of this fluent iterable have
* been copied
*/
@GwtIncompatible("Array.newArray(Class, int)")
public final E[] toArray(Class<E> type) {
return Iterables.toArray(iterable, type);
}
/**
* Copies all the elements from this fluent iterable to {@code collection}. This is equivalent to
* calling {@code Iterables.addAll(collection, this)}.
*
* @param collection the collection to copy elements to
* @return {@code collection}, for convenience
* @since 14.0
*/
public final <C extends Collection<? super E>> C copyInto(C collection) {
checkNotNull(collection);
if (iterable instanceof Collection) {
collection.addAll(Collections2.cast(iterable));
} else {
for (E item : iterable) {
collection.add(item);
}
}
return collection;
}
/**
* Returns the element at the specified position in this fluent iterable.
*
* @param position position of the element to return
* @return the element at the specified position in this fluent iterable
* @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to
* the size of this fluent iterable
*/
public final E get(int position) {
return Iterables.get(iterable, position);
}
/**
* Function that transforms {@code Iterable<E>} into a fluent iterable.
*/
private static class FromIterableFunction<E>
implements Function<Iterable<E>, FluentIterable<E>> {
@Override
public FluentIterable<E> apply(Iterable<E> fromObject) {
return FluentIterable.from(fromObject);
}
}
}
| Java |
/*
* 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.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.Serializable;
import java.util.Map.Entry;
import javax.annotation.Nullable;
/**
* {@code keySet()} implementation for {@link ImmutableMap}.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
final class ImmutableMapKeySet<K, V> extends ImmutableSet<K> {
private final ImmutableMap<K, V> map;
ImmutableMapKeySet(ImmutableMap<K, V> map) {
this.map = map;
}
@Override
public int size() {
return map.size();
}
@Override
public UnmodifiableIterator<K> iterator() {
return asList().iterator();
}
@Override
public boolean contains(@Nullable Object object) {
return map.containsKey(object);
}
@Override
ImmutableList<K> createAsList() {
final ImmutableList<Entry<K, V>> entryList = map.entrySet().asList();
return new ImmutableAsList<K>() {
@Override
public K get(int index) {
return entryList.get(index).getKey();
}
@Override
ImmutableCollection<K> delegateCollection() {
return ImmutableMapKeySet.this;
}
};
}
@Override
boolean isPartialView() {
return true;
}
@GwtIncompatible("serialization")
@Override Object writeReplace() {
return new KeySetSerializedForm<K>(map);
}
@GwtIncompatible("serialization")
private static class KeySetSerializedForm<K> implements Serializable {
final ImmutableMap<K, ?> map;
KeySetSerializedForm(ImmutableMap<K, ?> map) {
this.map = map;
}
Object readResolve() {
return map.keySet();
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* Copyright (C) 2009 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.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.util.Comparator;
import javax.annotation.Nullable;
/**
* List returned by {@code ImmutableSortedSet.asList()} when the set isn't empty.
*
* @author Jared Levy
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("serial")
final class ImmutableSortedAsList<E> extends RegularImmutableAsList<E>
implements SortedIterable<E> {
ImmutableSortedAsList(
ImmutableSortedSet<E> backingSet, ImmutableList<E> backingList) {
super(backingSet, backingList);
}
@Override
ImmutableSortedSet<E> delegateCollection() {
return (ImmutableSortedSet<E>) super.delegateCollection();
}
@Override public Comparator<? super E> comparator() {
return delegateCollection().comparator();
}
// Override indexOf() and lastIndexOf() to be O(log N) instead of O(N).
@GwtIncompatible("ImmutableSortedSet.indexOf")
// TODO(cpovirk): consider manual binary search under GWT to preserve O(log N) lookup
@Override public int indexOf(@Nullable Object target) {
int index = delegateCollection().indexOf(target);
// TODO(kevinb): reconsider if it's really worth making feeble attempts at
// sanity for inconsistent comparators.
// The equals() check is needed when the comparator isn't compatible with
// equals().
return (index >= 0 && get(index).equals(target)) ? index : -1;
}
@GwtIncompatible("ImmutableSortedSet.indexOf")
@Override public int lastIndexOf(@Nullable Object target) {
return indexOf(target);
}
@Override
public boolean contains(Object target) {
// Necessary for ISS's with comparators inconsistent with equals.
return indexOf(target) >= 0;
}
@GwtIncompatible("super.subListUnchecked does not exist; inherited subList is valid if slow")
/*
* TODO(cpovirk): if we start to override indexOf/lastIndexOf under GWT, we'll want some way to
* override subList to return an ImmutableSortedAsList for better performance. Right now, I'm not
* sure there's any performance hit from our failure to override subListUnchecked under GWT
*/
@Override
ImmutableList<E> subListUnchecked(int fromIndex, int toIndex) {
return new RegularImmutableSortedSet<E>(
super.subListUnchecked(fromIndex, toIndex), comparator())
.asList();
}
}
| Java |
/*
* Copyright (C) 2009 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.collect;
import com.google.common.annotations.GwtCompatible;
/**
* Implementation of {@link ImmutableListMultimap} with no entries.
*
* @author Mike Ward
*/
@GwtCompatible(serializable = true)
class EmptyImmutableSetMultimap extends ImmutableSetMultimap<Object, Object> {
static final EmptyImmutableSetMultimap INSTANCE
= new EmptyImmutableSetMultimap();
private EmptyImmutableSetMultimap() {
super(ImmutableMap.<Object, ImmutableSet<Object>>of(), 0, null);
}
private Object readResolve() {
return INSTANCE; // preserve singleton property
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2007 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.collect;
import static com.google.common.collect.Multisets.setCountImpl;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import javax.annotation.Nullable;
/**
* This class provides a skeletal implementation of the {@link Multiset}
* interface. A new multiset implementation can be created easily by extending
* this class and implementing the {@link Multiset#entrySet()} method, plus
* optionally overriding {@link #add(Object, int)} and
* {@link #remove(Object, int)} to enable modifications to the multiset.
*
* <p>The {@link #count} and {@link #size} implementations all iterate across
* the set returned by {@link Multiset#entrySet()}, as do many methods acting on
* the set returned by {@link #elementSet()}. Override those methods for better
* performance.
*
* @author Kevin Bourrillion
* @author Louis Wasserman
*/
@GwtCompatible
abstract class AbstractMultiset<E> extends AbstractCollection<E>
implements Multiset<E> {
// Query Operations
@Override public int size() {
return Multisets.sizeImpl(this);
}
@Override public boolean isEmpty() {
return entrySet().isEmpty();
}
@Override public boolean contains(@Nullable Object element) {
return count(element) > 0;
}
@Override public Iterator<E> iterator() {
return Multisets.iteratorImpl(this);
}
@Override
public int count(@Nullable Object element) {
for (Entry<E> entry : entrySet()) {
if (Objects.equal(entry.getElement(), element)) {
return entry.getCount();
}
}
return 0;
}
// Modification Operations
@Override public boolean add(@Nullable E element) {
add(element, 1);
return true;
}
@Override
public int add(@Nullable E element, int occurrences) {
throw new UnsupportedOperationException();
}
@Override public boolean remove(@Nullable Object element) {
return remove(element, 1) > 0;
}
@Override
public int remove(@Nullable Object element, int occurrences) {
throw new UnsupportedOperationException();
}
@Override
public int setCount(@Nullable E element, int count) {
return setCountImpl(this, element, count);
}
@Override
public boolean setCount(@Nullable E element, int oldCount, int newCount) {
return setCountImpl(this, element, oldCount, newCount);
}
// Bulk Operations
/**
* {@inheritDoc}
*
* <p>This implementation is highly efficient when {@code elementsToAdd}
* is itself a {@link Multiset}.
*/
@Override public boolean addAll(Collection<? extends E> elementsToAdd) {
return Multisets.addAllImpl(this, elementsToAdd);
}
@Override public boolean removeAll(Collection<?> elementsToRemove) {
return Multisets.removeAllImpl(this, elementsToRemove);
}
@Override public boolean retainAll(Collection<?> elementsToRetain) {
return Multisets.retainAllImpl(this, elementsToRetain);
}
@Override public void clear() {
Iterators.clear(entryIterator());
}
// Views
private transient Set<E> elementSet;
@Override
public Set<E> elementSet() {
Set<E> result = elementSet;
if (result == null) {
elementSet = result = createElementSet();
}
return result;
}
/**
* Creates a new instance of this multiset's element set, which will be
* returned by {@link #elementSet()}.
*/
Set<E> createElementSet() {
return new ElementSet();
}
class ElementSet extends Multisets.ElementSet<E> {
@Override
Multiset<E> multiset() {
return AbstractMultiset.this;
}
}
abstract Iterator<Entry<E>> entryIterator();
abstract int distinctElements();
private transient Set<Entry<E>> entrySet;
@Override public Set<Entry<E>> entrySet() {
Set<Entry<E>> result = entrySet;
return (result == null) ? entrySet = createEntrySet() : result;
}
class EntrySet extends Multisets.EntrySet<E> {
@Override Multiset<E> multiset() {
return AbstractMultiset.this;
}
@Override public Iterator<Entry<E>> iterator() {
return entryIterator();
}
@Override public int size() {
return distinctElements();
}
}
Set<Entry<E>> createEntrySet() {
return new EntrySet();
}
// Object methods
/**
* {@inheritDoc}
*
* <p>This implementation returns {@code true} if {@code object} is a multiset
* of the same size and if, for each element, the two multisets have the same
* count.
*/
@Override public boolean equals(@Nullable Object object) {
return Multisets.equalsImpl(this, object);
}
/**
* {@inheritDoc}
*
* <p>This implementation returns the hash code of {@link
* Multiset#entrySet()}.
*/
@Override public int hashCode() {
return entrySet().hashCode();
}
/**
* {@inheritDoc}
*
* <p>This implementation returns the result of invoking {@code toString} on
* {@link Multiset#entrySet()}.
*/
@Override public String toString() {
return entrySet().toString();
}
}
| Java |
/*
* Copyright (C) 2011 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.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.BoundType.CLOSED;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.Serializable;
import java.util.Collection;
import javax.annotation.Nullable;
/**
* An implementation of {@link ContiguousSet} that contains one or more elements.
*
* @author Gregory Kick
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("unchecked") // allow ungenerified Comparable types
final class RegularContiguousSet<C extends Comparable> extends ContiguousSet<C> {
private final Range<C> range;
RegularContiguousSet(Range<C> range, DiscreteDomain<C> domain) {
super(domain);
this.range = range;
}
private ContiguousSet<C> intersectionInCurrentDomain(Range<C> other) {
return (range.isConnected(other))
? ContiguousSet.create(range.intersection(other), domain)
: new EmptyContiguousSet<C>(domain);
}
@Override ContiguousSet<C> headSetImpl(C toElement, boolean inclusive) {
return intersectionInCurrentDomain(Range.upTo(toElement, BoundType.forBoolean(inclusive)));
}
@Override ContiguousSet<C> subSetImpl(C fromElement, boolean fromInclusive, C toElement,
boolean toInclusive) {
if (fromElement.compareTo(toElement) == 0 && !fromInclusive && !toInclusive) {
// Range would reject our attempt to create (x, x).
return new EmptyContiguousSet<C>(domain);
}
return intersectionInCurrentDomain(Range.range(
fromElement, BoundType.forBoolean(fromInclusive),
toElement, BoundType.forBoolean(toInclusive)));
}
@Override ContiguousSet<C> tailSetImpl(C fromElement, boolean inclusive) {
return intersectionInCurrentDomain(Range.downTo(fromElement, BoundType.forBoolean(inclusive)));
}
@GwtIncompatible("not used by GWT emulation")
@Override int indexOf(Object target) {
return contains(target) ? (int) domain.distance(first(), (C) target) : -1;
}
@Override public UnmodifiableIterator<C> iterator() {
return new AbstractSequentialIterator<C>(first()) {
final C last = last();
@Override
protected C computeNext(C previous) {
return equalsOrThrow(previous, last) ? null : domain.next(previous);
}
};
}
@GwtIncompatible("NavigableSet")
@Override public UnmodifiableIterator<C> descendingIterator() {
return new AbstractSequentialIterator<C>(last()) {
final C first = first();
@Override
protected C computeNext(C previous) {
return equalsOrThrow(previous, first) ? null : domain.previous(previous);
}
};
}
private static boolean equalsOrThrow(Comparable<?> left, @Nullable Comparable<?> right) {
return right != null && Range.compareOrThrow(left, right) == 0;
}
@Override boolean isPartialView() {
return false;
}
@Override public C first() {
return range.lowerBound.leastValueAbove(domain);
}
@Override public C last() {
return range.upperBound.greatestValueBelow(domain);
}
@Override public int size() {
long distance = domain.distance(first(), last());
return (distance >= Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) distance + 1;
}
@Override public boolean contains(@Nullable Object object) {
if (object == null) {
return false;
}
try {
return range.contains((C) object);
} catch (ClassCastException e) {
return false;
}
}
@Override public boolean containsAll(Collection<?> targets) {
return Collections2.containsAllImpl(this, targets);
}
@Override public boolean isEmpty() {
return false;
}
@Override public ContiguousSet<C> intersection(ContiguousSet<C> other) {
checkNotNull(other);
checkArgument(this.domain.equals(other.domain));
if (other.isEmpty()) {
return other;
} else {
C lowerEndpoint = Ordering.natural().max(this.first(), other.first());
C upperEndpoint = Ordering.natural().min(this.last(), other.last());
return (lowerEndpoint.compareTo(upperEndpoint) < 0)
? ContiguousSet.create(Range.closed(lowerEndpoint, upperEndpoint), domain)
: new EmptyContiguousSet<C>(domain);
}
}
@Override public Range<C> range() {
return range(CLOSED, CLOSED);
}
@Override public Range<C> range(BoundType lowerBoundType, BoundType upperBoundType) {
return Range.create(range.lowerBound.withLowerBoundType(lowerBoundType, domain),
range.upperBound.withUpperBoundType(upperBoundType, domain));
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
} else if (object instanceof RegularContiguousSet) {
RegularContiguousSet<?> that = (RegularContiguousSet<?>) object;
if (this.domain.equals(that.domain)) {
return this.first().equals(that.first())
&& this.last().equals(that.last());
}
}
return super.equals(object);
}
// copied to make sure not to use the GWT-emulated version
@Override public int hashCode() {
return Sets.hashCodeImpl(this);
}
@GwtIncompatible("serialization")
private static final class SerializedForm<C extends Comparable> implements Serializable {
final Range<C> range;
final DiscreteDomain<C> domain;
private SerializedForm(Range<C> range, DiscreteDomain<C> domain) {
this.range = range;
this.domain = domain;
}
private Object readResolve() {
return new RegularContiguousSet<C>(range, domain);
}
}
@GwtIncompatible("serialization")
@Override Object writeReplace() {
return new SerializedForm<C>(range, domain);
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2009 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.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.util.Map;
/**
* An implementation of {@link ImmutableTable} that holds a single cell.
*
* @author Gregory Kick
*/
@GwtCompatible
class SingletonImmutableTable<R, C, V> extends ImmutableTable<R, C, V> {
final R singleRowKey;
final C singleColumnKey;
final V singleValue;
SingletonImmutableTable(R rowKey, C columnKey, V value) {
this.singleRowKey = checkNotNull(rowKey);
this.singleColumnKey = checkNotNull(columnKey);
this.singleValue = checkNotNull(value);
}
SingletonImmutableTable(Cell<R, C, V> cell) {
this(cell.getRowKey(), cell.getColumnKey(), cell.getValue());
}
@Override public ImmutableMap<R, V> column(C columnKey) {
checkNotNull(columnKey);
return containsColumn(columnKey)
? ImmutableMap.of(singleRowKey, singleValue)
: ImmutableMap.<R, V>of();
}
@Override public ImmutableMap<C, Map<R, V>> columnMap() {
return ImmutableMap.of(singleColumnKey,
(Map<R, V>) ImmutableMap.of(singleRowKey, singleValue));
}
@Override public ImmutableMap<R, Map<C, V>> rowMap() {
return ImmutableMap.of(singleRowKey,
(Map<C, V>) ImmutableMap.of(singleColumnKey, singleValue));
}
@Override public int size() {
return 1;
}
@Override
ImmutableSet<Cell<R, C, V>> createCellSet() {
return ImmutableSet.of(
cellOf(singleRowKey, singleColumnKey, singleValue));
}
@Override ImmutableCollection<V> createValues() {
return ImmutableSet.of(singleValue);
}
}
| Java |
/*
* Copyright (C) 2012 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.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Queue;
/**
* A non-blocking queue which automatically evicts elements from the head of the queue when
* attempting to add new elements onto the queue and it is full.
*
* <p>An evicting queue must be configured with a maximum size. Each time an element is added
* to a full queue, the queue automatically removes its head element. This is different from
* conventional bounded queues, which either block or reject new elements when full.
*
* <p>This class is not thread-safe, and does not accept null elements.
*
* @author Kurt Alfred Kluever
* @since 15.0
*/
@Beta
@GwtIncompatible("java.util.ArrayDeque")
public final class EvictingQueue<E> extends ForwardingQueue<E> {
private final Queue<E> delegate;
private final int maxSize;
private EvictingQueue(int maxSize) {
checkArgument(maxSize >= 0, "maxSize (%s) must >= 0", maxSize);
this.delegate = new ArrayDeque<E>(maxSize);
this.maxSize = maxSize;
}
/**
* Creates and returns a new evicting queue that will hold up to {@code maxSize} elements.
*
* <p>When {@code maxSize} is zero, elements will be evicted immediately after being added to the
* queue.
*/
public static <E> EvictingQueue<E> create(int maxSize) {
return new EvictingQueue<E>(maxSize);
}
@Override protected Queue<E> delegate() {
return delegate;
}
/**
* Adds the given element to this queue. If the queue is currently full, the element at the head
* of the queue is evicted to make room.
*
* @return {@code true} always
*/
@Override public boolean offer(E e) {
return add(e);
}
/**
* Adds the given element to this queue. If the queue is currently full, the element at the head
* of the queue is evicted to make room.
*
* @return {@code true} always
*/
@Override public boolean add(E e) {
checkNotNull(e); // check before removing
if (maxSize == 0) {
return true;
}
if (size() == maxSize) {
delegate.remove();
}
delegate.add(e);
return true;
}
@Override public boolean addAll(Collection<? extends E> collection) {
return standardAddAll(collection);
}
@Override
public boolean contains(Object object) {
return delegate().contains(checkNotNull(object));
}
@Override
public boolean remove(Object object) {
return delegate().remove(checkNotNull(object));
}
// TODO(user): Do we want to checkNotNull each element in containsAll, removeAll, and retainAll?
// TODO(user): Do we want to add EvictingQueue#isFull()?
}
| Java |
/*
* Copyright (C) 2010 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.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.collect.MapMaker.RemovalCause;
import com.google.common.collect.MapMaker.RemovalListener;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ref.ReferenceQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReferenceArray;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
/**
* Adds computing functionality to {@link MapMakerInternalMap}.
*
* @author Bob Lee
* @author Charles Fry
*/
class ComputingConcurrentHashMap<K, V> extends MapMakerInternalMap<K, V> {
final Function<? super K, ? extends V> computingFunction;
/**
* Creates a new, empty map with the specified strategy, initial capacity, load factor and
* concurrency level.
*/
ComputingConcurrentHashMap(MapMaker builder,
Function<? super K, ? extends V> computingFunction) {
super(builder);
this.computingFunction = checkNotNull(computingFunction);
}
@Override
Segment<K, V> createSegment(int initialCapacity, int maxSegmentSize) {
return new ComputingSegment<K, V>(this, initialCapacity, maxSegmentSize);
}
@Override
ComputingSegment<K, V> segmentFor(int hash) {
return (ComputingSegment<K, V>) super.segmentFor(hash);
}
V getOrCompute(K key) throws ExecutionException {
int hash = hash(checkNotNull(key));
return segmentFor(hash).getOrCompute(key, hash, computingFunction);
}
@SuppressWarnings("serial") // This class is never serialized.
static final class ComputingSegment<K, V> extends Segment<K, V> {
ComputingSegment(MapMakerInternalMap<K, V> map, int initialCapacity, int maxSegmentSize) {
super(map, initialCapacity, maxSegmentSize);
}
V getOrCompute(K key, int hash, Function<? super K, ? extends V> computingFunction)
throws ExecutionException {
try {
outer: while (true) {
// don't call getLiveEntry, which would ignore computing values
ReferenceEntry<K, V> e = getEntry(key, hash);
if (e != null) {
V value = getLiveValue(e);
if (value != null) {
recordRead(e);
return value;
}
}
// at this point e is either null, computing, or expired;
// avoid locking if it's already computing
if (e == null || !e.getValueReference().isComputingReference()) {
boolean createNewEntry = true;
ComputingValueReference<K, V> computingValueReference = null;
lock();
try {
preWriteCleanup();
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
if (valueReference.isComputingReference()) {
createNewEntry = false;
} else {
V value = e.getValueReference().get();
if (value == null) {
enqueueNotification(entryKey, hash, value, RemovalCause.COLLECTED);
} else if (map.expires() && map.isExpired(e)) {
// This is a duplicate check, as preWriteCleanup already purged expired
// entries, but let's accomodate an incorrect expiration queue.
enqueueNotification(entryKey, hash, value, RemovalCause.EXPIRED);
} else {
recordLockedRead(e);
return value;
}
// immediately reuse invalid entries
evictionQueue.remove(e);
expirationQueue.remove(e);
this.count = newCount; // write-volatile
}
break;
}
}
if (createNewEntry) {
computingValueReference = new ComputingValueReference<K, V>(computingFunction);
if (e == null) {
e = newEntry(key, hash, first);
e.setValueReference(computingValueReference);
table.set(index, e);
} else {
e.setValueReference(computingValueReference);
}
}
} finally {
unlock();
postWriteCleanup();
}
if (createNewEntry) {
// This thread solely created the entry.
return compute(key, hash, e, computingValueReference);
}
}
// The entry already exists. Wait for the computation.
checkState(!Thread.holdsLock(e), "Recursive computation");
// don't consider expiration as we're concurrent with computation
V value = e.getValueReference().waitForValue();
if (value != null) {
recordRead(e);
return value;
}
// else computing thread will clearValue
continue outer;
}
} finally {
postReadCleanup();
}
}
V compute(K key, int hash, ReferenceEntry<K, V> e,
ComputingValueReference<K, V> computingValueReference)
throws ExecutionException {
V value = null;
long start = System.nanoTime();
long end = 0;
try {
// Synchronizes on the entry to allow failing fast when a recursive computation is
// detected. This is not fool-proof since the entry may be copied when the segment
// is written to.
synchronized (e) {
value = computingValueReference.compute(key, hash);
end = System.nanoTime();
}
if (value != null) {
// putIfAbsent
V oldValue = put(key, hash, value, true);
if (oldValue != null) {
// the computed value was already clobbered
enqueueNotification(key, hash, value, RemovalCause.REPLACED);
}
}
return value;
} finally {
if (end == 0) {
end = System.nanoTime();
}
if (value == null) {
clearValue(key, hash, computingValueReference);
}
}
}
}
/**
* Used to provide computation exceptions to other threads.
*/
private static final class ComputationExceptionReference<K, V> implements ValueReference<K, V> {
final Throwable t;
ComputationExceptionReference(Throwable t) {
this.t = t;
}
@Override
public V get() {
return null;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return null;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return this;
}
@Override
public boolean isComputingReference() {
return false;
}
@Override
public V waitForValue() throws ExecutionException {
throw new ExecutionException(t);
}
@Override
public void clear(ValueReference<K, V> newValue) {}
}
/**
* Used to provide computation result to other threads.
*/
private static final class ComputedReference<K, V> implements ValueReference<K, V> {
final V value;
ComputedReference(@Nullable V value) {
this.value = value;
}
@Override
public V get() {
return value;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return null;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return this;
}
@Override
public boolean isComputingReference() {
return false;
}
@Override
public V waitForValue() {
return get();
}
@Override
public void clear(ValueReference<K, V> newValue) {}
}
private static final class ComputingValueReference<K, V> implements ValueReference<K, V> {
final Function<? super K, ? extends V> computingFunction;
@GuardedBy("ComputingValueReference.this") // writes
volatile ValueReference<K, V> computedReference = unset();
public ComputingValueReference(Function<? super K, ? extends V> computingFunction) {
this.computingFunction = computingFunction;
}
@Override
public V get() {
// All computation lookups go through waitForValue. This method thus is
// only used by put, to whom we always want to appear absent.
return null;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return null;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, @Nullable V value, ReferenceEntry<K, V> entry) {
return this;
}
@Override
public boolean isComputingReference() {
return true;
}
/**
* Waits for a computation to complete. Returns the result of the computation.
*/
@Override
public V waitForValue() throws ExecutionException {
if (computedReference == UNSET) {
boolean interrupted = false;
try {
synchronized (this) {
while (computedReference == UNSET) {
try {
wait();
} catch (InterruptedException ie) {
interrupted = true;
}
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
return computedReference.waitForValue();
}
@Override
public void clear(ValueReference<K, V> newValue) {
// The pending computation was clobbered by a manual write. Unblock all
// pending gets, and have them return the new value.
setValueReference(newValue);
// TODO(fry): could also cancel computation if we had a thread handle
}
V compute(K key, int hash) throws ExecutionException {
V value;
try {
value = computingFunction.apply(key);
} catch (Throwable t) {
setValueReference(new ComputationExceptionReference<K, V>(t));
throw new ExecutionException(t);
}
setValueReference(new ComputedReference<K, V>(value));
return value;
}
void setValueReference(ValueReference<K, V> valueReference) {
synchronized (this) {
if (computedReference == UNSET) {
computedReference = valueReference;
notifyAll();
}
}
}
}
// Serialization Support
private static final long serialVersionUID = 4;
@Override
Object writeReplace() {
return new ComputingSerializationProxy<K, V>(keyStrength, valueStrength, keyEquivalence,
valueEquivalence, expireAfterWriteNanos, expireAfterAccessNanos, maximumSize,
concurrencyLevel, removalListener, this, computingFunction);
}
static final class ComputingSerializationProxy<K, V> extends AbstractSerializationProxy<K, V> {
final Function<? super K, ? extends V> computingFunction;
ComputingSerializationProxy(Strength keyStrength, Strength valueStrength,
Equivalence<Object> keyEquivalence, Equivalence<Object> valueEquivalence,
long expireAfterWriteNanos, long expireAfterAccessNanos, int maximumSize,
int concurrencyLevel, RemovalListener<? super K, ? super V> removalListener,
ConcurrentMap<K, V> delegate, Function<? super K, ? extends V> computingFunction) {
super(keyStrength, valueStrength, keyEquivalence, valueEquivalence, expireAfterWriteNanos,
expireAfterAccessNanos, maximumSize, concurrencyLevel, removalListener, delegate);
this.computingFunction = computingFunction;
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
writeMapTo(out);
}
@SuppressWarnings("deprecation") // self-use
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
MapMaker mapMaker = readMapMaker(in);
delegate = mapMaker.makeComputingMap(computingFunction);
readEntries(in);
}
Object readResolve() {
return delegate;
}
private static final long serialVersionUID = 4;
}
}
| Java |
/*
* Copyright (C) 2007 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.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Basic implementation of the {@link SetMultimap} interface. It's a wrapper
* around {@link AbstractMapBasedMultimap} that converts the returned collections into
* {@code Sets}. The {@link #createCollection} method must return a {@code Set}.
*
* @author Jared Levy
*/
@GwtCompatible
abstract class AbstractSetMultimap<K, V>
extends AbstractMapBasedMultimap<K, V> implements SetMultimap<K, V> {
/**
* Creates a new multimap that uses the provided map.
*
* @param map place to store the mapping from each key to its corresponding
* values
*/
protected AbstractSetMultimap(Map<K, Collection<V>> map) {
super(map);
}
@Override abstract Set<V> createCollection();
@Override Set<V> createUnmodifiableEmptyCollection() {
return ImmutableSet.of();
}
// Following Javadoc copied from SetMultimap.
/**
* {@inheritDoc}
*
* <p>Because a {@code SetMultimap} has unique values for a given key, this
* method returns a {@link Set}, instead of the {@link Collection} specified
* in the {@link Multimap} interface.
*/
@Override public Set<V> get(@Nullable K key) {
return (Set<V>) super.get(key);
}
/**
* {@inheritDoc}
*
* <p>Because a {@code SetMultimap} has unique values for a given key, this
* method returns a {@link Set}, instead of the {@link Collection} specified
* in the {@link Multimap} interface.
*/
@Override public Set<Map.Entry<K, V>> entries() {
return (Set<Map.Entry<K, V>>) super.entries();
}
/**
* {@inheritDoc}
*
* <p>Because a {@code SetMultimap} has unique values for a given key, this
* method returns a {@link Set}, instead of the {@link Collection} specified
* in the {@link Multimap} interface.
*/
@Override public Set<V> removeAll(@Nullable Object key) {
return (Set<V>) super.removeAll(key);
}
/**
* {@inheritDoc}
*
* <p>Because a {@code SetMultimap} has unique values for a given key, this
* method returns a {@link Set}, instead of the {@link Collection} specified
* in the {@link Multimap} interface.
*
* <p>Any duplicates in {@code values} will be stored in the multimap once.
*/
@Override public Set<V> replaceValues(
@Nullable K key, Iterable<? extends V> values) {
return (Set<V>) super.replaceValues(key, values);
}
/**
* {@inheritDoc}
*
* <p>Though the method signature doesn't say so explicitly, the returned map
* has {@link Set} values.
*/
@Override public Map<K, Collection<V>> asMap() {
return super.asMap();
}
/**
* Stores a key-value pair in the multimap.
*
* @param key key to store in the multimap
* @param value value to store in the multimap
* @return {@code true} if the method increased the size of the multimap, or
* {@code false} if the multimap already contained the key-value pair
*/
@Override public boolean put(@Nullable K key, @Nullable V value) {
return super.put(key, value);
}
/**
* Compares the specified object to this multimap for equality.
*
* <p>Two {@code SetMultimap} instances are equal if, for each key, they
* contain the same values. Equality does not depend on the ordering of keys
* or values.
*/
@Override public boolean equals(@Nullable Object object) {
return super.equals(object);
}
private static final long serialVersionUID = 7431625294878419160L;
}
| Java |
/*
* Copyright (C) 2007 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.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Objects;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A general-purpose bimap implementation using any two backing {@code Map}
* instances.
*
* <p>Note that this class contains {@code equals()} calls that keep it from
* supporting {@code IdentityHashMap} backing maps.
*
* @author Kevin Bourrillion
* @author Mike Bostock
*/
@GwtCompatible(emulated = true)
abstract class AbstractBiMap<K, V> extends ForwardingMap<K, V>
implements BiMap<K, V>, Serializable {
private transient Map<K, V> delegate;
transient AbstractBiMap<V, K> inverse;
/** Package-private constructor for creating a map-backed bimap. */
AbstractBiMap(Map<K, V> forward, Map<V, K> backward) {
setDelegates(forward, backward);
}
/** Private constructor for inverse bimap. */
private AbstractBiMap(Map<K, V> backward, AbstractBiMap<V, K> forward) {
delegate = backward;
inverse = forward;
}
@Override protected Map<K, V> delegate() {
return delegate;
}
/**
* Returns its input, or throws an exception if this is not a valid key.
*/
K checkKey(@Nullable K key) {
return key;
}
/**
* Returns its input, or throws an exception if this is not a valid value.
*/
V checkValue(@Nullable V value) {
return value;
}
/**
* Specifies the delegate maps going in each direction. Called by the
* constructor and by subclasses during deserialization.
*/
void setDelegates(Map<K, V> forward, Map<V, K> backward) {
checkState(delegate == null);
checkState(inverse == null);
checkArgument(forward.isEmpty());
checkArgument(backward.isEmpty());
checkArgument(forward != backward);
delegate = forward;
inverse = new Inverse<V, K>(backward, this);
}
void setInverse(AbstractBiMap<V, K> inverse) {
this.inverse = inverse;
}
// Query Operations (optimizations)
@Override public boolean containsValue(@Nullable Object value) {
return inverse.containsKey(value);
}
// Modification Operations
@Override public V put(@Nullable K key, @Nullable V value) {
return putInBothMaps(key, value, false);
}
@Override
public V forcePut(@Nullable K key, @Nullable V value) {
return putInBothMaps(key, value, true);
}
private V putInBothMaps(@Nullable K key, @Nullable V value, boolean force) {
checkKey(key);
checkValue(value);
boolean containedKey = containsKey(key);
if (containedKey && Objects.equal(value, get(key))) {
return value;
}
if (force) {
inverse().remove(value);
} else {
checkArgument(!containsValue(value), "value already present: %s", value);
}
V oldValue = delegate.put(key, value);
updateInverseMap(key, containedKey, oldValue, value);
return oldValue;
}
private void updateInverseMap(
K key, boolean containedKey, V oldValue, V newValue) {
if (containedKey) {
removeFromInverseMap(oldValue);
}
inverse.delegate.put(newValue, key);
}
@Override public V remove(@Nullable Object key) {
return containsKey(key) ? removeFromBothMaps(key) : null;
}
private V removeFromBothMaps(Object key) {
V oldValue = delegate.remove(key);
removeFromInverseMap(oldValue);
return oldValue;
}
private void removeFromInverseMap(V oldValue) {
inverse.delegate.remove(oldValue);
}
// Bulk Operations
@Override public void putAll(Map<? extends K, ? extends V> map) {
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override public void clear() {
delegate.clear();
inverse.delegate.clear();
}
// Views
@Override
public BiMap<V, K> inverse() {
return inverse;
}
private transient Set<K> keySet;
@Override public Set<K> keySet() {
Set<K> result = keySet;
return (result == null) ? keySet = new KeySet() : result;
}
private class KeySet extends ForwardingSet<K> {
@Override protected Set<K> delegate() {
return delegate.keySet();
}
@Override public void clear() {
AbstractBiMap.this.clear();
}
@Override public boolean remove(Object key) {
if (!contains(key)) {
return false;
}
removeFromBothMaps(key);
return true;
}
@Override public boolean removeAll(Collection<?> keysToRemove) {
return standardRemoveAll(keysToRemove);
}
@Override public boolean retainAll(Collection<?> keysToRetain) {
return standardRetainAll(keysToRetain);
}
@Override public Iterator<K> iterator() {
return Maps.keyIterator(entrySet().iterator());
}
}
private transient Set<V> valueSet;
@Override public Set<V> values() {
/*
* We can almost reuse the inverse's keySet, except we have to fix the
* iteration order so that it is consistent with the forward map.
*/
Set<V> result = valueSet;
return (result == null) ? valueSet = new ValueSet() : result;
}
private class ValueSet extends ForwardingSet<V> {
final Set<V> valuesDelegate = inverse.keySet();
@Override protected Set<V> delegate() {
return valuesDelegate;
}
@Override public Iterator<V> iterator() {
return Maps.valueIterator(entrySet().iterator());
}
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override public String toString() {
return standardToString();
}
}
private transient Set<Entry<K, V>> entrySet;
@Override public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
return (result == null) ? entrySet = new EntrySet() : result;
}
private class EntrySet extends ForwardingSet<Entry<K, V>> {
final Set<Entry<K, V>> esDelegate = delegate.entrySet();
@Override protected Set<Entry<K, V>> delegate() {
return esDelegate;
}
@Override public void clear() {
AbstractBiMap.this.clear();
}
@Override public boolean remove(Object object) {
if (!esDelegate.contains(object)) {
return false;
}
// safe because esDelgate.contains(object).
Entry<?, ?> entry = (Entry<?, ?>) object;
inverse.delegate.remove(entry.getValue());
/*
* Remove the mapping in inverse before removing from esDelegate because
* if entry is part of esDelegate, entry might be invalidated after the
* mapping is removed from esDelegate.
*/
esDelegate.remove(entry);
return true;
}
@Override public Iterator<Entry<K, V>> iterator() {
final Iterator<Entry<K, V>> iterator = esDelegate.iterator();
return new Iterator<Entry<K, V>>() {
Entry<K, V> entry;
@Override public boolean hasNext() {
return iterator.hasNext();
}
@Override public Entry<K, V> next() {
entry = iterator.next();
final Entry<K, V> finalEntry = entry;
return new ForwardingMapEntry<K, V>() {
@Override protected Entry<K, V> delegate() {
return finalEntry;
}
@Override public V setValue(V value) {
// Preconditions keep the map and inverse consistent.
checkState(contains(this), "entry no longer in map");
// similar to putInBothMaps, but set via entry
if (Objects.equal(value, getValue())) {
return value;
}
checkArgument(!containsValue(value),
"value already present: %s", value);
V oldValue = finalEntry.setValue(value);
checkState(Objects.equal(value, get(getKey())),
"entry no longer in map");
updateInverseMap(getKey(), true, oldValue, value);
return oldValue;
}
};
}
@Override public void remove() {
checkState(entry != null);
V value = entry.getValue();
iterator.remove();
removeFromInverseMap(value);
}
};
}
// See java.util.Collections.CheckedEntrySet for details on attacks.
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override public boolean contains(Object o) {
return Maps.containsEntryImpl(delegate(), o);
}
@Override public boolean containsAll(Collection<?> c) {
return standardContainsAll(c);
}
@Override public boolean removeAll(Collection<?> c) {
return standardRemoveAll(c);
}
@Override public boolean retainAll(Collection<?> c) {
return standardRetainAll(c);
}
}
/** The inverse of any other {@code AbstractBiMap} subclass. */
private static class Inverse<K, V> extends AbstractBiMap<K, V> {
private Inverse(Map<K, V> backward, AbstractBiMap<V, K> forward) {
super(backward, forward);
}
/*
* Serialization stores the forward bimap, the inverse of this inverse.
* Deserialization calls inverse() on the forward bimap and returns that
* inverse.
*
* If a bimap and its inverse are serialized together, the deserialized
* instances have inverse() methods that return the other.
*/
@Override
K checkKey(K key) {
return inverse.checkValue(key);
}
@Override
V checkValue(V value) {
return inverse.checkKey(value);
}
/**
* @serialData the forward bimap
*/
@GwtIncompatible("java.io.ObjectOuputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(inverse());
}
@GwtIncompatible("java.io.ObjectInputStream")
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
setInverse((AbstractBiMap<V, K>) stream.readObject());
}
@GwtIncompatible("Not needed in the emulated source.")
Object readResolve() {
return inverse().inverse();
}
@GwtIncompatible("Not needed in emulated source.")
private static final long serialVersionUID = 0;
}
@GwtIncompatible("Not needed in emulated source.")
private static final long serialVersionUID = 0;
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.