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 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; } /** * Copies a collection of {@code Byte} instances into a new array of * primitive {@code byte} 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. * * @param collection a collection of {@code Byte} 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 byte[] toArray(Collection<Byte> 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] = (Byte) 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 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]; array[start + index] = checkNotNull(element); // checkNotNull for GWT (do not optimize) 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() requires Java 6 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]; array[start + index] = checkNotNull(element); // checkNotNull for GWT (do not optimize) 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() requires Java 6 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 java.io.Serializable; import java.math.BigInteger; import javax.annotation.Nullable; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; /** * 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><b>Please do not extend this class; it will be made final in the near future.</b> * * <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 */ @Beta @GwtCompatible(serializable = true) public class UnsignedLong extends Number implements Comparable<UnsignedLong>, Serializable { // TODO(user): make final as soon as util.UnsignedLong is migrated over 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; protected UnsignedLong(long value) { this.value = value; } /** * Returns an {@code UnsignedLong} that, when treated as signed, is equal to {@code value}. The * inverse operation is {@link #longValue()}. * * <p>Put another way, if {@code value} is negative, the returned result will be equal to * {@code 2^64 + value}; otherwise, the returned result will be equal to {@code value}. */ public static UnsignedLong asUnsigned(long value) { return new UnsignedLong(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 asUnsigned(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 asUnsigned(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. */ public UnsignedLong add(UnsignedLong val) { checkNotNull(val); return asUnsigned(this.value + val.value); } /** * Returns the result of subtracting this and {@code val}. If the result would be negative, * returns the low 64 bits of the result. */ public UnsignedLong subtract(UnsignedLong val) { checkNotNull(val); return asUnsigned(this.value - 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. */ public UnsignedLong multiply(UnsignedLong val) { checkNotNull(val); return asUnsigned(value * val.value); } /** * Returns the result of dividing this by {@code val}. */ public UnsignedLong divide(UnsignedLong val) { checkNotNull(val); return asUnsigned(UnsignedLongs.divide(value, val.value)); } /** * Returns the remainder of dividing this by {@code val}. */ public UnsignedLong remainder(UnsignedLong val) { checkNotNull(val); return asUnsigned(UnsignedLongs.remainder(value, 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 #asUnsigned}. * * <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) 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.Beta; 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 */ @Beta 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") 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 */ @SuppressWarnings("fallthrough") public static int log10(BigInteger x, RoundingMode mode) { checkPositive("x", x); if (fitsInLong(x)) { return LongMath.log10(x.longValue(), mode); } // capacity of 10 suffices for all x <= 10^(2^10). List<BigInteger> powersOf10 = new ArrayList<BigInteger>(10); BigInteger powerOf10 = BigInteger.TEN; while (x.compareTo(powerOf10) >= 0) { powersOf10.add(powerOf10); powerOf10 = powerOf10.pow(2); } BigInteger floorPow = BigInteger.ONE; int floorLog = 0; for (int i = powersOf10.size() - 1; i >= 0; i--) { BigInteger powOf10 = powersOf10.get(i); floorLog *= 2; BigInteger tenPow = powOf10.multiply(floorPow); if (x.compareTo(tenPow) >= 0) { floorPow = tenPow; floorLog++; } } switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(floorPow.equals(x)); // 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(); } } /** * 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 */ @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(); } } 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; } 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} */ 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.BIGGEST_BINOMIALS.length && n <= LongMath.BIGGEST_BINOMIALS[k]) { return BigInteger.valueOf(LongMath.binomial(n, k)); } BigInteger result = BigInteger.ONE; for (int i = 0; i < k; i++) { result = result.multiply(BigInteger.valueOf(n - i)); result = result.divide(BigInteger.valueOf(i + 1)); } return result; } // Returns true if BigInteger.valueOf(x.longValue()).equals(x). 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 com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; 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 */ @Beta 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: return (x >= 0.0) ? x : Math.floor(x); case CEILING: return (x >= 0.0) ? Math.ceil(x) : x; case DOWN: return x; case UP: return (x >= 0.0) ? Math.ceil(x) : Math.floor(x); case HALF_EVEN: return Math.rint(x); case HALF_UP: if (isMathematicalInteger(x)) { return x; } else { return (x >= 0.0) ? x + 0.5 : x - 0.5; } case HALF_DOWN: if (isMathematicalInteger(x)) { return x; } else if (x >= 0.0) { double z = x + 0.5; return (z == x) ? x : DoubleUtils.nextDown(z); // x + 0.5 - epsilon } else { double z = x - 0.5; return (z == x) ? x : Math.nextUp(z); // x - 0.5 + epsilon } 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 = Math.getExponent(x); if (exponent < 0) { return BigInteger.ZERO; } 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 must be 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 Math.log(x) / LN_2; // surprisingly within 1 ulp according to tests } private static final double LN_2 = Math.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 = Math.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)) <= Math.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 EVERY_SIXTEENTH_FACTORIAL[n >> 4] directly. double accum = 1.0; for (int i = 1 + (n & ~0xf); i <= n; i++) { accum *= i; } return accum * EVERY_SIXTEENTH_FACTORIAL[n >> 4]; } } @VisibleForTesting static final int MAX_FACTORIAL = 170; @VisibleForTesting static final double[] EVERY_SIXTEENTH_FACTORIAL = { 0x1.0p0, 0x1.30777758p44, 0x1.956ad0aae33a4p117, 0x1.ee69a78d72cb6p202, 0x1.fe478ee34844ap295, 0x1.c619094edabffp394, 0x1.3638dd7bd6347p498, 0x1.7cac197cfe503p605, 0x1.1e5dfc140e1e5p716, 0x1.8ce85fadb707ep829, 0x1.95d5f3d928edep945}; }
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.Beta; 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 */ @Beta 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 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") 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 (x <= cmp) ? logFloor : logFloor + 1; 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 */ @SuppressWarnings("fallthrough") public static int log10(long x, RoundingMode mode) { checkPositive("x", x); if (fitsInInt(x)) { return IntMath.log10((int) x, mode); } int logFloor = log10Floor(x); long floorPow = POWERS_OF_10[logFloor]; switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(x == floorPow); // fall through case FLOOR: case DOWN: return logFloor; case CEILING: case UP: return (x == floorPow) ? logFloor : logFloor + 1; case HALF_DOWN: case HALF_UP: case HALF_EVEN: // sqrt(10) is irrational, so log10(x)-logFloor is never exactly 0.5 return (x <= HALF_POWERS_OF_10[logFloor]) ? logFloor : logFloor + 1; default: throw new AssertionError(); } } static int log10Floor(long x) { for (int i = 1; i < POWERS_OF_10.length; i++) { if (x < POWERS_OF_10[i]) { return i - 1; } } return POWERS_OF_10.length - 1; } @VisibleForTesting static final long[] POWERS_OF_10 = { 1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L, 1000000000L, 10000000000L, 100000000000L, 1000000000000L, 10000000000000L, 100000000000000L, 1000000000000000L, 10000000000000000L, 100000000000000000L, 1000000000000000000L }; // HALF_POWERS_OF_10[i] = largest long less than 10^(i + 0.5) @VisibleForTesting static final long[] HALF_POWERS_OF_10 = { 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} */ 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; } } } 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 */ @SuppressWarnings("fallthrough") public static long sqrt(long x, RoundingMode mode) { checkNonNegative("x", x); if (fitsInInt(x)) { return IntMath.sqrt((int) x, mode); } long 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 * sqrtFloor == x) ? sqrtFloor : sqrtFloor + 1; case HALF_DOWN: case HALF_UP: case HALF_EVEN: 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.) */ return (halfSquare >= x | halfSquare < 0) ? sqrtFloor : sqrtFloor + 1; default: throw new AssertionError(); } } private static long sqrtFloor(long x) { // Hackers's Delight, Figure 11-1 long sqrt0 = (long) Math.sqrt(x); // Precision can be lost in the cast to double, so we use this as a starting estimate. long sqrt1 = (sqrt0 + (x / sqrt0)) >> 1; if (sqrt1 == sqrt0) { return sqrt0; } do { sqrt0 = sqrt1; sqrt1 = (sqrt0 + (x / sqrt0)) >> 1; } while (sqrt1 < sqrt0); return sqrt0; } /** * 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 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} */ 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} */ public static long mod(long x, long m) { if (m <= 0) { throw new ArithmeticException("Modulus " + m + " must be > 0"); } 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 | b == 0) { return a | b; } /* * Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm. * This is over 40% 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 if (a < b) { // swap a, b long t = b; b = a; a = t; } a -= b; // a is now positive and even 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 */ 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 */ 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 */ 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 */ 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); } } 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} */ 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; } if (k >= BIGGEST_BINOMIALS.length || n > BIGGEST_BINOMIALS[k]) { return Long.MAX_VALUE; } long result = 1; if (k < BIGGEST_SIMPLE_BINOMIALS.length && n <= BIGGEST_SIMPLE_BINOMIALS[k]) { // guaranteed not to overflow for (int i = 0; i < k; i++) { result *= n - i; result /= i + 1; } } else { // We want to do this in long math for speed, but want to avoid overflow. // Dividing by the GCD suffices to avoid overflow in all the remaining cases. for (int i = 1; i <= k; i++, n--) { int d = IntMath.gcd(n, i); result /= i / d; // (i/d) is guaranteed to divide result result *= n / d; } } return result; } /* * binomial(BIGGEST_BINOMIALS[k], k) fits in a long, but not * binomial(BIGGEST_BINOMIALS[k] + 1, k). */ static final int[] BIGGEST_BINOMIALS = {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(BIGGEST_SIMPLE_BINOMIALS[k], k) doesn't need to use the slower GCD-based impl, * but binomial(BIGGEST_SIMPLE_BINOMIALS[k] + 1, k) does. */ @VisibleForTesting static final int[] BIGGEST_SIMPLE_BINOMIALS = {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; } 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 static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.math.BigInteger; /** * A collection of preconditions for math functions. * * @author Louis Wasserman */ @GwtCompatible final class MathPreconditions { static int checkPositive(String role, int x) { if (x <= 0) { throw new IllegalArgumentException(role + " (" + x + ") must be > 0"); } return x; } static long checkPositive(String role, long x) { if (x <= 0) { throw new IllegalArgumentException(role + " (" + x + ") must be > 0"); } return x; } static BigInteger checkPositive(String role, BigInteger x) { if (x.signum() <= 0) { throw new IllegalArgumentException(role + " (" + x + ") must be > 0"); } return x; } static int checkNonNegative(String role, int x) { if (x < 0) { throw new IllegalArgumentException(role + " (" + x + ") must be >= 0"); } return x; } static long checkNonNegative(String role, long x) { if (x < 0) { throw new IllegalArgumentException(role + " (" + x + ") must be >= 0"); } return x; } static BigInteger checkNonNegative(String role, BigInteger x) { if (checkNotNull(x).signum() < 0) { 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 java.math.BigInteger; /** * Utilities for {@code double} primitives. Some of these are exposed in JDK 6, * but we can't depend on them there. * * @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 = Math.getExponent(d); long bits = Double.doubleToRawLongBits(d); bits &= SIGNIFICAND_MASK; return (exponent == Double.MIN_EXPONENT - 1) ? bits << 1 : bits | IMPLICIT_BIT; } static boolean isFinite(double d) { return Math.getExponent(d) <= Double.MAX_EXPONENT; } static boolean isNormal(double d) { return Math.getExponent(d) >= Double.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 = Double.doubleToRawLongBits(x) & SIGNIFICAND_MASK; return Double.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 > Double.MAX_EXPONENT) { return x.signum() * Double.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 Double.longBitsToDouble(bits); } /** * Returns its argument if it is non-negative, zero if it is negative. */ static double ensureNonNegative(double value) { checkArgument(!Double.isNaN(value)); if (value > 0.0) { return value; } else { return 0.0; } } private static final long ONE_BITS = Double.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.math.RoundingMode.HALF_EVEN; import static java.math.RoundingMode.HALF_UP; 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 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 */ @Beta @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 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 */ @GwtIncompatible("need BigIntegerMath to adequately test") @SuppressWarnings("fallthrough") 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 (x <= cmp) ? logFloor : logFloor + 1; 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 = POWERS_OF_10[logFloor]; switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(x == floorPow); // fall through case FLOOR: case DOWN: return logFloor; case CEILING: case UP: return (x == floorPow) ? logFloor : logFloor + 1; case HALF_DOWN: case HALF_UP: case HALF_EVEN: // sqrt(10) is irrational, so log10(x) - logFloor is never exactly 0.5 return (x <= HALF_POWERS_OF_10[logFloor]) ? logFloor : logFloor + 1; default: throw new AssertionError(); } } private static int log10Floor(int x) { for (int i = 1; i < POWERS_OF_10.length; i++) { if (x < POWERS_OF_10[i]) { return i - 1; } } return POWERS_OF_10.length - 1; } @VisibleForTesting static final int[] POWERS_OF_10 = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000}; // HALF_POWERS_OF_10[i] = largest int less than 10^(i + 0.5) @VisibleForTesting static final int[] HALF_POWERS_OF_10 = {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; } } 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 * sqrtFloor == x) ? sqrtFloor : sqrtFloor + 1; 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.) */ return (x <= halfSquare | halfSquare < 0) ? sqrtFloor : sqrtFloor + 1; 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} */ @GwtIncompatible("failing tests") @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); // The simple Euclidean algorithm is the fastest for ints, and is easily the most readable. while (b != 0) { int t = b; b = a % b; a = t; } return a; } /** * 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 */ @GwtIncompatible("failing tests") 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; } 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} */ @GwtIncompatible("need BigIntegerMath to adequately test") public static int factorial(int n) { checkNonNegative("n", n); return (n < FACTORIALS.length) ? FACTORIALS[n] : Integer.MAX_VALUE; } 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 >= BIGGEST_BINOMIALS.length || n > BIGGEST_BINOMIALS[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(BIGGEST_BINOMIALS[k], k) fits in an int, but not binomial(BIGGEST_BINOMIALS[k]+1,k). @VisibleForTesting static int[] BIGGEST_BINOMIALS = { Integer.MAX_VALUE, Integer.MAX_VALUE, 65536, 2345, 477, 193, 110, 75, 58, 49, 43, 39, 37, 35, 34, 34, 33 }; private IntMath() {} }
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}s. * * @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 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 = source; this.event = 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.collect.HashMultimap; import com.google.common.collect.Multimap; import java.lang.reflect.Method; /** * A {@link HandlerFindingStrategy} for collecting all event handler methods * that are marked with the {@link Subscribe} annotation. * * @author Cliff Biffle */ class AnnotatedHandlerFinder implements HandlerFindingStrategy { /** * {@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(); while (clazz != null) { for (Method method : clazz.getMethods()) { Subscribe annotation = method.getAnnotation(Subscribe.class); if (annotation != null) { Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length != 1) { throw new IllegalArgumentException( "Method " + method + " has @Subscribe annotation, but requires " + parameterTypes.length + " arguments. Event handler methods " + "must require a single argument."); } Class<?> eventType = parameterTypes[0]; EventHandler handler = makeHandler(listener, method); methodsInListener.put(eventType, handler); } } clazz = clazz.getSuperclass(); } return methodsInListener; } /** * 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 com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Supplier; 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.Lists; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.ExecutionException; 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> * 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> * 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 &mdash; 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> * 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> * 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 { /** * All registered event handlers, indexed by event type. */ private final SetMultimap<Class<?>, EventHandler> handlersByType = Multimaps.newSetMultimap(new ConcurrentHashMap<Class<?>, Collection<EventHandler>>(), new Supplier<Set<EventHandler>>() { @Override public Set<EventHandler> get() { return new CopyOnWriteArraySet<EventHandler>(); } }); /** * 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<ConcurrentLinkedQueue<EventWithHandler>> eventsToDispatch = new ThreadLocal<ConcurrentLinkedQueue<EventWithHandler>>() { @Override protected ConcurrentLinkedQueue<EventWithHandler> initialValue() { return new ConcurrentLinkedQueue<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; } }; /** * A thread-safe cache for flattenHierarch(). The Class class is immutable. */ private LoadingCache<Class<?>, Set<Class<?>>> flattenHierarchyCache = CacheBuilder.newBuilder() .weakKeys() .build(new CacheLoader<Class<?>, Set<Class<?>>>() { @Override public Set<Class<?>> load(Class<?> concreteClass) throws Exception { List<Class<?>> parents = Lists.newLinkedList(); Set<Class<?>> classes = Sets.newHashSet(); parents.add(concreteClass); while (!parents.isEmpty()) { Class<?> clazz = parents.remove(0); classes.add(clazz); Class<?> parent = clazz.getSuperclass(); if (parent != null) { parents.add(parent); } for (Class<?> iface : clazz.getInterfaces()) { parents.add(iface); } } return classes; } }); /** * 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() + "." + 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) { handlersByType.putAll(finder.findAllHandlers(object)); } /** * 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()) { Set<EventHandler> currentHandlers = getHandlersForEventType(entry.getKey()); Collection<EventHandler> eventMethodsInListener = entry.getValue(); if (currentHandlers == null || !currentHandlers.containsAll(entry.getValue())) { throw new IllegalArgumentException( "missing event handler for an annotated method. Is " + object + " registered?"); } currentHandlers.removeAll(eventMethodsInListener); } } /** * 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) { Set<EventHandler> wrappers = getHandlersForEventType(eventType); if (wrappers != null && !wrappers.isEmpty()) { dispatched = true; for (EventHandler wrapper : wrappers) { enqueueEvent(event, wrapper); } } } 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. */ protected 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. */ protected 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 { while (true) { EventWithHandler eventWithHandler = eventsToDispatch.get().poll(); if (eventWithHandler == null) { break; } dispatch(eventWithHandler.event, eventWithHandler.handler); } } finally { isDispatching.set(false); } } /** * 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. */ protected 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); } } /** * Retrieves a mutable set of the currently registered handlers for * {@code type}. If no handlers are currently registered for {@code type}, * this method may either return {@code null} or an empty set. * * @param type type of handlers to retrieve. * @return currently registered handlers, or {@code null}. */ Set<EventHandler> getHandlersForEventType(Class<?> type) { return handlersByType.get(type); } /** * Creates a new Set for insertion into the handler map. This is provided * as an override point for subclasses. The returned set should support * concurrent access. * * @return a new, mutable set for handlers. */ protected Set<EventHandler> newHandlerSet() { return new CopyOnWriteArraySet<EventHandler>(); } /** * 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.get(concreteClass); } catch (ExecutionException 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 = event; this.handler = 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 com.google.common.base.Preconditions; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * 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}s are * propagated as-is). */ public void handleEvent(Object event) throws InvocationTargetException { 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 + target.hashCode(); } @Override public boolean equals(Object obj) { if(this == obj) { return true; } if(obj == null) { return false; } if(getClass() != obj.getClass()) { return false; } final EventHandler other = (EventHandler) obj; return method.equals(other.method) && target == other.target; } }
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> * * Converting an existing EventListener-based system to use the EventBus is * easy. * * <h3>For Listeners</h3> * 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 &mdash; 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> * 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> * * 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> * * 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>Can I unregister a listener from the Event Bus?</h3> * Currently, no -- a listener registered with an EventBus instance will * continue to receive events until the EventBus itself is disposed. * * <p>In the apps using EventBus so far, this has not been a problem: * <ul> * <li>Most listeners are registered on startup or lazy initialization, and * persist for the life of the application. * <li>Scope-specific EventBus instances can handle temporary event * distribution (e.g. distributing events among request-scoped objects) * <li>For testing, EventBus instances can be easily created and thrown away, * removing the need for explicit unregistration. * </ul> * * <h3>Why use an annotation to mark handler methods, rather than requiring the * listener to implement an interface?</h3> * 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 { * &#064;Subscribe void recordCustomerChange(ChangeEvent e) { * recordChange(e.getChange()); * } * }</pre> * * 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> * 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> * * 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> * 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> * 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> * 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> * 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> * 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> * 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 */ 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 synchronized void handleEvent(Object event) throws InvocationTargetException { 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 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 = 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 = executor; } @Override protected 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. */ @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 protected void dispatch(final Object event, final EventHandler handler) { executor.execute(new Runnable() { @Override @SuppressWarnings("synthetic-access") public void run() { AsyncEventBus.super.dispatch(event, handler); } }); } }
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.annotations.VisibleForTesting; import com.google.common.base.Preconditions; 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>This class hooks into the {@code sun.net.util.IPAddressUtil} class * to make use of the {@code textToNumericFormatV4} and * {@code textToNumericFormatV6} methods directly as a means to avoid * accidentally traversing all nameservices (it can be vitally important * to avoid, say, blocking on DNS at times). * * <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(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(copyOfRange(ip.getAddress(), 2, 6)); } /** * A simple 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); if (server != null) { this.server = server; } else { this.server = ANY4; } if (client != null) { this.client = client; } else { this.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(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 = 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(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 = hash64To32(addressAsLong); // 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 {@code int} hash of a 64-bit long. * * This comes from http://www.concentric.net/~ttwang/tech/inthash.htm * * This hash gives no guarantees on the cryptographic suitability nor the * quality of randomness produced, and the mapping may change in the future. * * @param key A 64-bit number to hash * @return {@code int} the input hashed into 32 bits */ @VisibleForTesting static int hash64To32(long key) { key = (~key) + (key << 18); key = key ^ (key >>> 31); key = key * 21; key = key ^ (key >>> 11); key = key + (key << 6); key = key ^ (key >>> 22); return (int) key; } /** * 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; } /** * This method emulates the Java 6 method * {@code Arrays.copyOfRange(byte, int, int)}, which is not available in * Java 5, and thus cannot be used in Guava code. */ private static byte[] copyOfRange(byte[] original, int from, int to) { Preconditions.checkNotNull(original); int end = Math.min(to, original.length); byte[] result = new byte[to - from]; System.arraycopy(original, from, result, 0, end - from); return result; } }
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 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 */ @Beta @GwtCompatible public final class HttpHeaders { private HttpHeaders() {} // HTTP Request and Response header fields /** The HTTP Cache-Control header field name. */ public static final String CACHE_CONTROL = "Cache-Control"; /** The HTTP Content-Length header field name. */ public static final String CONTENT_LENGTH = "Content-Length"; /** The HTTP Content-Type header field name. */ public static final String CONTENT_TYPE = "Content-Type"; /** The HTTP Date header field name. */ public static final String DATE = "Date"; /** The HTTP Pragma header field name. */ public static final String PRAGMA = "Pragma"; /** The HTTP Via header field name. */ public static final String VIA = "Via"; /** The HTTP Warning header field name. */ public static final String WARNING = "Warning"; // HTTP Request header fields /** The HTTP Accept header field name. */ public static final String ACCEPT = "Accept"; /** The HTTP Accept-Charset header field name. */ public static final String ACCEPT_CHARSET = "Accept-Charset"; /** The HTTP Accept-Encoding header field name. */ public static final String ACCEPT_ENCODING = "Accept-Encoding"; /** The HTTP Accept-Language header field name. */ public static final String ACCEPT_LANGUAGE = "Accept-Language"; /** The HTTP Access-Control-Request-Headers header field name. */ public static final String ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers"; /** The HTTP Access-Control-Request-Method header field name. */ public static final String ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method"; /** The HTTP Authorization header field name. */ public static final String AUTHORIZATION = "Authorization"; /** The HTTP Connection header field name. */ public static final String CONNECTION = "Connection"; /** The HTTP Cookie header field name. */ public static final String COOKIE = "Cookie"; /** The HTTP Expect header field name. */ public static final String EXPECT = "Expect"; /** The HTTP From header field name. */ public static final String FROM = "From"; /** The HTTP Host header field name. */ public static final String HOST = "Host"; /** The HTTP If-Match header field name. */ public static final String IF_MATCH = "If-Match"; /** The HTTP If-Modified-Since header field name. */ public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; /** The HTTP If-None-Match header field name. */ public static final String IF_NONE_MATCH = "If-None-Match"; /** The HTTP If-Range header field name. */ public static final String IF_RANGE = "If-Range"; /** The HTTP If-Unmodified-Since header field name. */ public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; /** The HTTP Last-Event-ID header field name. */ public static final String LAST_EVENT_ID = "Last-Event-ID"; /** The HTTP Max-Forwards header field name. */ public static final String MAX_FORWARDS = "Max-Forwards"; /** The HTTP Origin header field name. */ public static final String ORIGIN = "Origin"; /** The HTTP Proxy-Authorization header field name. */ public static final String PROXY_AUTHORIZATION = "Proxy-Authorization"; /** The HTTP Range header field name. */ public static final String RANGE = "Range"; /** The HTTP Referer header field name. */ public static final String REFERER = "Referer"; /** The HTTP TE header field name. */ public static final String TE = "TE"; /** The HTTP Upgrade header field name. */ public static final String UPGRADE = "Upgrade"; /** The HTTP User-Agent header field name. */ public static final String USER_AGENT = "User-Agent"; // HTTP Response header fields /** The HTTP Accept-Ranges header field name. */ public static final String ACCEPT_RANGES = "Accept-Ranges"; /** The HTTP Access-Control-Allow-Headers header field name. */ public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers"; /** The HTTP Access-Control-Allow-Methods header field name. */ public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods"; /** The HTTP Access-Control-Allow-Origin header field name. */ public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin"; /** The HTTP Access-Control-Allow-Credentials header field name. */ public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials"; /** The HTTP Access-Control-Expose-Headers header field name. */ public static final String ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers"; /** The HTTP Access-Control-Max-Age header field name. */ public static final String ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age"; /** The HTTP Age header field name. */ public static final String AGE = "Age"; /** The HTTP Allow header field name. */ public static final String ALLOW = "Allow"; /** The HTTP Content-Disposition header field name. */ public static final String CONTENT_DISPOSITION = "Content-Disposition"; /** The HTTP Content-Encoding header field name. */ public static final String CONTENT_ENCODING = "Content-Encoding"; /** The HTTP Content-Language header field name. */ public static final String CONTENT_LANGUAGE = "Content-Language"; /** The HTTP Content-Location header field name. */ public static final String CONTENT_LOCATION = "Content-Location"; /** The HTTP Content-MD5 header field name. */ public static final String CONTENT_MD5 = "Content-MD5"; /** The HTTP Content-Range header field name. */ public static final String CONTENT_RANGE = "Content-Range"; /** The HTTP ETag header field name. */ public static final String ETAG = "ETag"; /** The HTTP Expires header field name. */ public static final String EXPIRES = "Expires"; /** The HTTP Last-Modified header field name. */ public static final String LAST_MODIFIED = "Last-Modified"; /** The HTTP Link header field name. */ public static final String LINK = "Link"; /** The HTTP Location header field name. */ public static final String LOCATION = "Location"; /** The HTTP P3P header field name. Limited browser support. */ public static final String P3P = "P3P"; /** The HTTP Proxy-Authenticate header field name. */ public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate"; /** The HTTP Refresh header field name. Non-standard header supported by most browsers. */ public static final String REFRESH = "Refresh"; /** The HTTP Retry-After header field name. */ public static final String RETRY_AFTER = "Retry-After"; /** The HTTP Server header field name. */ public static final String SERVER = "Server"; /** The HTTP Set-Cookie header field name. */ public static final String SET_COOKIE = "Set-Cookie"; /** The HTTP Set-Cookie2 header field name. */ public static final String SET_COOKIE2 = "Set-Cookie2"; /** The HTTP Trailer header field name. */ public static final String TRAILER = "Trailer"; /** The HTTP Transfer-Encoding header field name. */ public static final String TRANSFER_ENCODING = "Transfer-Encoding"; /** The HTTP Vary header field name. */ public static final String VARY = "Vary"; /** The HTTP WWW-Authenticate header field name. */ public static final String WWW_AUTHENTICATE = "WWW-Authenticate"; // Common, non-standard HTTP header fields /** The HTTP DNT header field name. */ public static final String DNT = "DNT"; /** The HTTP X-Content-Type-Options header field name. */ public static final String X_CONTENT_TYPE_OPTIONS = "X-Content-Type-Options"; /** The HTTP X-Do-Not-Track header field name. */ public static final String X_DO_NOT_TRACK = "X-Do-Not-Track"; /** The HTTP X-Forwarded-For header field name. */ public static final String X_FORWARDED_FOR = "X-Forwarded-For"; /** The HTTP X-Forwarded-Proto header field name. */ public static final String X_FORWARDED_PROTO = "X-Forwarded-Proto"; /** The HTTP X-Frame-Options header field name. */ public static final String X_FRAME_OPTIONS = "X-Frame-Options"; /** The HTTP X-Powered-By header field name. */ public static final String X_POWERED_BY = "X-Powered-By"; /** The HTTP X-Requested-With header field name. */ public static final String X_REQUESTED_WITH = "X-Requested-With"; /** The HTTP X-User-IP header field name. */ public static final String X_USER_IP = "X-User-IP"; /** The HTTP 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.Objects; 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> * 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(emulated = true) 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 #isValidLenient} * @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; } /** * Returns the domain name, normalized to all lower case. */ public String name() { return name; } /** * 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); } /** * A deprecated synonym for {@link #isValid(String)}. * * @since 8.0 (previously named {@code isValid}) * @deprecated Use {@link #isValid(String)} instead */ @Deprecated public static boolean isValidLenient(String name) { return isValid(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]); } // TODO: specify this to return the same as name(); remove name() @Override public String toString() { return Objects.toStringHelper(this).add("name", name).toString(); } /** * 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) 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.base.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; 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 public final class HostAndPort { /** 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. * * 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)); HostAndPort parsedHost = fromString(host); checkArgument(!parsedHost.hasPort()); return new HostAndPort(parsedHost.host, port, parsedHost.hasBracketlessColons); } private static final Pattern BRACKET_PATTERN = Pattern.compile("^\\[(.*:.*)\\](?::(\\d*))?$"); /** * 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("[")) { // Parse a bracketed host, typically an IPv6 literal. Matcher matcher = BRACKET_PATTERN.matcher(hostPortString); checkArgument(matcher.matches(), "Invalid bracketed host/port: %s", hostPortString); host = matcher.group(1); portString = matcher.group(2); // could be null } 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 (portString != null) { // 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); } /** * 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(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; } }
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>. * * @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) 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> { /* * 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; 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 Object[] toArray() { return delegate.toArray(); } @Override public <T> T[] toArray(T[] array) { return delegate.toArray(array); } @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 <E> 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 <E> 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 <E> int resultIndex(int higherIndex) { return ~higherIndex; } }; abstract <E> 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, 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, 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 static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; /** * A rule for a local mutation to a binary search tree, that changes at most one entry. In addition * to specifying how it modifies a particular entry via a {@code BstModifier}, it specifies a * {@link BstBalancePolicy} for rebalancing the tree after the modification is performed and a * {@link BstNodeFactory} for constructing newly rebalanced nodes. * * @author Louis Wasserman * @param <K> The key type of the nodes in binary search trees that this rule can modify. * @param <N> The type of the nodes in binary search trees that this rule can modify. */ @GwtCompatible final class BstMutationRule<K, N extends BstNode<K, N>> { /** * Constructs a {@code BstMutationRule} with the specified modifier, balance policy, and node * factory. */ public static <K, N extends BstNode<K, N>> BstMutationRule<K, N> createRule( BstModifier<K, N> modifier, BstBalancePolicy<N> balancePolicy, BstNodeFactory<N> nodeFactory) { return new BstMutationRule<K, N>(modifier, balancePolicy, nodeFactory); } private final BstModifier<K, N> modifier; private final BstBalancePolicy<N> balancePolicy; private final BstNodeFactory<N> nodeFactory; private BstMutationRule(BstModifier<K, N> modifier, BstBalancePolicy<N> balancePolicy, BstNodeFactory<N> nodeFactory) { this.balancePolicy = checkNotNull(balancePolicy); this.nodeFactory = checkNotNull(nodeFactory); this.modifier = checkNotNull(modifier); } /** * Returns the {@link BstModifier} that specifies the change to a targeted entry in a binary * search tree. */ public BstModifier<K, N> getModifier() { return modifier; } /** * Returns the policy used to rebalance nodes in the tree after this modification has been * performed. */ public BstBalancePolicy<N> getBalancePolicy() { return balancePolicy; } /** * Returns the node factory used to create new nodes in the tree after this modification has been * performed. */ public BstNodeFactory<N> getNodeFactory() { return nodeFactory; } }
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 javax.annotation.Nullable; /** * The result of a {@code BstModifier}. * * @author Louis Wasserman */ @GwtCompatible final class BstModificationResult<N extends BstNode<?, N>> { enum ModificationType { IDENTITY, REBUILDING_CHANGE, REBALANCING_CHANGE; } static <N extends BstNode<?, N>> BstModificationResult<N> identity(@Nullable N target) { return new BstModificationResult<N>(target, target, ModificationType.IDENTITY); } static <N extends BstNode<?, N>> BstModificationResult<N> rebuildingChange( @Nullable N originalTarget, @Nullable N changedTarget) { return new BstModificationResult<N>( originalTarget, changedTarget, ModificationType.REBUILDING_CHANGE); } static <N extends BstNode<?, N>> BstModificationResult<N> rebalancingChange( @Nullable N originalTarget, @Nullable N changedTarget) { return new BstModificationResult<N>( originalTarget, changedTarget, ModificationType.REBALANCING_CHANGE); } @Nullable private final N originalTarget; @Nullable private final N changedTarget; private final ModificationType type; private BstModificationResult( @Nullable N originalTarget, @Nullable N changedTarget, ModificationType type) { this.originalTarget = originalTarget; this.changedTarget = changedTarget; this.type = checkNotNull(type); } @Nullable N getOriginalTarget() { return originalTarget; } @Nullable N getChangedTarget() { return changedTarget; } ModificationType getType() { return type; } }
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 AbstractMultimap} 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 AbstractMultimap<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(); // 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 Google Inc. * * 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 java.util.Comparator; 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 gak@google.com (Gregory Kick) * @since 11.0 */ @Beta @GwtCompatible // TODO(gak): make serializable public abstract class ImmutableTable<R, C, V> implements Table<R, C, V> { /** Returns an empty immutable table. */ @SuppressWarnings("unchecked") public static final <R, C, V> ImmutableTable<R, C, V> of() { return (ImmutableTable<R, C, V>) EmptyImmutableTable.INSTANCE; } /** Returns an immutable table containing a single cell. */ public static final <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 final <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#Builder()} constructor. */ public static final <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 abstract ImmutableSet<Cell<R, C, V>> cellSet(); /** * {@inheritDoc} * * @throws NullPointerException if {@code columnKey} is {@code null} */ @Override public abstract ImmutableMap<R, V> column(C columnKey); @Override public abstract ImmutableSet<C> columnKeySet(); /** * {@inheritDoc} * * <p>The value {@code Map<R, V>}s in the returned map are * {@link ImmutableMap}s as well. */ @Override public abstract ImmutableMap<C, Map<R, V>> columnMap(); /** * {@inheritDoc} * * @throws NullPointerException if {@code rowKey} is {@code null} */ @Override public abstract ImmutableMap<C, V> row(R rowKey); @Override public abstract ImmutableSet<R> rowKeySet(); /** * {@inheritDoc} * * <p>The value {@code Map<C, V>}s in the returned map are * {@link ImmutableMap}s as well. */ @Override public abstract ImmutableMap<R, Map<C, V>> rowMap(); /** * Guaranteed to throw an exception and leave the table unmodified. * * @throws UnsupportedOperationException always */ @Override public final void clear() { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the table unmodified. * * @throws UnsupportedOperationException always */ @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 */ @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 */ @Override public final V remove(Object rowKey, Object columnKey) { throw new UnsupportedOperationException(); } @Override public boolean equals(@Nullable Object obj) { if (obj == this) { return true; } else if (obj instanceof Table<?, ?, ?>) { Table<?, ?, ?> that = (Table<?, ?, ?>) obj; return this.cellSet().equals(that.cellSet()); } else { return false; } } @Override public int hashCode() { return cellSet().hashCode(); } @Override public String toString() { return rowMap().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 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(Object target) { return false; } @Override public UnmodifiableIterator<Object> iterator() { return Iterators.emptyIterator(); } @Override boolean isPartialView() { return false; } private static final Object[] EMPTY_ARRAY = new Object[0]; @Override public Object[] toArray() { return EMPTY_ARRAY; } @Override public <T> T[] toArray(T[] a) { if (a.length > 0) { a[0] = null; } return a; } @Override public boolean containsAll(Collection<?> targets) { return targets.isEmpty(); } @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) 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.Equivalences; 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 = builder.getValueEquivalence(); 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 Equivalences.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 Equivalences.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 Equivalences.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; } }, SOFT { @Override <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) { return new SoftEntry<K, V>(segment.keyReferenceQueue, key, hash, next); } }, SOFT_EXPIRABLE { @Override <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) { return new SoftExpirableEntry<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; } }, SOFT_EVICTABLE { @Override <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) { return new SoftEvictableEntry<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; } }, SOFT_EXPIRABLE_EVICTABLE { @Override <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) { return new SoftExpirableEvictableEntry<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; } }, 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 }, { SOFT, SOFT_EXPIRABLE, SOFT_EVICTABLE, SOFT_EXPIRABLE_EVICTABLE }, { 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. */ ValueReference<K, V> copyFor(ReferenceQueue<V> queue, 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, 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) {} } static abstract 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, ReferenceEntry<K, V> entry) { return new WeakValueReference<K, V>(queue, get(), 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, ReferenceEntry<K, V> entry) { return new SoftValueReference<K, V>(queue, get(), 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, 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); } @GuardedBy("Segment.this") ReferenceEntry<K, V> copyEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) { ValueReference<K, V> valueReference = original.getValueReference(); ReferenceEntry<K, V> newEntry = map.entryFactory.copyEntry(this, original, newNext); newEntry.setValueReference(valueReference.copyFor(this.valueReferenceQueue, 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()) { if (isCollected(e)) { removeCollectedEntry(e); newCount--; } else { int newIndex = e.getHash() & newMask; ReferenceEntry<K, V> newNext = newTable.get(newIndex); ReferenceEntry<K, V> newFirst = copyEntry(e, newNext); newTable.set(newIndex, newFirst); } } } } } 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()) { if (isCollected(e)) { removeCollectedEntry(e); newCount--; } else { newFirst = copyEntry(e, newFirst); } } 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 entry has been partially collected, meaning that either the key * is null, or the value is null and it is not computing. */ boolean isCollected(ReferenceEntry<K, V> entry) { if (entry.getKey() == null) { return true; } return isCollected(entry.getValueReference()); } /** * 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); } /** * Returns the live internal entry for the specified key. Does not impact recency ordering. */ ReferenceEntry<K, V> getLiveEntry(@Nullable Object key) { if (key == null) { return null; } int hash = hash(key); return segmentFor(hash).getLiveEntry(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(); } } Set<K> keySet; @Override public Set<K> keySet() { Set<K> ks = keySet; return (ks != null) ? ks : (keySet = new KeySet()); } Collection<V> values; @Override public Collection<V> values() { Collection<V> vs = values; return (vs != null) ? vs : (values = new Values()); } 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 { 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(); } 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 implements Iterator<K> { @Override public K next() { return nextEntry().getKey(); } } final class ValueIterator extends HashIterator implements Iterator<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 implements Iterator<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) .valueEquivalence(valueEquivalence) .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 com.google.common.annotations.GwtCompatible; import java.io.Serializable; 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> implements Collection<E>, Serializable { static final ImmutableCollection<Object> EMPTY_IMMUTABLE_COLLECTION = new EmptyImmutableCollection(); ImmutableCollection() {} /** * Returns an unmodifiable iterator across the elements in this collection. */ @Override public abstract UnmodifiableIterator<E> iterator(); @Override public Object[] toArray() { return ObjectArrays.toArrayImpl(this); } @Override public <T> T[] toArray(T[] other) { return ObjectArrays.toArrayImpl(this, other); } @Override public boolean contains(@Nullable Object object) { return object != null && Iterators.contains(iterator(), object); } @Override public boolean containsAll(Collection<?> targets) { return Collections2.containsAllImpl(this, targets); } @Override public boolean isEmpty() { return size() == 0; } @Override public String toString() { return Collections2.toStringImpl(this); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always */ @Override public final boolean add(E e) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always */ @Override public final boolean remove(Object object) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always */ @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 */ @Override public final boolean removeAll(Collection<?> oldElements) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always */ @Override public final boolean retainAll(Collection<?> elementsToKeep) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always */ @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 ImmutableAsList<E>(toArray(), this); } } abstract boolean isPartialView(); private static class EmptyImmutableCollection extends ImmutableCollection<Object> { @Override public int size() { return 0; } @Override public boolean isEmpty() { return true; } @Override public boolean contains(@Nullable Object object) { return false; } @Override public UnmodifiableIterator<Object> iterator() { return Iterators.EMPTY_ITERATOR; } private static final Object[] EMPTY_ARRAY = new Object[0]; @Override public Object[] toArray() { return EMPTY_ARRAY; } @Override public <T> T[] toArray(T[] array) { if (array.length > 0) { array[0] = null; } return array; } @Override ImmutableList<Object> createAsList() { return ImmutableList.of(); } @Override boolean isPartialView() { return false; } } /** * Nonempty collection stored in an array. */ private static class ArrayImmutableCollection<E> extends ImmutableCollection<E> { private final E[] elements; ArrayImmutableCollection(E[] elements) { this.elements = elements; } @Override public int size() { return elements.length; } @Override public boolean isEmpty() { return false; } @Override public UnmodifiableIterator<E> iterator() { return Iterators.forArray(elements); } @Override ImmutableList<E> createAsList() { return elements.length == 1 ? new SingletonImmutableList<E>(elements[0]) : new RegularImmutableList<E>(elements); } @Override boolean isPartialView() { return false; } } /* * Serializes ImmutableCollections as their logical contents. This ensures * that implementation types do not leak into the serialized representation. */ private static class SerializedForm implements Serializable { final Object[] elements; SerializedForm(Object[] elements) { this.elements = elements; } Object readResolve() { return elements.length == 0 ? EMPTY_IMMUTABLE_COLLECTION : new ArrayImmutableCollection<Object>(Platform.clone(elements)); } private static final long serialVersionUID = 0; } Object writeReplace() { return new SerializedForm(toArray()); } /** * Abstract base class for builders of {@link ImmutableCollection} types. * * @since 10.0 */ public abstract static class Builder<E> { 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(); } }
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; /** * Bimap with one or more mappings. * * @author Jared Levy */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // uses writeReplace(), not default serialization class RegularImmutableBiMap<K, V> extends ImmutableBiMap<K, V> { final transient ImmutableMap<K, V> delegate; final transient ImmutableBiMap<V, K> inverse; RegularImmutableBiMap(ImmutableMap<K, V> delegate) { this.delegate = delegate; ImmutableMap.Builder<V, K> builder = ImmutableMap.builder(); for (Entry<K, V> entry : delegate.entrySet()) { builder.put(entry.getValue(), entry.getKey()); } ImmutableMap<V, K> backwardMap = builder.build(); this.inverse = new RegularImmutableBiMap<V, K>(backwardMap, this); } RegularImmutableBiMap(ImmutableMap<K, V> delegate, ImmutableBiMap<V, K> inverse) { this.delegate = delegate; this.inverse = inverse; } @Override ImmutableMap<K, V> delegate() { return delegate; } @Override public ImmutableBiMap<V, K> inverse() { return inverse; } @Override boolean isPartialView() { return delegate.isPartialView() || inverse.delegate().isPartialView(); } }
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.GwtCompatible; import com.google.common.collect.Multiset.Entry; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedSet; /** * Provides static utility methods for creating and working with * {@link SortedMultiset} instances. * * @author Louis Wasserman */ @GwtCompatible final class SortedMultisets { private SortedMultisets() { } /** * A skeleton implementation for {@link SortedMultiset#elementSet}. */ static abstract class ElementSet<E> extends Multisets.ElementSet<E> implements SortedSet<E> { @Override abstract SortedMultiset<E> multiset(); @Override public Comparator<? super E> comparator() { return multiset().comparator(); } @Override public SortedSet<E> subSet(E fromElement, E toElement) { return multiset().subMultiset(fromElement, BoundType.CLOSED, toElement, BoundType.OPEN).elementSet(); } @Override public SortedSet<E> headSet(E toElement) { return multiset().headMultiset(toElement, BoundType.OPEN).elementSet(); } @Override public SortedSet<E> tailSet(E fromElement) { return multiset().tailMultiset(fromElement, BoundType.CLOSED) .elementSet(); } @Override public E first() { return getElementOrThrow(multiset().firstEntry()); } @Override public E last() { return getElementOrThrow(multiset().lastEntry()); } } private static <E> E getElementOrThrow(Entry<E> entry) { if (entry == null) { throw new NoSuchElementException(); } return entry.getElement(); } /** * A skeleton implementation of a descending multiset. Only needs * {@code forwardMultiset()} and {@code entryIterator()}. */ static abstract class DescendingMultiset<E> extends ForwardingMultiset<E> implements SortedMultiset<E> { abstract SortedMultiset<E> forwardMultiset(); private transient Comparator<? super E> comparator; @Override public Comparator<? super E> comparator() { Comparator<? super E> result = comparator; if (result == null) { return comparator = Ordering.from(forwardMultiset().comparator()).<E>reverse(); } return result; } private transient SortedSet<E> elementSet; @Override public SortedSet<E> elementSet() { SortedSet<E> result = elementSet; if (result == null) { return elementSet = new SortedMultisets.ElementSet<E>() { @Override SortedMultiset<E> multiset() { return DescendingMultiset.this; } }; } return result; } @Override public Entry<E> pollFirstEntry() { return forwardMultiset().pollLastEntry(); } @Override public Entry<E> pollLastEntry() { return forwardMultiset().pollFirstEntry(); } @Override public SortedMultiset<E> headMultiset(E toElement, BoundType boundType) { return forwardMultiset().tailMultiset(toElement, boundType) .descendingMultiset(); } @Override public SortedMultiset<E> subMultiset(E fromElement, BoundType fromBoundType, E toElement, BoundType toBoundType) { return forwardMultiset().subMultiset(toElement, toBoundType, fromElement, fromBoundType).descendingMultiset(); } @Override public SortedMultiset<E> tailMultiset(E fromElement, BoundType boundType) { return forwardMultiset().headMultiset(fromElement, boundType) .descendingMultiset(); } @Override protected Multiset<E> delegate() { return forwardMultiset(); } @Override public SortedMultiset<E> descendingMultiset() { return forwardMultiset(); } @Override public Entry<E> firstEntry() { return forwardMultiset().lastEntry(); } @Override public Entry<E> lastEntry() { return forwardMultiset().firstEntry(); } abstract Iterator<Entry<E>> entryIterator(); private transient Set<Entry<E>> entrySet; @Override public Set<Entry<E>> entrySet() { Set<Entry<E>> result = entrySet; return (result == null) ? entrySet = createEntrySet() : result; } Set<Entry<E>> createEntrySet() { return new Multisets.EntrySet<E>() { @Override Multiset<E> multiset() { return DescendingMultiset.this; } @Override public Iterator<Entry<E>> iterator() { return entryIterator(); } @Override public int size() { return forwardMultiset().entrySet().size(); } }; } @Override public Iterator<E> iterator() { return Multisets.iteratorImpl(this); } @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } @Override public String toString() { return entrySet().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.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. * * <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>Though the method signature doesn't say so explicitly, the returned map * has {@link SortedSet} values. */ @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) 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 static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.AbstractCollection; import java.util.AbstractMap; 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.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 AbstractMultimap} 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 abstract class AbstractMultimap<K, V> implements Multimap<K, V>, 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 AbstractMultimap(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 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 isEmpty() { return totalSize == 0; } @Override public boolean containsKey(@Nullable Object key) { return map.containsKey(key); } @Override public boolean containsValue(@Nullable Object value) { for (Collection<V> collection : map.values()) { if (collection.contains(value)) { return true; } } return false; } @Override public boolean containsEntry(@Nullable Object key, @Nullable Object value) { Collection<V> collection = map.get(key); return collection != null && collection.contains(value); } // Modification Operations @Override public boolean put(@Nullable K key, @Nullable V value) { Collection<V> collection = getOrCreateCollection(key); 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; } @Override public boolean remove(@Nullable Object key, @Nullable Object value) { Collection<V> collection = map.get(key); if (collection == null) { return false; } boolean changed = collection.remove(value); if (changed) { totalSize--; if (collection.isEmpty()) { map.remove(key); } } return changed; } // Bulk Operations @Override public boolean putAll(@Nullable K key, Iterable<? extends V> values) { if (!values.iterator().hasNext()) { return false; } Collection<V> collection = getOrCreateCollection(key); int oldSize = collection.size(); boolean changed = false; if (values instanceof Collection) { Collection<? extends V> c = Collections2.cast(values); changed = collection.addAll(c); } else { for (V value : values) { changed |= collection.add(value); } } totalSize += (collection.size() - oldSize); return changed; } @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; } /** * {@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); } 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); Collection<V> output = createCollection(); if (collection != null) { output.addAll(collection); totalSize -= collection.size(); collection.clear(); } return unmodifiableCollectionSubclass(output); } private Collection<V> unmodifiableCollectionSubclass( Collection<V> collection) { 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. */ private Collection<V> wrapCollection( @Nullable K key, Collection<V> collection) { 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 * AbstractMultimap#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 AbstractMultimap.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); } } /** * 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()); } } /** 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); } } private transient Set<K> keySet; @Override public Set<K> keySet() { Set<K> result = keySet; return (result == null) ? keySet = createKeySet() : result; } private Set<K> createKeySet() { return (map instanceof SortedMap) ? new SortedKeySet((SortedMap<K, Collection<V>>) map) : new KeySet(map); } private class KeySet extends Maps.KeySet<K, Collection<V>> { /** * This is usually the same as map, except when someone requests a * subcollection of a {@link SortedKeySet}. */ final Map<K, Collection<V>> subMap; KeySet(final Map<K, Collection<V>> subMap) { this.subMap = subMap; } @Override Map<K, Collection<V>> map() { return subMap; } @Override public Iterator<K> iterator() { return new Iterator<K>() { final Iterator<Map.Entry<K, Collection<V>>> entryIterator = subMap.entrySet().iterator(); 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() { checkState(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 = subMap.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 subMap.keySet().containsAll(c); } @Override public boolean equals(@Nullable Object object) { return this == object || this.subMap.keySet().equals(object); } @Override public int hashCode() { return subMap.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>>) subMap; } @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)); } } private transient Multiset<K> multiset; @Override public Multiset<K> keys() { Multiset<K> result = multiset; if (result == null) { return multiset = new Multimaps.Keys<K, V>() { @Override Multimap<K, V> multimap() { return AbstractMultimap.this; } }; } return result; } /** * 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; try { collection = map.remove(key); } catch (NullPointerException e) { return 0; } catch (ClassCastException e) { return 0; } int count = 0; if (collection != null) { count = collection.size(); collection.clear(); totalSize -= count; } return count; } private transient Collection<V> valuesCollection; /** * {@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() { Collection<V> result = valuesCollection; if (result == null) { return valuesCollection = new Multimaps.Values<K, V>() { @Override Multimap<K, V> multimap() { return AbstractMultimap.this; } }; } return result; } private transient Collection<Map.Entry<K, V>> entries; /* * 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() { Collection<Map.Entry<K, V>> result = entries; return (result == null) ? entries = createEntries() : result; } Collection<Map.Entry<K, V>> createEntries() { if (this instanceof SetMultimap) { return new Multimaps.EntrySet<K, V>() { @Override Multimap<K, V> multimap() { return AbstractMultimap.this; } @Override public Iterator<Entry<K, V>> iterator() { return createEntryIterator(); } }; } return new Multimaps.Entries<K, V>() { @Override Multimap<K, V> multimap() { return AbstractMultimap.this; } @Override public Iterator<Entry<K, V>> iterator() { return createEntryIterator(); } }; } /** * 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 AbstractMultimap} implementations. * * @return an iterator across map entries */ Iterator<Map.Entry<K, V>> createEntryIterator() { return new EntryIterator(); } /** Iterator across all key-value pairs. */ private class EntryIterator implements Iterator<Map.Entry<K, V>> { final Iterator<Map.Entry<K, Collection<V>>> keyIterator; K key; Collection<V> collection; Iterator<V> valueIterator; EntryIterator() { keyIterator = map.entrySet().iterator(); if (keyIterator.hasNext()) { findValueIteratorAndKey(); } else { valueIterator = Iterators.emptyModifiableIterator(); } } void findValueIteratorAndKey() { Map.Entry<K, Collection<V>> entry = keyIterator.next(); key = entry.getKey(); collection = entry.getValue(); valueIterator = collection.iterator(); } @Override public boolean hasNext() { return keyIterator.hasNext() || valueIterator.hasNext(); } @Override public Map.Entry<K, V> next() { if (!valueIterator.hasNext()) { findValueIteratorAndKey(); } return Maps.immutableEntry(key, valueIterator.next()); } @Override public void remove() { valueIterator.remove(); if (collection.isEmpty()) { keyIterator.remove(); } totalSize--; } } 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; } private Map<K, Collection<V>> createAsMap() { return (map instanceof SortedMap) ? new SortedAsMap((SortedMap<K, Collection<V>>) map) : new AsMap(map); } private class AsMap extends AbstractMap<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; } transient Set<Map.Entry<K, Collection<V>>> entrySet; @Override public Set<Map.Entry<K, Collection<V>>> entrySet() { Set<Map.Entry<K, Collection<V>>> result = entrySet; return (result == null) ? entrySet = new AsMapEntries() : result; } // 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 AbstractMultimap.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) { AbstractMultimap.this.clear(); } else { Iterators.clear(new AsMapIterator()); } } 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(); K key = entry.getKey(); collection = entry.getValue(); return Maps.immutableEntry(key, wrapCollection(key, collection)); } @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 = new SortedKeySet(sortedMap()) : result; } } // Comparison and hashing @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof Multimap) { Multimap<?, ?> that = (Multimap<?, ?>) object; return this.map.equals(that.asMap()); } return false; } /** * 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 map.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 map.toString(); } private static final long serialVersionUID = 2447537837011683357L; }
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) 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.GwtCompatible; import java.util.List; import javax.annotation.Nullable; /** * A transforming wrapper around an ImmutableList. For internal use only. {@link * #transform(Object)} must be functional. * * @author Louis Wasserman */ @GwtCompatible @SuppressWarnings("serial") // uses writeReplace(), not default serialization abstract class TransformedImmutableList<D, E> extends ImmutableList<E> { private class TransformedView extends TransformedImmutableList<D, E> { TransformedView(ImmutableList<D> backingList) { super(backingList); } @Override E transform(D d) { return TransformedImmutableList.this.transform(d); } } private transient final ImmutableList<D> backingList; TransformedImmutableList(ImmutableList<D> backingList) { this.backingList = checkNotNull(backingList); } abstract E transform(D d); @Override public int indexOf(@Nullable Object object) { if (object == null) { return -1; } for (int i = 0; i < size(); i++) { if (get(i).equals(object)) { return i; } } return -1; } @Override public int lastIndexOf(@Nullable Object object) { if (object == null) { return -1; } for (int i = size() - 1; i >= 0; i--) { if (get(i).equals(object)) { return i; } } return -1; } @Override public E get(int index) { return transform(backingList.get(index)); } @Override public UnmodifiableListIterator<E> listIterator(int index) { return new AbstractIndexedListIterator<E>(size(), index) { @Override protected E get(int index) { return TransformedImmutableList.this.get(index); } }; } @Override public int size() { return backingList.size(); } @Override public ImmutableList<E> subList(int fromIndex, int toIndex) { return new TransformedView(backingList.subList(fromIndex, toIndex)); } @Override public boolean equals(@Nullable Object obj) { if (obj == this) { return true; } if (obj instanceof List) { List<?> list = (List<?>) obj; return size() == list.size() && Iterators.elementsEqual(iterator(), list.iterator()); } return false; } @Override public int hashCode() { int hashCode = 1; for (E e : this) { hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode()); } return hashCode; } @Override public Object[] toArray() { return ObjectArrays.toArrayImpl(this); } @Override public <T> T[] toArray(T[] array) { return ObjectArrays.toArrayImpl(this, array); } @Override boolean isPartialView() { 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.checkState; 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; import javax.annotation.Nullable; /** * 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 */ @Beta 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 poll(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 poll(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() { checkState( toRemove != null, "Each call to remove() must be preceded by a call to next()"); 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() {} @Override NavigableMap<K, V> map() { return 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. */ 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); } @Nullable private static <T> T poll(Iterator<T> iterator) { if (iterator.hasNext()) { T result = iterator.next(); iterator.remove(); return result; } 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.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.collect.Multiset.Entry; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Set; 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) { SortedSet<?> sortedSet = (SortedSet<?>) elements; comparator2 = sortedSet.comparator(); if (comparator2 == null) { comparator2 = (Comparator) Ordering.natural(); } } else if (elements instanceof SortedIterable) { comparator2 = ((SortedIterable<?>) elements).comparator(); } else { comparator2 = null; } return comparator.equals(comparator2); } /** * Returns a sorted collection of the unique elements according to the specified comparator. Does * not check for null. */ @SuppressWarnings("unchecked") public static <E> Collection<E> sortedUnique( Comparator<? super E> comparator, Iterator<E> elements) { SortedSet<E> sortedSet = Sets.newTreeSet(comparator); Iterators.addAll(sortedSet, elements); return sortedSet; } /** * Returns a sorted collection of the unique elements according to the specified comparator. Does * not check for null. */ @SuppressWarnings("unchecked") public static <E> Collection<E> sortedUnique( Comparator<? super E> comparator, Iterable<E> elements) { if (elements instanceof Multiset) { elements = ((Multiset<E>) elements).elementSet(); } if (elements instanceof Set) { if (hasSameComparator(comparator, elements)) { return (Set<E>) elements; } List<E> list = Lists.newArrayList(elements); Collections.sort(list, comparator); return list; } E[] array = (E[]) Iterables.toArray(elements); if (!hasSameComparator(comparator, elements)) { Arrays.sort(array, comparator); } return uniquifySortedArray(comparator, array); } private static <E> Collection<E> uniquifySortedArray( Comparator<? super E> comparator, E[] array) { if (array.length == 0) { return Collections.emptySet(); } int length = 1; for (int i = 1; i < array.length; i++) { int cmp = comparator.compare(array[i], array[length - 1]); if (cmp != 0) { array[length++] = array[i]; } } if (length < array.length) { array = ObjectArrays.arraysCopyOf(array, length); } return Arrays.asList(array); } /** * Returns a collection of multiset entries representing the counts of the distinct elements, in * sorted order. Does not check for null. */ public static <E> Collection<Multiset.Entry<E>> sortedCounts( Comparator<? super E> comparator, Iterator<E> elements) { TreeMultiset<E> multiset = TreeMultiset.create(comparator); Iterators.addAll(multiset, elements); return multiset.entrySet(); } /** * Returns a collection of multiset entries representing the counts of the distinct elements, in * sorted order. Does not check for null. */ public static <E> Collection<Multiset.Entry<E>> sortedCounts( Comparator<? super E> comparator, Iterable<E> elements) { if (elements instanceof Multiset) { Multiset<E> multiset = (Multiset<E>) elements; if (hasSameComparator(comparator, elements)) { return multiset.entrySet(); } List<Multiset.Entry<E>> entries = Lists.newArrayList(multiset.entrySet()); Collections.sort( entries, Ordering.from(comparator).onResultOf(new Function<Multiset.Entry<E>, E>() { @Override public E apply(Entry<E> entry) { return entry.getElement(); } })); return entries; } else if (elements instanceof Set) { // known distinct Collection<E> sortedElements; if (hasSameComparator(comparator, elements)) { sortedElements = (Collection<E>) elements; } else { List<E> list = Lists.newArrayList(elements); Collections.sort(list, comparator); sortedElements = list; } return singletonEntries(sortedElements); } else if (hasSameComparator(comparator, elements)) { E current = null; int currentCount = 0; List<Multiset.Entry<E>> sortedEntries = Lists.newArrayList(); for (E e : elements) { if (currentCount > 0) { if (comparator.compare(current, e) == 0) { currentCount++; } else { sortedEntries.add(Multisets.immutableEntry(current, currentCount)); current = e; currentCount = 1; } } else { current = e; currentCount = 1; } } if (currentCount > 0) { sortedEntries.add(Multisets.immutableEntry(current, currentCount)); } return sortedEntries; } TreeMultiset<E> multiset = TreeMultiset.create(comparator); Iterables.addAll(multiset, elements); return multiset.entrySet(); } static <E> Collection<Multiset.Entry<E>> singletonEntries(Collection<E> set) { return Collections2.transform(set, new Function<E, Multiset.Entry<E>>() { @Override public Entry<E> apply(E elem) { return Multisets.immutableEntry(elem, 1); } }); } }
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.Beta; import com.google.common.annotations.GwtCompatible; import java.util.Iterator; import java.util.NoSuchElementException; /** * Static methods pertaining to {@link Range} instances. Each of the * {@link Range nine types of ranges} can be constructed with a corresponding * factory method: * * <dl> * <dt>{@code (a..b)} * <dd>{@link #open} * <dt>{@code [a..b]} * <dd>{@link #closed} * <dt>{@code [a..b)} * <dd>{@link #closedOpen} * <dt>{@code (a..b]} * <dd>{@link #openClosed} * <dt>{@code (a..+∞)} * <dd>{@link #greaterThan} * <dt>{@code [a..+∞)} * <dd>{@link #atLeast} * <dt>{@code (-∞..b)} * <dd>{@link #lessThan} * <dt>{@code (-∞..b]} * <dd>{@link #atMost} * <dt>{@code (-∞..+∞)} * <dd>{@link #all} * </dl> * * <p>Additionally, {@link Range} instances can be constructed by passing the * {@link BoundType bound types} explicitly. * * <dl> * <dt>Bounded on both ends * <dd>{@link #range} * <dt>Unbounded on top ({@code (a..+∞)} or {@code (a..+∞)}) * <dd>{@link #downTo} * <dt>Unbounded on bottom ({@code (-∞..b)} or {@code (-∞..b]}) * <dd>{@link #upTo} * </dl> * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/RangesExplained"> * {@code Range}</a>. * * @author Kevin Bourrillion * @author Gregory Kick * @since 10.0 */ @GwtCompatible @Beta public final class Ranges { private Ranges() {} static <C extends Comparable<?>> Range<C> create( Cut<C> lowerBound, Cut<C> upperBound) { return new Range<C>(lowerBound, upperBound); } /** * Returns a range that contains all values strictly greater than {@code * lower} and strictly less than {@code upper}. * * @throws IllegalArgumentException if {@code lower} is greater than <i>or * equal to</i> {@code upper} */ public static <C extends Comparable<?>> Range<C> open(C lower, C upper) { return create(Cut.aboveValue(lower), Cut.belowValue(upper)); } /** * Returns a range that contains all values greater than or equal to * {@code lower} and less than or equal to {@code upper}. * * @throws IllegalArgumentException if {@code lower} is greater than {@code * upper} */ public static <C extends Comparable<?>> Range<C> closed(C lower, C upper) { return create(Cut.belowValue(lower), Cut.aboveValue(upper)); } /** * Returns a range that contains all values greater than or equal to * {@code lower} and strictly less than {@code upper}. * * @throws IllegalArgumentException if {@code lower} is greater than {@code * upper} */ public static <C extends Comparable<?>> Range<C> closedOpen( C lower, C upper) { return create(Cut.belowValue(lower), Cut.belowValue(upper)); } /** * Returns a range that contains all values strictly greater than {@code * lower} and less than or equal to {@code upper}. * * @throws IllegalArgumentException if {@code lower} is greater than {@code * upper} */ public static <C extends Comparable<?>> Range<C> openClosed( C lower, C upper) { return create(Cut.aboveValue(lower), Cut.aboveValue(upper)); } /** * Returns a range that contains any value from {@code lower} to {@code * upper}, where each endpoint may be either inclusive (closed) or exclusive * (open). * * @throws IllegalArgumentException if {@code lower} is greater than {@code * upper} */ public static <C extends Comparable<?>> Range<C> range( C lower, BoundType lowerType, C upper, BoundType upperType) { checkNotNull(lowerType); checkNotNull(upperType); Cut<C> lowerBound = (lowerType == BoundType.OPEN) ? Cut.aboveValue(lower) : Cut.belowValue(lower); Cut<C> upperBound = (upperType == BoundType.OPEN) ? Cut.belowValue(upper) : Cut.aboveValue(upper); return create(lowerBound, upperBound); } /** * Returns a range that contains all values strictly less than {@code * endpoint}. */ public static <C extends Comparable<?>> Range<C> lessThan(C endpoint) { return create(Cut.<C>belowAll(), Cut.belowValue(endpoint)); } /** * Returns a range that contains all values less than or equal to * {@code endpoint}. */ public static <C extends Comparable<?>> Range<C> atMost(C endpoint) { return create(Cut.<C>belowAll(), Cut.aboveValue(endpoint)); } /** * Returns a range with no lower bound up to the given endpoint, which may be * either inclusive (closed) or exclusive (open). */ public static <C extends Comparable<?>> Range<C> upTo( C endpoint, BoundType boundType) { switch (boundType) { case OPEN: return lessThan(endpoint); case CLOSED: return atMost(endpoint); default: throw new AssertionError(); } } /** * Returns a range that contains all values strictly greater than {@code * endpoint}. */ public static <C extends Comparable<?>> Range<C> greaterThan(C endpoint) { return create(Cut.aboveValue(endpoint), Cut.<C>aboveAll()); } /** * Returns a range that contains all values greater than or equal to * {@code endpoint}. */ public static <C extends Comparable<?>> Range<C> atLeast(C endpoint) { return create(Cut.belowValue(endpoint), Cut.<C>aboveAll()); } /** * Returns a range from the given endpoint, which may be either inclusive * (closed) or exclusive (open), with no upper bound. */ public static <C extends Comparable<?>> Range<C> downTo( C endpoint, BoundType boundType) { switch (boundType) { case OPEN: return greaterThan(endpoint); case CLOSED: return atLeast(endpoint); default: throw new AssertionError(); } } /** Returns a range that contains every value of type {@code C}. */ public static <C extends Comparable<?>> Range<C> all() { return create(Cut.<C>belowAll(), Cut.<C>aboveAll()); } /** * Returns a range that {@linkplain Range#contains(Comparable) contains} only * the given value. The returned range is {@linkplain BoundType#CLOSED closed} * on both ends. */ public static <C extends Comparable<?>> Range<C> singleton(C value) { return closed(value, value); } /** * Returns the minimal range that * {@linkplain Range#contains(Comparable) contains} all of the given values. * The returned range is {@linkplain BoundType#CLOSED closed} on both ends. * * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> * @throws NoSuchElementException if {@code values} is empty * @throws NullPointerException if any of {@code values} is null */ public static <C extends Comparable<?>> Range<C> encloseAll( Iterable<C> values) { checkNotNull(values); if (values instanceof ContiguousSet) { return ((ContiguousSet<C>) values).range(); } Iterator<C> valueIterator = values.iterator(); C min = checkNotNull(valueIterator.next()); C max = min; while (valueIterator.hasNext()) { C value = checkNotNull(valueIterator.next()); min = Ordering.natural().min(min, value); max = Ordering.natural().max(max, value); } return closed(min, max); } }
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 reverse of the natural order 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.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.primitives.Ints; import java.io.Serializable; 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 javax.annotation.Nullable; /** * Static utility methods pertaining to {@link List} instances. Also see this * class's counterparts {@link Sets} and {@link Maps}. * * <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 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) { checkNotNull(elements); // for GWT ArrayList<E> list = newArrayList(); while (elements.hasNext()) { list.add(elements.next()); } 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(); for (E element : elements) { list.add(element); } return list; } /** * 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 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 always implements {@link Serializable}, * but serialization will succeed only when {@code fromList} and * {@code function} are serializable. 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}. */ 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) { final ListIterator<F> delegate = fromList.listIterator(index); return new ListIterator<T>() { @Override public void add(T e) { throw new UnsupportedOperationException(); } @Override public boolean hasNext() { return delegate.hasNext(); } @Override public boolean hasPrevious() { return delegate.hasPrevious(); } @Override public T next() { return function.apply(delegate.next()); } @Override public int nextIndex() { return delegate.nextIndex(); } @Override public T previous() { return function.apply(delegate.previous()); } @Override public int previousIndex() { return delegate.previousIndex(); } @Override public void remove() { delegate.remove(); } @Override public void set(T e) { throw new UnsupportedOperationException("not supported"); } }; } 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) { int listSize = size(); checkElementIndex(index, listSize); int start = index * size; int end = Math.min(start + size, list.size()); return list.subList(start, end); } @Override public int size() { // TODO(user): refactor to common.math.IntMath.divide int result = list.size() / size; if (result * size != list.size()) { result++; } return result; } @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 boolean contains(@Nullable Object object) { return indexOf(object) >= 0; } @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 UnmodifiableListIterator<Character> listIterator( int index) { return new AbstractIndexedListIterator<Character>(size(), index) { @Override protected Character get(int index) { return string.charAt(index); } }; } @Override public ImmutableList<Character> subList( int fromIndex, int toIndex) { return charactersOf(string.substring(fromIndex, toIndex)); } @Override boolean isPartialView() { return false; } @Override public Character get(int index) { return string.charAt(index); } @Override public int size() { return string.length(); } @Override public boolean equals(@Nullable Object obj) { if (!(obj instanceof List)) { return false; } List<?> list = (List<?>) obj; int n = string.length(); if (n != list.size()) { return false; } Iterator<?> iterator = list.iterator(); for (int i = 0; i < n; i++) { Object elem = iterator.next(); if (!(elem instanceof Character) || ((Character) elem).charValue() != string.charAt(i)) { return false; } } return true; } int hash = 0; @Override public int hashCode() { int h = hash; if (h == 0) { h = 1; for (int i = 0; i < string.length(); i++) { h = h * 31 + string.charAt(i); } hash = h; } return h; } } /** * 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) { return sequence.charAt(index); } @Override public boolean contains(@Nullable Object o) { return indexOf(o) >= 0; } @Override public int indexOf(@Nullable Object o) { if (o instanceof Character) { char c = (Character) o; for (int i = 0; i < sequence.length(); i++) { if (sequence.charAt(i) == c) { return i; } } } return -1; } @Override public int lastIndexOf(@Nullable Object o) { if (o instanceof Character) { char c = ((Character) o).charValue(); for (int i = sequence.length() - 1; i >= 0; i--) { if (sequence.charAt(i) == c) { return i; } } } return -1; } @Override public int size() { return sequence.length(); } @Override public List<Character> subList(int fromIndex, int toIndex) { return charactersOf(sequence.subSequence(fromIndex, toIndex)); } @Override public int hashCode() { int hash = 1; for (int i = 0; i < sequence.length(); i++) { hash = hash * 31 + sequence.charAt(i); } return hash; } @Override public boolean equals(@Nullable Object o) { if (!(o instanceof List)) { return false; } List<?> list = (List<?>) o; int n = sequence.length(); if (n != list.size()) { return false; } Iterator<?> iterator = list.iterator(); for (int i = 0; i < n; i++) { Object elem = iterator.next(); if (!(elem instanceof Character) || ((Character) elem).charValue() != sequence.charAt(i)) { return false; } } return true; } } /** * 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 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 boolean isEmpty() { return forwardList.isEmpty(); } @Override public int size() { return forwardList.size(); } @Override public boolean contains(@Nullable Object o) { return forwardList.contains(o); } @Override public boolean containsAll(Collection<?> c) { return forwardList.containsAll(c); } @Override public List<T> subList(int fromIndex, int toIndex) { checkPositionIndexes(fromIndex, toIndex, size()); return reverse(forwardList.subList( reversePosition(toIndex), reversePosition(fromIndex))); } @Override public int indexOf(@Nullable Object o) { int index = forwardList.lastIndexOf(o); return (index >= 0) ? reverseIndex(index) : -1; } @Override public int lastIndexOf(@Nullable Object o) { int index = forwardList.indexOf(o); return (index >= 0) ? reverseIndex(index) : -1; } @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 canRemove; boolean canSet; @Override public void add(T e) { forwardIterator.add(e); forwardIterator.previous(); canSet = canRemove = false; } @Override public boolean hasNext() { return forwardIterator.hasPrevious(); } @Override public boolean hasPrevious() { return forwardIterator.hasNext(); } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } canSet = canRemove = true; return forwardIterator.previous(); } @Override public int nextIndex() { return reversePosition(forwardIterator.nextIndex()); } @Override public T previous() { if (!hasPrevious()) { throw new NoSuchElementException(); } canSet = canRemove = true; return forwardIterator.next(); } @Override public int previousIndex() { return nextIndex() - 1; } @Override public void remove() { checkState(canRemove); forwardIterator.remove(); canRemove = canSet = false; } @Override public void set(T e) { checkState(canSet); 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){ int hashCode = 1; for (Object o : list) { hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode()); } 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); } } }
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; } 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.Collections2.TransformedCollection; import com.google.common.collect.Table.Cell; import java.io.Serializable; import java.util.Collection; import java.util.Collections; 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 @Beta 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> implements Table<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 boolean isEmpty() { return original.isEmpty(); } @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(); } @Override public boolean equals(@Nullable Object obj) { if (obj == this) { return true; } if (obj instanceof Table) { Table<?, ?, ?> other = (Table<?, ?, ?>) obj; return cellSet().equals(other.cellSet()); } return false; } @Override public int hashCode() { return cellSet().hashCode(); } @Override public String toString() { return rowMap().toString(); } // 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()); } }; CellSet cellSet; @Override public Set<Cell<C, R, V>> cellSet() { CellSet result = cellSet; return (result == null) ? cellSet = new CellSet() : result; } class CellSet extends TransformedCollection<Cell<R, C, V>, Cell<C, R, V>> implements Set<Cell<C, R, V>> { // Casting TRANSPOSE_CELL to a type that always succeeds @SuppressWarnings("unchecked") CellSet() { super(original.cellSet(), (Function) TRANSPOSE_CELL); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof Set)) { return false; } Set<?> os = (Set<?>) obj; if (os.size() != size()) { return false; } return containsAll(os); } @Override public int hashCode() { return Sets.hashCodeImpl(this); } @Override public boolean contains(Object obj) { if (obj instanceof Cell) { Cell<?, ?, ?> cell = (Cell<?, ?, ?>) obj; return original.cellSet().contains(immutableCell( cell.getColumnKey(), cell.getRowKey(), cell.getValue())); } return false; } @Override public boolean remove(Object obj) { if (obj instanceof Cell) { Cell<?, ?, ?> cell = (Cell<?, ?, ?>) obj; return original.cellSet().remove(immutableCell( cell.getColumnKey(), cell.getRowKey(), cell.getValue())); } return false; } } } /** * 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 */ 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 */ 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> implements Table<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 boolean containsRow(Object rowKey) { return fromTable.containsRow(rowKey); } @Override public boolean containsColumn(Object columnKey) { return fromTable.containsColumn(columnKey); } @Override public boolean containsValue(Object value) { return values().contains(value); } @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 boolean isEmpty() { return fromTable.isEmpty(); } @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())); } }; } class CellSet extends TransformedCollection<Cell<R, C, V1>, Cell<R, C, V2>> implements Set<Cell<R, C, V2>> { CellSet() { super(fromTable.cellSet(), cellFunction()); } @Override public boolean equals(Object obj) { return Sets.equalsImpl(this, obj); } @Override public int hashCode() { return Sets.hashCodeImpl(this); } @Override public boolean contains(Object obj) { if (obj instanceof Cell) { Cell<?, ?, ?> cell = (Cell<?, ?, ?>) obj; if (!Objects.equal( cell.getValue(), get(cell.getRowKey(), cell.getColumnKey()))) { return false; } return cell.getValue() != null || fromTable.contains(cell.getRowKey(), cell.getColumnKey()); } return false; } @Override public boolean remove(Object obj) { if (contains(obj)) { Cell<?, ?, ?> cell = (Cell<?, ?, ?>) obj; fromTable.remove(cell.getRowKey(), cell.getColumnKey()); return true; } return false; } } CellSet cellSet; @Override public Set<Cell<R, C, V2>> cellSet() { return (cellSet == null) ? cellSet = new CellSet() : cellSet; } @Override public Set<R> rowKeySet() { return fromTable.rowKeySet(); } @Override public Set<C> columnKeySet() { return fromTable.columnKeySet(); } Collection<V2> values; @Override public Collection<V2> values() { return (values == null) ? values = Collections2.transform(fromTable.values(), function) : values; } Map<R, Map<C, V2>> createRowMap() { 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); } Map<R, Map<C, V2>> rowMap; @Override public Map<R, Map<C, V2>> rowMap() { return (rowMap == null) ? rowMap = createRowMap() : rowMap; } Map<C, Map<R, V2>> createColumnMap() { 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); } Map<C, Map<R, V2>> columnMap; @Override public Map<C, Map<R, V2>> columnMap() { return (columnMap == null) ? columnMap = createColumnMap() : columnMap; } @Override public boolean equals(@Nullable Object obj) { if (obj == this) { return true; } if (obj instanceof Table) { Table<?, ?, ?> other = (Table<?, ?, ?>) obj; return cellSet().equals(other.cellSet()); } return false; } @Override public int hashCode() { return cellSet().hashCode(); } @Override public String toString() { return rowMap().toString(); } } /** * 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 */ 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); } }; }
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> * * 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) 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(Object key) { return delegate().containsKey(key); } @Override public boolean containsValue(Object value) { return delegate().containsValue(value); } @Override public V get(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 */ @Beta 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 */ @Beta protected void standardClear() { Iterator<Entry<K, V>> entryIterator = entrySet().iterator(); while (entryIterator.hasNext()) { entryIterator.next(); entryIterator.remove(); } } /** * 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() {} @Override Map<K, V> map() { return 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() {} @Override Map<K, V> map() { return 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 */ @Beta 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 */ @Beta 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 */ @Beta 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 */ @Beta 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 */ @Beta protected String standardToString() { return Maps.toStringImpl(this); } }
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.base.Preconditions; 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 */ @SuppressWarnings("serial") final class ImmutableSortedAsList<E> extends ImmutableList<E> implements SortedIterable<E> { private final transient ImmutableSortedSet<E> backingSet; private final transient ImmutableList<E> backingList; ImmutableSortedAsList( ImmutableSortedSet<E> backingSet, ImmutableList<E> backingList) { this.backingSet = backingSet; this.backingList = backingList; } @Override public Comparator<? super E> comparator() { return backingSet.comparator(); } // Override contains(), indexOf(), and lastIndexOf() to be O(log N) instead of O(N). @Override public boolean contains(@Nullable Object target) { // TODO: why not contains(target)? return backingSet.indexOf(target) >= 0; } @Override public int indexOf(@Nullable Object target) { return backingSet.indexOf(target); } @Override public int lastIndexOf(@Nullable Object target) { return backingSet.indexOf(target); } // The returned ImmutableSortedAsList maintains the contains(), indexOf(), and // lastIndexOf() performance benefits. @Override public ImmutableList<E> subList(int fromIndex, int toIndex) { Preconditions.checkPositionIndexes(fromIndex, toIndex, size()); return (fromIndex == toIndex) ? ImmutableList.<E>of() : new RegularImmutableSortedSet<E>( backingList.subList(fromIndex, toIndex), backingSet.comparator()) .asList(); } // The ImmutableAsList serialized form has the correct behavior. @Override Object writeReplace() { return new ImmutableAsList.SerializedForm(backingSet); } @Override public UnmodifiableIterator<E> iterator() { return backingList.iterator(); } @Override public E get(int index) { return backingList.get(index); } @Override public UnmodifiableListIterator<E> listIterator() { return backingList.listIterator(); } @Override public UnmodifiableListIterator<E> listIterator(int index) { return backingList.listIterator(index); } @Override public int size() { return backingList.size(); } @Override public boolean equals(@Nullable Object obj) { return backingList.equals(obj); } @Override public int hashCode() { return backingList.hashCode(); } @Override boolean isPartialView() { return backingList.isPartialView(); } }
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(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(E element, int occurrences) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object element) { return remove(element, 1) > 0; } @Override public int remove(Object element, int occurrences) { throw new UnsupportedOperationException(); } @Override public int setCount(E element, int count) { return setCountImpl(this, element, count); } @Override public boolean setCount(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; } // Abstract method doesn't exist in GWT emulation /* @Override */ ContiguousSet<C> headSetImpl(C toElement, boolean inclusive) { return range.intersection(Ranges.upTo(toElement, BoundType.forBoolean(inclusive))) .asSet(domain); } // Abstract method doesn't exist in GWT emulation /* @Override */ int indexOf(Object target) { return contains(target) ? (int) domain.distance(first(), (C) target) : -1; } // Abstract method doesn't exist in GWT emulation /* @Override */ ContiguousSet<C> subSetImpl(C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) { return range.intersection(Ranges.range(fromElement, BoundType.forBoolean(fromInclusive), toElement, BoundType.forBoolean(toInclusive))).asSet(domain); } // Abstract method doesn't exist in GWT emulation /* @Override */ ContiguousSet<C> tailSetImpl(C fromElement, boolean inclusive) { return range.intersection(Ranges.downTo(fromElement, BoundType.forBoolean(inclusive))) .asSet(domain); } @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); } }; } 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(Object object) { try { return range.contains((C) object); } catch (ClassCastException e) { return false; } } @Override public boolean containsAll(Collection<?> targets) { try { return range.containsAll((Iterable<? extends C>) targets); } catch (ClassCastException e) { return false; } } @Override public boolean isEmpty() { return false; } // copied to make sure not to use the GWT-emulated version @Override public Object[] toArray() { return ObjectArrays.toArrayImpl(this); } // copied to make sure not to use the GWT-emulated version @Override public <T> T[] toArray(T[] other) { return ObjectArrays.toArrayImpl(this, other); } @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) ? Ranges.closed(lowerEndpoint, upperEndpoint).asSet(domain) : new EmptyContiguousSet<C>(domain); } } @Override public Range<C> range() { return range(CLOSED, CLOSED); } @Override public Range<C> range(BoundType lowerBoundType, BoundType upperBoundType) { return Ranges.create(range.lowerBound.withLowerBoundType(lowerBoundType, domain), range.upperBound.withUpperBoundType(upperBoundType, domain)); } @Override public boolean equals(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 Google Inc. * * 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.Map; import javax.annotation.Nullable; /** * An implementation of {@link ImmutableTable} that holds a single cell. * * @author gak@google.com (Gregory Kick) */ @GwtCompatible final class SingletonImmutableTable<R, C, V> extends ImmutableTable<R, C, V> { private final R singleRowKey; private final C singleColumnKey; private 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 ImmutableSet<Cell<R, C, V>> cellSet() { return ImmutableSet.of( Tables.immutableCell(singleRowKey, singleColumnKey, singleValue)); } @Override public ImmutableMap<R, V> column(C columnKey) { checkNotNull(columnKey); return containsColumn(columnKey) ? ImmutableMap.of(singleRowKey, singleValue) : ImmutableMap.<R, V>of(); } @Override public ImmutableSet<C> columnKeySet() { return ImmutableSet.of(singleColumnKey); } @Override public ImmutableMap<C, Map<R, V>> columnMap() { return ImmutableMap.of(singleColumnKey, (Map<R, V>) ImmutableMap.of(singleRowKey, singleValue)); } @Override public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) { return containsRow(rowKey) && containsColumn(columnKey); } @Override public boolean containsColumn(@Nullable Object columnKey) { return Objects.equal(this.singleColumnKey, columnKey); } @Override public boolean containsRow(@Nullable Object rowKey) { return Objects.equal(this.singleRowKey, rowKey); } @Override public boolean containsValue(@Nullable Object value) { return Objects.equal(this.singleValue, value); } @Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) { return contains(rowKey, columnKey) ? singleValue : null; } @Override public boolean isEmpty() { return false; } @Override public ImmutableMap<C, V> row(R rowKey) { checkNotNull(rowKey); return containsRow(rowKey) ? ImmutableMap.of(singleColumnKey, singleValue) : ImmutableMap.<C, V>of(); } @Override public ImmutableSet<R> rowKeySet() { return ImmutableSet.of(singleRowKey); } @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 public ImmutableCollection<V> values() { return ImmutableSet.of(singleValue); } @Override public boolean equals(@Nullable Object obj) { if (obj == this) { return true; } else if (obj instanceof Table<?, ?, ?>) { Table<?, ?, ?> that = (Table<?, ?, ?>) obj; if (that.size() == 1) { Cell<?, ?, ?> thatCell = that.cellSet().iterator().next(); return Objects.equal(this.singleRowKey, thatCell.getRowKey()) && Objects.equal(this.singleColumnKey, thatCell.getColumnKey()) && Objects.equal(this.singleValue, thatCell.getValue()); } } return false; } @Override public int hashCode() { return Objects.hashCode(singleRowKey, singleColumnKey, singleValue); } @Override public String toString() { return new StringBuilder() .append('{') .append(singleRowKey) .append("={") .append(singleColumnKey) .append('=') .append(singleValue) .append("}}") .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 java.util.Map; 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 SingletonImmutableMap<K, V> extends ImmutableMap<K, V> { final transient K singleKey; final transient V singleValue; private transient Entry<K, V> entry; SingletonImmutableMap(K singleKey, V singleValue) { this.singleKey = singleKey; this.singleValue = singleValue; } SingletonImmutableMap(Entry<K, V> entry) { this.entry = entry; this.singleKey = entry.getKey(); this.singleValue = entry.getValue(); } private Entry<K, V> entry() { Entry<K, V> e = entry; return (e == null) ? (entry = Maps.immutableEntry(singleKey, singleValue)) : e; } @Override public V get(@Nullable Object key) { return singleKey.equals(key) ? singleValue : null; } @Override public int size() { return 1; } @Override public boolean isEmpty() { return false; } @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; } private transient ImmutableSet<Entry<K, V>> entrySet; @Override public ImmutableSet<Entry<K, V>> entrySet() { ImmutableSet<Entry<K, V>> es = entrySet; return (es == null) ? (entrySet = ImmutableSet.of(entry())) : es; } private transient ImmutableSet<K> keySet; @Override public ImmutableSet<K> keySet() { ImmutableSet<K> ks = keySet; return (ks == null) ? (keySet = ImmutableSet.of(singleKey)) : ks; } private transient ImmutableCollection<V> values; @Override public ImmutableCollection<V> values() { ImmutableCollection<V> v = values; return (v == null) ? (values = new Values<V>(singleValue)) : v; } @SuppressWarnings("serial") // uses writeReplace(), not default serialization private static class Values<V> extends ImmutableCollection<V> { final V singleValue; Values(V singleValue) { this.singleValue = singleValue; } @Override public boolean contains(Object object) { return singleValue.equals(object); } @Override public boolean isEmpty() { return false; } @Override public int size() { return 1; } @Override public UnmodifiableIterator<V> iterator() { return Iterators.singletonIterator(singleValue); } @Override boolean isPartialView() { return true; } } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof Map) { Map<?, ?> that = (Map<?, ?>) object; if (that.size() != 1) { return false; } Entry<?, ?> entry = that.entrySet().iterator().next(); return singleKey.equals(entry.getKey()) && singleValue.equals(entry.getValue()); } return false; } @Override public int hashCode() { return singleKey.hashCode() ^ singleValue.hashCode(); } @Override public String toString() { return new StringBuilder() .append('{') .append(singleKey.toString()) .append('=') .append(singleValue.toString()) .append('}') .toString(); } }
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.base.Throwables; 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.io.Serializable; 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, 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, 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, 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(); } } } } /** * Overrides get() to compute on demand. Also throws an exception when {@code null} is returned * from a computation. */ static final class ComputingMapAdapter<K, V> extends ComputingConcurrentHashMap<K, V> implements Serializable { private static final long serialVersionUID = 0; ComputingMapAdapter(MapMaker mapMaker, Function<? super K, ? extends V> computingFunction) { super(mapMaker, computingFunction); } @SuppressWarnings("unchecked") // unsafe, which is one advantage of Cache over Map @Override public V get(Object key) { V value; try { value = getOrCompute((K) key); } catch (ExecutionException e) { Throwable cause = e.getCause(); Throwables.propagateIfInstanceOf(cause, ComputationException.class); throw new ComputationException(cause); } if (value == null) { throw new NullPointerException(computingFunction + " returned null for key " + key + "."); } return value; } } // 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 AbstractMultimap} 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 AbstractMultimap<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(); // 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(K key, 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(K key) { return key; } /** * Returns its input, or throws an exception if this is not a valid value. */ V checkValue(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(Object value) { return inverse.containsKey(value); } // Modification Operations @Override public V put(K key, V value) { return putInBothMaps(key, value, false); } @Override public V forcePut(K key, 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(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() { final Iterator<Entry<K, V>> iterator = delegate.entrySet().iterator(); return new Iterator<K>() { Entry<K, V> entry; @Override public boolean hasNext() { return iterator.hasNext(); } @Override public K next() { entry = iterator.next(); return entry.getKey(); } @Override public void remove() { checkState(entry != null); V value = entry.getValue(); iterator.remove(); removeFromInverseMap(value); } }; } } 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() { final Iterator<V> iterator = delegate.values().iterator(); return new Iterator<V>() { V valueToRemove; @Override public boolean hasNext() { return iterator.hasNext(); } @Override public V next() { return valueToRemove = iterator.next(); } @Override public void remove() { iterator.remove(); removeFromInverseMap(valueToRemove); } }; } @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
/* * 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 static com.google.common.collect.SortedLists.KeyAbsentBehavior.INVERTED_INSERTION_INDEX; import static com.google.common.collect.SortedLists.KeyAbsentBehavior.NEXT_HIGHER; import static com.google.common.collect.SortedLists.KeyAbsentBehavior.NEXT_LOWER; import static com.google.common.collect.SortedLists.KeyPresentBehavior.ANY_PRESENT; import com.google.common.primitives.Ints; import java.util.Comparator; import java.util.List; import javax.annotation.Nullable; /** * An immutable sorted multiset with one or more distinct elements. * * @author Louis Wasserman */ final class RegularImmutableSortedMultiset<E> extends ImmutableSortedMultiset<E> { private static final class CumulativeCountEntry<E> extends Multisets.AbstractEntry<E> { final E element; final int count; final long cumulativeCount; CumulativeCountEntry(E element, int count, @Nullable CumulativeCountEntry<E> previous) { this.element = element; this.count = count; this.cumulativeCount = count + ((previous == null) ? 0 : previous.cumulativeCount); } @Override public E getElement() { return element; } @Override public int getCount() { return count; } } static <E> RegularImmutableSortedMultiset<E> createFromSorted(Comparator<? super E> comparator, List<? extends Multiset.Entry<E>> entries) { List<CumulativeCountEntry<E>> newEntries = Lists.newArrayListWithCapacity(entries.size()); CumulativeCountEntry<E> previous = null; for (Multiset.Entry<E> entry : entries) { newEntries.add( previous = new CumulativeCountEntry<E>(entry.getElement(), entry.getCount(), previous)); } return new RegularImmutableSortedMultiset<E>(comparator, ImmutableList.copyOf(newEntries)); } final transient ImmutableList<CumulativeCountEntry<E>> entries; RegularImmutableSortedMultiset( Comparator<? super E> comparator, ImmutableList<CumulativeCountEntry<E>> entries) { super(comparator); this.entries = entries; assert !entries.isEmpty(); } ImmutableList<E> elementList() { return new TransformedImmutableList<CumulativeCountEntry<E>, E>(entries) { @Override E transform(CumulativeCountEntry<E> entry) { return entry.getElement(); } }; } @Override ImmutableSortedSet<E> createElementSet() { return new RegularImmutableSortedSet<E>(elementList(), comparator()); } @Override ImmutableSortedSet<E> createDescendingElementSet() { return new RegularImmutableSortedSet<E>(elementList().reverse(), reverseComparator()); } @SuppressWarnings("unchecked") @Override UnmodifiableIterator<Multiset.Entry<E>> entryIterator() { return (UnmodifiableIterator) entries.iterator(); } @SuppressWarnings("unchecked") @Override UnmodifiableIterator<Multiset.Entry<E>> descendingEntryIterator() { return (UnmodifiableIterator) entries.reverse().iterator(); } @Override public CumulativeCountEntry<E> firstEntry() { return entries.get(0); } @Override public CumulativeCountEntry<E> lastEntry() { return entries.get(entries.size() - 1); } @Override public int size() { CumulativeCountEntry<E> firstEntry = firstEntry(); CumulativeCountEntry<E> lastEntry = lastEntry(); return Ints.saturatedCast( lastEntry.cumulativeCount - firstEntry.cumulativeCount + firstEntry.count); } @Override int distinctElements() { return entries.size(); } @Override boolean isPartialView() { return entries.isPartialView(); } @SuppressWarnings("unchecked") @Override public int count(@Nullable Object element) { if (element == null) { return 0; } try { int index = SortedLists.binarySearch( elementList(), (E) element, comparator(), ANY_PRESENT, INVERTED_INSERTION_INDEX); return (index >= 0) ? entries.get(index).getCount() : 0; } catch (ClassCastException e) { return 0; } } @Override public ImmutableSortedMultiset<E> headMultiset(E upperBound, BoundType boundType) { int index; switch (boundType) { case OPEN: index = SortedLists.binarySearch( elementList(), checkNotNull(upperBound), comparator(), ANY_PRESENT, NEXT_HIGHER); break; case CLOSED: index = SortedLists.binarySearch( elementList(), checkNotNull(upperBound), comparator(), ANY_PRESENT, NEXT_LOWER) + 1; break; default: throw new AssertionError(); } return createSubMultiset(0, index); } @Override public ImmutableSortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) { int index; switch (boundType) { case OPEN: index = SortedLists.binarySearch( elementList(), checkNotNull(lowerBound), comparator(), ANY_PRESENT, NEXT_LOWER) + 1; break; case CLOSED: index = SortedLists.binarySearch( elementList(), checkNotNull(lowerBound), comparator(), ANY_PRESENT, NEXT_HIGHER); break; default: throw new AssertionError(); } return createSubMultiset(index, distinctElements()); } private ImmutableSortedMultiset<E> createSubMultiset(int newFromIndex, int newToIndex) { if (newFromIndex == 0 && newToIndex == entries.size()) { return this; } else if (newFromIndex >= newToIndex) { return emptyMultiset(comparator()); } else { return new RegularImmutableSortedMultiset<E>( comparator(), entries.subList(newFromIndex, newToIndex)); } } }
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.Beta; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.math.BigInteger; /** * Factories for common {@link DiscreteDomain} instances. * * <p>See the Guava User Guide section on <a href= * "http://code.google.com/p/guava-libraries/wiki/RangesExplained#Discrete_Domains"> * {@code DiscreteDomain}</a>. * * @author Gregory Kick * @since 10.0 */ @GwtCompatible @Beta public final class DiscreteDomains { private DiscreteDomains() {} /** * Returns the discrete domain for values of type {@code Integer}. */ public static DiscreteDomain<Integer> integers() { return IntegerDomain.INSTANCE; } private static final class IntegerDomain extends DiscreteDomain<Integer> implements Serializable { private static final IntegerDomain INSTANCE = new IntegerDomain(); @Override public Integer next(Integer value) { int i = value; return (i == Integer.MAX_VALUE) ? null : i + 1; } @Override public Integer previous(Integer value) { int i = value; return (i == Integer.MIN_VALUE) ? null : i - 1; } @Override public long distance(Integer start, Integer end) { return (long) end - start; } @Override public Integer minValue() { return Integer.MIN_VALUE; } @Override public Integer maxValue() { return Integer.MAX_VALUE; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 0; } /** * Returns the discrete domain for values of type {@code Long}. */ public static DiscreteDomain<Long> longs() { return LongDomain.INSTANCE; } private static final class LongDomain extends DiscreteDomain<Long> implements Serializable { private static final LongDomain INSTANCE = new LongDomain(); @Override public Long next(Long value) { long l = value; return (l == Long.MAX_VALUE) ? null : l + 1; } @Override public Long previous(Long value) { long l = value; return (l == Long.MIN_VALUE) ? null : l - 1; } @Override public long distance(Long start, Long end) { long result = end - start; if (end > start && result < 0) { // overflow return Long.MAX_VALUE; } if (end < start && result > 0) { // underflow return Long.MIN_VALUE; } return result; } @Override public Long minValue() { return Long.MIN_VALUE; } @Override public Long maxValue() { return Long.MAX_VALUE; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 0; } /** * Returns the discrete domain for values of type {@code BigInteger}. */ // TODO(kevinb): make sure it's tested, and make it public static DiscreteDomain<BigInteger> bigIntegers() { return BigIntegerDomain.INSTANCE; } private static final class BigIntegerDomain extends DiscreteDomain<BigInteger> implements Serializable { private static final BigIntegerDomain INSTANCE = new BigIntegerDomain(); private static final BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE); private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE); @Override public BigInteger next(BigInteger value) { return value.add(BigInteger.ONE); } @Override public BigInteger previous(BigInteger value) { return value.subtract(BigInteger.ONE); } @Override public long distance(BigInteger start, BigInteger end) { return start.subtract(end).max(MIN_LONG).min(MAX_LONG).longValue(); } private Object readResolve() { return INSTANCE; } 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; /** * Provides equivalent behavior to {@link String#intern} for other immutable * types. * * @author Kevin Bourrillion * @since 3.0 */ @Beta public interface Interner<E> { /** * Chooses and returns the representative instance for any of a collection of * instances that are equal to each other. If two {@linkplain Object#equals * equal} inputs are given to this method, both calls will return the same * instance. That is, {@code intern(a).equals(a)} always holds, and {@code * intern(a) == intern(b)} if and only if {@code a.equals(b)}. Note that * {@code intern(a)} is permitted to return one instance now and a different * instance later if the original interned instance was garbage-collected. * * <p><b>Warning:</b> do not use with mutable objects. * * @throws NullPointerException if {@code sample} is null */ E intern(E sample); }
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 java.util.Comparator; import java.util.Map; import java.util.Map.Entry; import java.util.SortedMap; import javax.annotation.Nullable; 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.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Maps.EntryTransformer; /** * Static utility methods pertaining to {@link SortedMap} instances. * * @author Louis Wasserman * @since 8.0 * @deprecated Use the identical methods in {@link Maps}. This class is * scheduled for deletion from Guava in Guava release 12.0. */ @Beta @Deprecated @GwtCompatible public final class SortedMaps { private SortedMaps() {} /** * Returns a view of a sorted map where each value is transformed by a * function. All other properties of the map, such as iteration order, are * left intact. For example, the code: <pre> {@code * * SortedMap<String, Integer> map = ImmutableSortedMap.of("a", 4, "b", 9); * Function<Integer, Double> sqrt = * new Function<Integer, Double>() { * public Double apply(Integer in) { * return Math.sqrt((int) in); * } * }; * SortedMap<String, Double> transformed = * Maps.transformSortedValues(map, sqrt); * System.out.println(transformed);}</pre> * * ... prints {@code {a=2.0, b=3.0}}. * * <p>Changes in the underlying map are reflected in this view. Conversely, * this view supports removal operations, and these are reflected in the * underlying map. * * <p>It's acceptable for the underlying map to contain null keys, and even * null values provided that the function is capable of accepting null input. * The transformed map might contain null values, if the function sometimes * gives a null result. * * <p>The returned map is not thread-safe or serializable, even if the * underlying map is. * * <p>The function is applied lazily, invoked when needed. This is necessary * for the returned map to be a view, but it means that the function will be * applied many times for bulk operations like {@link Map#containsValue} and * {@code Map.toString()}. For this to perform well, {@code function} should * be fast. To avoid lazy evaluation when the returned map doesn't need to be * a view, copy the returned map into a new map of your choosing. * * @deprecated Use {@link Maps#transformValues(SortedMap, Function)} */ @Deprecated public static <K, V1, V2> SortedMap<K, V2> transformValues( SortedMap<K, V1> fromMap, final Function<? super V1, V2> function) { return Maps.transformValues(fromMap, function); } /** * Returns a view of a sorted map whose values are derived from the original * sorted map's entries. In contrast to {@link #transformValues}, this * method's entry-transformation logic may depend on the key as well as the * value. * * <p>All other properties of the transformed map, such as iteration order, * are left intact. For example, the code: <pre> {@code * * Map<String, Boolean> options = * ImmutableSortedMap.of("verbose", true, "sort", false); * EntryTransformer<String, Boolean, String> flagPrefixer = * new EntryTransformer<String, Boolean, String>() { * public String transformEntry(String key, Boolean value) { * return value ? key : "yes" + key; * } * }; * SortedMap<String, String> transformed = * LabsMaps.transformSortedEntries(options, flagPrefixer); * System.out.println(transformed);}</pre> * * ... prints {@code {sort=yessort, verbose=verbose}}. * * <p>Changes in the underlying map are reflected in this view. Conversely, * this view supports removal operations, and these are reflected in the * underlying map. * * <p>It's acceptable for the underlying map to contain null keys and null * values provided that the transformer is capable of accepting null inputs. * The transformed map might contain null values if the transformer sometimes * gives a null result. * * <p>The returned map is not thread-safe or serializable, even if the * underlying map is. * * <p>The transformer is applied lazily, invoked when needed. This is * necessary for the returned map to be a view, but it means that the * transformer will be applied many times for bulk operations like {@link * Map#containsValue} and {@link Object#toString}. For this to perform well, * {@code transformer} should be fast. To avoid lazy evaluation when the * returned map doesn't need to be a view, copy the returned map into a new * map of your choosing. * * <p><b>Warning:</b> This method assumes that for any instance {@code k} of * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies * that {@code k2} is also of type {@code K}. Using an {@code * EntryTransformer} key type for which this may not hold, such as {@code * ArrayList}, may risk a {@code ClassCastException} when calling methods on * the transformed map. * * @deprecated Use {@link Maps#transformEntries(SortedMap, EntryTransformer)} */ @Deprecated public static <K, V1, V2> SortedMap<K, V2> transformEntries( final SortedMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { return Maps.transformEntries(fromMap, transformer); } /** * Computes the difference between two sorted maps, using the comparator of * the left map, or {@code Ordering.natural()} if the left map uses the * natural ordering of its elements. This difference is an immutable snapshot * of the state of the maps at the time this method is called. It will never * change, even if the maps change at a later time. * * <p>Since this method uses {@code TreeMap} instances internally, the keys of * the right map must all compare as distinct according to the comparator * of the left map. * * <p><b>Note:</b>If you only need to know whether two sorted maps have the * same mappings, call {@code left.equals(right)} instead of this method. * * @param left the map to treat as the "left" map for purposes of comparison * @param right the map to treat as the "right" map for purposes of comparison * @return the difference between the two maps * @deprecated Use {@link Maps#difference(SortedMap, Map)} */ @Deprecated public static <K, V> SortedMapDifference<K, V> difference( SortedMap<K, ? extends V> left, Map<? extends K, ? extends V> right) { return Maps.difference(left, right); } /** * Returns the specified comparator if not null; otherwise returns {@code * Ordering.natural()}. This method is an abomination of generics; the only * purpose of this method is to contain the ugly type-casting in one place. */ @SuppressWarnings("unchecked") static <E> Comparator<? super E> orNaturalOrder( @Nullable Comparator<? super E> comparator) { if (comparator != null) { // can't use ? : because of javac bug 5080917 return comparator; } return (Comparator<E>) Ordering.natural(); } /** * Returns a sorted map containing the mappings in {@code unfiltered} whose * keys satisfy a predicate. The returned map is a live view of {@code * unfiltered}; changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a key that * doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()} * methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings whose keys satisfy the * filter will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with * equals</i>, as documented at {@link Predicate#apply}. Do not provide a * predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is * inconsistent with equals. */ @GwtIncompatible("untested") public static <K, V> SortedMap<K, V> filterKeys( SortedMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { // TODO: Return a subclass of Maps.FilteredKeyMap for slightly better // performance. checkNotNull(keyPredicate); Predicate<Entry<K, V>> entryPredicate = new Predicate<Entry<K, V>>() { @Override public boolean apply(Entry<K, V> input) { return keyPredicate.apply(input.getKey()); } }; return filterEntries(unfiltered, entryPredicate); } /** * Returns a sorted map containing the mappings in {@code unfiltered} whose * values satisfy a predicate. The returned map is a live view of {@code * unfiltered}; changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a value * that doesn't satisfy the predicate, the map's {@code put()}, {@code * putAll()}, and {@link Entry#setValue} methods throw an {@link * IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings whose values satisfy the * filter will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with * equals</i>, as documented at {@link Predicate#apply}. Do not provide a * predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is * inconsistent with equals. */ @GwtIncompatible("untested") public static <K, V> SortedMap<K, V> filterValues( SortedMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) { checkNotNull(valuePredicate); Predicate<Entry<K, V>> entryPredicate = new Predicate<Entry<K, V>>() { @Override public boolean apply(Entry<K, V> input) { return valuePredicate.apply(input.getValue()); } }; return filterEntries(unfiltered, entryPredicate); } /** * Returns a sorted map containing the mappings in {@code unfiltered} that * satisfy a predicate. The returned map is a live view of {@code unfiltered}; * changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a * key/value pair that doesn't satisfy the predicate, the map's {@code put()} * and {@code putAll()} methods throw an {@link IllegalArgumentException}. * Similarly, the map's entries have a {@link Entry#setValue} method that * throws an {@link IllegalArgumentException} when the existing key and the * provided value don't satisfy the predicate. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings that satisfy the filter * will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with * equals</i>, as documented at {@link Predicate#apply}. */ @GwtIncompatible("untested") public static <K, V> SortedMap<K, V> filterEntries( SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { checkNotNull(entryPredicate); return (unfiltered instanceof FilteredSortedMap) ? filterFiltered((FilteredSortedMap<K, V>) unfiltered, entryPredicate) : new FilteredSortedMap<K, V>(checkNotNull(unfiltered), entryPredicate); } /** * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when * filtering a filtered sorted map. */ private static <K, V> SortedMap<K, V> filterFiltered( FilteredSortedMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) { Predicate<Entry<K, V>> predicate = Predicates.and(map.predicate, entryPredicate); return new FilteredSortedMap<K, V>(map.sortedMap(), predicate); } private static class FilteredSortedMap<K, V> extends Maps.FilteredEntryMap<K, V> implements SortedMap<K, V> { FilteredSortedMap(SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { super(unfiltered, entryPredicate); } SortedMap<K, V> sortedMap() { return (SortedMap<K, V>) unfiltered; } @Override public Comparator<? super K> comparator() { return sortedMap().comparator(); } @Override public K firstKey() { // correctly throws NoSuchElementException when filtered map is empty. return keySet().iterator().next(); } @Override public K lastKey() { SortedMap<K, V> headMap = sortedMap(); while (true) { // correctly throws NoSuchElementException when filtered map is empty. K key = headMap.lastKey(); if (apply(key, unfiltered.get(key))) { return key; } headMap = sortedMap().headMap(key); } } @Override public SortedMap<K, V> headMap(K toKey) { return new FilteredSortedMap<K, V>(sortedMap().headMap(toKey), predicate); } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { return new FilteredSortedMap<K, V>( sortedMap().subMap(fromKey, toKey), predicate); } @Override public SortedMap<K, V> tailMap(K fromKey) { return new FilteredSortedMap<K, V>( sortedMap().tailMap(fromKey), predicate); } } }
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.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.SortedSet; /** * A {@link Multiset} which maintains the ordering of its elements, according to * either their natural order or an explicit {@link Comparator}. In all cases, * this implementation uses {@link Comparable#compareTo} or * {@link Comparator#compare} instead of {@link Object#equals} to determine * equivalence of instances. * * <p><b>Warning:</b> The comparison must be <i>consistent with equals</i> as * explained by the {@link Comparable} class specification. Otherwise, the * resulting multiset will violate the {@link Collection} contract, which it is * specified in terms of {@link Object#equals}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset"> * {@code Multiset}</a>. * * @author Louis Wasserman * @since 11.0 */ @Beta @GwtCompatible public interface SortedMultiset<E> extends Multiset<E>, SortedIterable<E> { /** * Returns the comparator that orders this multiset, or * {@link Ordering#natural()} if the natural ordering of the elements is used. */ Comparator<? super E> comparator(); /** * Returns the entry of the first element in this multiset, or {@code null} if * this multiset is empty. */ Entry<E> firstEntry(); /** * Returns the entry of the last element in this multiset, or {@code null} if * this multiset is empty. */ Entry<E> lastEntry(); /** * Returns and removes the entry associated with the lowest element in this * multiset, or returns {@code null} if this multiset is empty. */ Entry<E> pollFirstEntry(); /** * Returns and removes the entry associated with the greatest element in this * multiset, or returns {@code null} if this multiset is empty. */ Entry<E> pollLastEntry(); /** * Returns a {@link SortedSet} view of the distinct elements in this multiset. */ @Override SortedSet<E> elementSet(); /** * {@inheritDoc} * * <p>The iterator returns the elements in ascending order according to this * multiset's comparator. */ @Override Iterator<E> iterator(); /** * Returns a descending view of this multiset. Modifications made to either * map will be reflected in the other. */ SortedMultiset<E> descendingMultiset(); /** * Returns a view of this multiset restricted to the elements less than * {@code upperBound}, optionally including {@code upperBound} itself. The * returned multiset is a view of this multiset, so changes to one will be * reflected in the other. The returned multiset supports all operations that * this multiset supports. * * <p>The returned multiset will throw an {@link IllegalArgumentException} on * attempts to add elements outside its range. */ SortedMultiset<E> headMultiset(E upperBound, BoundType boundType); /** * Returns a view of this multiset restricted to the range between * {@code lowerBound} and {@code upperBound}. The returned multiset is a view * of this multiset, so changes to one will be reflected in the other. The * returned multiset supports all operations that this multiset supports. * * <p>The returned multiset will throw an {@link IllegalArgumentException} on * attempts to add elements outside its range. * * <p>This method is equivalent to * {@code tailMultiset(lowerBound, lowerBoundType).headMultiset(upperBound, * upperBoundType)}. */ SortedMultiset<E> subMultiset(E lowerBound, BoundType lowerBoundType, E upperBound, BoundType upperBoundType); /** * Returns a view of this multiset restricted to the elements greater than * {@code lowerBound}, optionally including {@code lowerBound} itself. The * returned multiset is a view of this multiset, so changes to one will be * reflected in the other. The returned multiset supports all operations that * this multiset supports. * * <p>The returned multiset will throw an {@link IllegalArgumentException} on * attempts to add elements outside its range. */ SortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType); }
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 java.util.Set; import javax.annotation.Nullable; /** * A set which forwards all its method calls to another set. Subclasses should * override one or more methods to modify the behavior of the backing set as * desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><b>Warning:</b> The methods of {@code ForwardingSet} forward * <b>indiscriminately</b> to the methods of the delegate. For example, * overriding {@link #add} alone <b>will not</b> change the behavior of {@link * #addAll}, which can lead to unexpected behavior. In this case, you should * override {@code addAll} as well, either providing your own implementation, or * delegating to the provided {@code standardAddAll} 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 Kevin Bourrillion * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingSet<E> extends ForwardingCollection<E> implements Set<E> { // TODO(user): identify places where thread safety is actually lost /** Constructor for use by subclasses. */ protected ForwardingSet() {} @Override protected abstract Set<E> delegate(); @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 #equals} in terms of {@link #size} and * {@link #containsAll}. If you override either of those methods, you may wish * to override {@link #equals} to forward to this implementation. * * @since 7.0 */ @Beta protected boolean standardEquals(@Nullable Object object) { return Sets.equalsImpl(this, object); } /** * A sensible definition of {@link #hashCode} in terms of {@link #iterator}. * If you override {@link #iterator}, you may wish to override {@link #equals} * to forward to this implementation. * * @since 7.0 */ @Beta protected int standardHashCode() { return Sets.hashCodeImpl(this); } }
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; /** * A {@code Multimap} that cannot hold duplicate key-value pairs. Adding a * key-value pair that's already in the multimap has no effect. * * <p>The {@link #get}, {@link #removeAll}, and {@link #replaceValues} methods * each return a {@link Set} of values, while {@link #entries} returns a {@code * Set} of map entries. Though the method signature doesn't say so explicitly, * the map returned by {@link #asMap} has {@code Set} 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 SetMultimap<K, V> extends Multimap<K, V> { /** * {@inheritDoc} * * <p>Because a {@code SetMultimap} has unique values for a given key, this * method returns a {@link Set}, instead of the {@link java.util.Collection} * specified in the {@link Multimap} interface. */ @Override Set<V> get(@Nullable K key); /** * {@inheritDoc} * * <p>Because a {@code SetMultimap} has unique values for a given key, this * method returns a {@link Set}, instead of the {@link java.util.Collection} * specified in the {@link Multimap} interface. */ @Override Set<V> removeAll(@Nullable Object key); /** * {@inheritDoc} * * <p>Because a {@code SetMultimap} has unique values for a given key, this * method returns a {@link Set}, 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 Set<V> replaceValues(K key, Iterable<? extends V> values); /** * {@inheritDoc} * * <p>Because a {@code SetMultimap} has unique values for a given key, this * method returns a {@link Set}, instead of the {@link java.util.Collection} * specified in the {@link Multimap} interface. */ @Override Set<Map.Entry<K, V>> entries(); /** * {@inheritDoc} * * <p>Though the method signature doesn't say so explicitly, the returned map * has {@link Set} values. */ @Override Map<K, Collection<V>> asMap(); /** * 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. * * <p>An empty {@code SetMultimap} is equal to any other empty {@code * Multimap}, including an empty {@code ListMultimap}. */ @Override boolean equals(@Nullable Object obj); }
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.VisibleForTesting; import com.google.common.primitives.Ints; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import javax.annotation.Nullable; /** * A high-performance, immutable {@code Set} with reliable, user-specified * iteration order. Does not permit null elements. * * <p>Unlike {@link Collections#unmodifiableSet}, which is a <i>view</i> of a * separate collection that can still change, an instance of this class contains * its own private data and will <i>never</i> change. This class is convenient * for {@code public static final} sets ("constant sets") and also lets you * easily make a "defensive copy" of a set provided to your class by a caller. * * <p><b>Warning:</b> Like most sets, an {@code ImmutableSet} will not function * correctly if an element is modified after being placed in the set. For this * reason, and to avoid general confusion, it is strongly recommended to place * only immutable objects into this collection. * * <p>This class has been observed to perform significantly better than {@link * HashSet} for objects with very fast {@link Object#hashCode} implementations * (as a well-behaved immutable object should). While this class's factory * methods create hash-based instances, the {@link ImmutableSortedSet} subclass * performs binary searches instead. * * <p><b>Note:</b> Although this class is not final, it cannot be subclassed * outside its package as it has no public or protected constructors. Thus, * instances of this type 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>. * * @see ImmutableList * @see ImmutableMap * @author Kevin Bourrillion * @author Nick Kralevich * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // we're overriding default serialization public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements Set<E> { /** * Returns the empty immutable set. This set behaves and performs comparably * to {@link Collections#emptySet}, and is preferable mainly for consistency * and maintainability of your code. */ // Casting to any type is safe because the set will never hold any elements. @SuppressWarnings({"unchecked"}) public static <E> ImmutableSet<E> of() { return (ImmutableSet<E>) EmptyImmutableSet.INSTANCE; } /** * Returns an immutable set containing a single element. This set behaves and * performs comparably to {@link Collections#singleton}, but will not accept * a null element. It is preferable mainly for consistency and * maintainability of your code. */ public static <E> ImmutableSet<E> of(E element) { return new SingletonImmutableSet<E>(element); } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any element is null */ public static <E> ImmutableSet<E> of(E e1, E e2) { return construct(e1, e2); } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any element is null */ public static <E> ImmutableSet<E> of(E e1, E e2, E e3) { return construct(e1, e2, e3); } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any element is null */ public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4) { return construct(e1, e2, e3, e4); } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any element is null */ public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5) { return construct(e1, e2, e3, e4, e5); } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any element is null * @since 3.0 (source-compatible since 2.0) */ public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E... others) { final int paramCount = 6; Object[] elements = new Object[paramCount + others.length]; elements[0] = e1; elements[1] = e2; elements[2] = e3; elements[3] = e4; elements[4] = e5; elements[5] = e6; for (int i = paramCount; i < elements.length; i++) { elements[i] = others[i - paramCount]; } return construct(elements); } /** {@code elements} has to be internally created array. */ private static <E> ImmutableSet<E> construct(Object... elements) { int tableSize = chooseTableSize(elements.length); Object[] table = new Object[tableSize]; int mask = tableSize - 1; ArrayList<Object> uniqueElementsList = null; int hashCode = 0; for (int i = 0; i < elements.length; i++) { Object element = elements[i]; int hash = element.hashCode(); for (int j = Hashing.smear(hash); ; j++) { int index = j & mask; Object value = table[index]; if (value == null) { if (uniqueElementsList != null) { uniqueElementsList.add(element); } // Came to an empty slot. Put the element here. table[index] = element; hashCode += hash; break; } else if (value.equals(element)) { if (uniqueElementsList == null) { // first dup uniqueElementsList = new ArrayList<Object>(elements.length); for (int k = 0; k < i; k++) { Object previous = elements[k]; uniqueElementsList.add(previous); } } break; } } } Object[] uniqueElements = uniqueElementsList == null ? elements : uniqueElementsList.toArray(); if (uniqueElements.length == 1) { // There is only one element or elements are all duplicates @SuppressWarnings("unchecked") // we are careful to only pass in E E element = (E) uniqueElements[0]; return new SingletonImmutableSet<E>(element, hashCode); } else if (tableSize != chooseTableSize(uniqueElements.length)) { // Resize the table when the array includes too many duplicates. // when this happens, we have already made a copy return construct(uniqueElements); } else { return new RegularImmutableSet<E>(uniqueElements, hashCode, table, mask); } } // We use power-of-2 tables, and this is the highest int that's a power of 2 static final int MAX_TABLE_SIZE = Ints.MAX_POWER_OF_TWO; // Represents how tightly we can pack things, as a maximum. private static final double DESIRED_LOAD_FACTOR = 0.7; // If the set has this many elements, it will "max out" the table size private static final int CUTOFF = (int) Math.floor(MAX_TABLE_SIZE * DESIRED_LOAD_FACTOR); /** * Returns an array size suitable for the backing array of a hash table that * uses open addressing with linear probing in its implementation. The * returned size is the smallest power of two that can hold setSize elements * with the desired load factor. * * <p>Do not call this method with setSize < 2. */ @VisibleForTesting static int chooseTableSize(int setSize) { // Correct the size for open addressing to match desired load factor. if (setSize < CUTOFF) { // Round up to the next highest power of 2. int tableSize = Integer.highestOneBit(setSize - 1) << 1; while (tableSize * DESIRED_LOAD_FACTOR < setSize) { tableSize <<= 1; } return tableSize; } // The table can't be completely full or we'll get infinite reprobes checkArgument(setSize < MAX_TABLE_SIZE, "collection too large"); return MAX_TABLE_SIZE; } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any of {@code elements} is null * @since 3.0 */ public static <E> ImmutableSet<E> copyOf(E[] elements) { // TODO(benyu): could we delegate to // copyFromCollection(Arrays.asList(elements))? switch (elements.length) { case 0: return of(); case 1: return of(elements[0]); default: return construct(elements.clone()); } } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. This method iterates over {@code elements} at most once. * * <p>Note that if {@code s} is a {@code Set<String>}, then {@code * ImmutableSet.copyOf(s)} returns an {@code ImmutableSet<String>} containing * each of the strings in {@code s}, while {@code ImmutableSet.of(s)} returns * a {@code ImmutableSet<Set<String>>} containing one element (the given set * itself). * * <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. * * @throws NullPointerException if any of {@code elements} is null */ public static <E> ImmutableSet<E> copyOf(Iterable<? extends E> elements) { return (elements instanceof Collection) ? copyOf(Collections2.cast(elements)) : copyOf(elements.iterator()); } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any of {@code elements} is null */ public static <E> ImmutableSet<E> copyOf(Iterator<? extends E> elements) { // TODO(benyu): here we could avoid toArray() for 0 or 1-element list, // worth it? return copyFromCollection(Lists.newArrayList(elements)); } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. This method iterates over {@code elements} at most * once. * * <p>Note that if {@code s} is a {@code Set<String>}, then {@code * ImmutableSet.copyOf(s)} returns an {@code ImmutableSet<String>} containing * each of the strings in {@code s}, while {@code ImmutableSet.of(s)} returns * a {@code ImmutableSet<Set<String>>} containing one element (the given set * itself). * * <p><b>Note:</b> Despite what the method name suggests, {@code copyOf} will * return constant-space views, rather than linear-space copies, of some * inputs known to be immutable. For some other immutable inputs, such as key * sets of an {@code ImmutableMap}, it still performs a copy in order to avoid * holding references to the values of the map. The heuristics used in this * decision are undocumented and subject to change except that: * <ul> * <li>A full copy will be done of any {@code ImmutableSortedSet}.</li> * <li>{@code ImmutableSet.copyOf()} is idempotent with respect to pointer * equality.</li> * </ul> * * <p>This method is safe to use even when {@code elements} is a synchronized * or concurrent collection that is currently being modified by another * thread. * * @throws NullPointerException if any of {@code elements} is null * @since 7.0 (source-compatible since 2.0) */ public static <E> ImmutableSet<E> copyOf(Collection<? extends E> elements) { if (elements instanceof ImmutableSet && !(elements instanceof ImmutableSortedSet)) { @SuppressWarnings("unchecked") // all supported methods are covariant ImmutableSet<E> set = (ImmutableSet<E>) elements; if (!set.isPartialView()) { return set; } } return copyFromCollection(elements); } private static <E> ImmutableSet<E> copyFromCollection( Collection<? extends E> collection) { Object[] elements = collection.toArray(); switch (elements.length) { case 0: return of(); case 1: @SuppressWarnings("unchecked") // collection had only Es in it E onlyElement = (E) elements[0]; return of(onlyElement); default: // safe to use the array without copying it // as specified by Collection.toArray(). return construct(elements); } } ImmutableSet() {} /** Returns {@code true} if the {@code hashCode()} method runs quickly. */ boolean isHashCodeFast() { return false; } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof ImmutableSet && isHashCodeFast() && ((ImmutableSet<?>) object).isHashCodeFast() && hashCode() != object.hashCode()) { return false; } return Sets.equalsImpl(this, object); } @Override public int hashCode() { return Sets.hashCodeImpl(this); } // This declaration is needed to make Set.iterator() and // ImmutableCollection.iterator() consistent. @Override public abstract UnmodifiableIterator<E> iterator(); abstract static class ArrayImmutableSet<E> extends ImmutableSet<E> { // the elements (two or more) in the desired order. final transient Object[] elements; ArrayImmutableSet(Object[] elements) { this.elements = elements; } @Override public int size() { return elements.length; } @Override public boolean isEmpty() { return false; } /* * The cast is safe because the only way to create an instance is via the * create() method above, which only permits elements of type E. */ @SuppressWarnings("unchecked") @Override public UnmodifiableIterator<E> iterator() { return (UnmodifiableIterator<E>) Iterators.forArray(elements); } @Override public Object[] toArray() { Object[] array = new Object[size()]; System.arraycopy(elements, 0, array, 0, size()); return array; } @Override public <T> T[] toArray(T[] array) { int size = size(); if (array.length < size) { array = ObjectArrays.newArray(array, size); } else if (array.length > size) { array[size] = null; } System.arraycopy(elements, 0, array, 0, size); return array; } @Override public boolean containsAll(Collection<?> targets) { if (targets == this) { return true; } if (!(targets instanceof ArrayImmutableSet)) { return super.containsAll(targets); } if (targets.size() > size()) { return false; } for (Object target : ((ArrayImmutableSet<?>) targets).elements) { if (!contains(target)) { return false; } } return true; } @Override boolean isPartialView() { return false; } @Override ImmutableList<E> createAsList() { return new ImmutableAsList<E>(elements, this); } } /** such as ImmutableMap.keySet() */ abstract static class TransformedImmutableSet<D, E> extends ImmutableSet<E> { final D[] source; final int hashCode; TransformedImmutableSet(D[] source, int hashCode) { this.source = source; this.hashCode = hashCode; } abstract E transform(D element); @Override public int size() { return source.length; } @Override public boolean isEmpty() { return false; } @Override public UnmodifiableIterator<E> iterator() { return new AbstractIndexedListIterator<E>(source.length) { @Override protected E get(int index) { return transform(source[index]); } }; } @Override public Object[] toArray() { return toArray(new Object[size()]); } @Override public <T> T[] toArray(T[] array) { int size = size(); if (array.length < size) { array = ObjectArrays.newArray(array, size); } else if (array.length > size) { array[size] = null; } // Writes will produce ArrayStoreException when the toArray() doc requires Object[] objectArray = array; for (int i = 0; i < source.length; i++) { objectArray[i] = transform(source[i]); } return array; } @Override public final int hashCode() { return hashCode; } @Override boolean isHashCodeFast() { return true; } } /* * This class is used to serialize all ImmutableSet instances, except for * ImmutableEnumSet/ImmutableSortedSet, regardless of implementation type. It * captures their "logical contents" and they are reconstructed using public * static factories. This is necessary to ensure that the existence of a * particular implementation type is an implementation detail. */ private static class SerializedForm implements Serializable { final Object[] elements; SerializedForm(Object[] elements) { this.elements = elements; } Object readResolve() { return copyOf(elements); } private static final long serialVersionUID = 0; } @Override Object writeReplace() { return new SerializedForm(toArray()); } /** * Returns a new builder. The generated builder is equivalent to the builder * created by the {@link Builder} constructor. */ public static <E> Builder<E> builder() { return new Builder<E>(); } /** * A builder for creating immutable set instances, especially {@code public * static final} sets ("constant sets"). Example: <pre> {@code * * public static final ImmutableSet<Color> GOOGLE_COLORS = * new ImmutableSet.Builder<Color>() * .addAll(WEBSAFE_COLORS) * .add(new Color(0, 191, 255)) * .build();}</pre> * * Builder instances can be reused; it is safe to call {@link #build} multiple * times to build multiple sets in series. Each set is a superset of the set * created before it. * * @since 2.0 (imported from Google Collections Library) */ public static class Builder<E> extends ImmutableCollection.Builder<E> { // accessed directly by ImmutableSortedSet final ArrayList<E> contents = Lists.newArrayList(); /** * Creates a new builder. The returned builder is equivalent to the builder * generated by {@link ImmutableSet#builder}. */ public Builder() {} /** * Adds {@code element} to the {@code ImmutableSet}. If the {@code * ImmutableSet} already contains {@code element}, then {@code add} has no * effect (only the previously added element is retained). * * @param element the element to add * @return this {@code Builder} object * @throws NullPointerException if {@code element} is null */ @Override public Builder<E> add(E element) { contents.add(checkNotNull(element)); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableSet}, * ignoring duplicate elements (only the first duplicate element is added). * * @param elements the elements to add * @return this {@code Builder} object * @throws NullPointerException if {@code elements} is null or contains a * null element */ @Override public Builder<E> add(E... elements) { contents.ensureCapacity(contents.size() + elements.length); super.add(elements); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableSet}, * ignoring duplicate elements (only the first duplicate element is added). * * @param elements the {@code Iterable} to add to the {@code ImmutableSet} * @return this {@code Builder} object * @throws NullPointerException if {@code elements} is null or contains a * null element */ @Override public Builder<E> addAll(Iterable<? extends E> elements) { if (elements instanceof Collection) { Collection<?> collection = (Collection<?>) elements; contents.ensureCapacity(contents.size() + collection.size()); } super.addAll(elements); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableSet}, * ignoring duplicate elements (only the first duplicate element is added). * * @param elements the elements to add to the {@code ImmutableSet} * @return this {@code Builder} object * @throws NullPointerException if {@code elements} is null or contains a * null element */ @Override public Builder<E> addAll(Iterator<? extends E> elements) { super.addAll(elements); return this; } /** * Returns a newly-created {@code ImmutableSet} based on the contents of * the {@code Builder}. */ @Override public ImmutableSet<E> build() { return copyOf(contents); } } }
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 static com.google.common.collect.BstSide.LEFT; import static com.google.common.collect.BstSide.RIGHT; import com.google.common.annotations.GwtCompatible; import java.util.Comparator; import javax.annotation.Nullable; /** * Tools to perform single-key queries and mutations in binary search trees. * * @author Louis Wasserman */ @GwtCompatible final class BstOperations { private BstOperations() {} /** * Returns the node with key {@code key} in {@code tree}, if any. */ @Nullable public static <K, N extends BstNode<K, N>> N seek( Comparator<? super K> comparator, @Nullable N tree, @Nullable K key) { checkNotNull(comparator); if (tree == null) { return null; } int cmp = comparator.compare(key, tree.getKey()); if (cmp == 0) { return tree; } else { BstSide side = (cmp < 0) ? LEFT : RIGHT; return seek(comparator, tree.childOrNull(side), key); } } /** * Returns the result of performing the mutation specified by {@code mutationRule} in {@code * tree} at the location with key {@code key}. * * <ul> * <li>If the returned {@link BstModificationResult} has type {@code IDENTITY}, the exact * original tree is returned. * <li>If the returned {@code BstModificationResult} has type {@code REBUILDING_CHANGE}, * the tree will be rebuilt with the node factory of the mutation rule, but not rebalanced. * <li>If the returned {@code BstModificationResult} has type {@code REBALANCING_CHANGE}, * the tree will be rebalanced using the balance policy of the mutation rule. * </ul> */ public static <K, N extends BstNode<K, N>> BstMutationResult<K, N> mutate( Comparator<? super K> comparator, BstMutationRule<K, N> mutationRule, @Nullable N tree, @Nullable K key) { checkNotNull(comparator); checkNotNull(mutationRule); if (tree != null) { int cmp = comparator.compare(key, tree.getKey()); if (cmp != 0) { BstSide side = (cmp < 0) ? LEFT : RIGHT; BstMutationResult<K, N> mutation = mutate(comparator, mutationRule, tree.childOrNull(side), key); return mutation.lift( tree, side, mutationRule.getNodeFactory(), mutationRule.getBalancePolicy()); } } return modify(tree, key, mutationRule); } /** * Perform the local mutation at the tip of the specified path. */ public static <K, N extends BstNode<K, N>> BstMutationResult<K, N> mutate( BstInOrderPath<N> path, BstMutationRule<K, N> mutationRule) { checkNotNull(path); checkNotNull(mutationRule); BstBalancePolicy<N> balancePolicy = mutationRule.getBalancePolicy(); BstNodeFactory<N> nodeFactory = mutationRule.getNodeFactory(); N target = path.getTip(); K key = target.getKey(); BstMutationResult<K, N> result = modify(target, key, mutationRule); while (path.hasPrefix()) { BstInOrderPath<N> prefix = path.getPrefix(); result = result.lift(prefix.getTip(), path.getSideOfExtension(), nodeFactory, balancePolicy); path = prefix; } return result; } /** * Perform the local mutation right here, at the specified node. */ private static <K, N extends BstNode<K, N>> BstMutationResult<K, N> modify( @Nullable N tree, K key, BstMutationRule<K, N> mutationRule) { BstBalancePolicy<N> rebalancePolicy = mutationRule.getBalancePolicy(); BstNodeFactory<N> nodeFactory = mutationRule.getNodeFactory(); BstModifier<K, N> modifier = mutationRule.getModifier(); N originalRoot = tree; N changedRoot; N originalTarget = (tree == null) ? null : nodeFactory.createLeaf(tree); BstModificationResult<N> modResult = modifier.modify(key, originalTarget); N originalLeft = null; N originalRight = null; if (tree != null) { originalLeft = tree.childOrNull(LEFT); originalRight = tree.childOrNull(RIGHT); } switch (modResult.getType()) { case IDENTITY: changedRoot = tree; break; case REBUILDING_CHANGE: if (modResult.getChangedTarget() != null) { changedRoot = nodeFactory.createNode(modResult.getChangedTarget(), originalLeft, originalRight); } else if (tree == null) { changedRoot = null; } else { throw new AssertionError( "Modification result is a REBUILDING_CHANGE, but rebalancing required"); } break; case REBALANCING_CHANGE: if (modResult.getChangedTarget() != null) { changedRoot = rebalancePolicy.balance( nodeFactory, modResult.getChangedTarget(), originalLeft, originalRight); } else if (tree != null) { changedRoot = rebalancePolicy.combine(nodeFactory, originalLeft, originalRight); } else { changedRoot = null; } break; default: throw new AssertionError(); } return BstMutationResult.mutationResult(key, originalRoot, changedRoot, modResult); } /** * Returns the result of removing the minimum element from the specified subtree. */ public static <K, N extends BstNode<K, N>> BstMutationResult<K, N> extractMin( N root, BstNodeFactory<N> nodeFactory, BstBalancePolicy<N> balancePolicy) { checkNotNull(root); checkNotNull(nodeFactory); checkNotNull(balancePolicy); if (root.hasChild(LEFT)) { BstMutationResult<K, N> subResult = extractMin(root.getChild(LEFT), nodeFactory, balancePolicy); return subResult.lift(root, LEFT, nodeFactory, balancePolicy); } return BstMutationResult.mutationResult( root.getKey(), root, root.childOrNull(RIGHT), BstModificationResult.rebalancingChange(root, null)); } /** * Returns the result of removing the maximum element from the specified subtree. */ public static <K, N extends BstNode<K, N>> BstMutationResult<K, N> extractMax( N root, BstNodeFactory<N> nodeFactory, BstBalancePolicy<N> balancePolicy) { checkNotNull(root); checkNotNull(nodeFactory); checkNotNull(balancePolicy); if (root.hasChild(RIGHT)) { BstMutationResult<K, N> subResult = extractMax(root.getChild(RIGHT), nodeFactory, balancePolicy); return subResult.lift(root, RIGHT, nodeFactory, balancePolicy); } return BstMutationResult.mutationResult(root.getKey(), root, root.childOrNull(LEFT), BstModificationResult.rebalancingChange(root, null)); } /** * Inserts the specified entry into the tree as the minimum entry. Assumes that {@code * entry.getKey()} is less than the key of all nodes in the subtree {@code root}. */ public static <N extends BstNode<?, N>> N insertMin(@Nullable N root, N entry, BstNodeFactory<N> nodeFactory, BstBalancePolicy<N> balancePolicy) { checkNotNull(entry); checkNotNull(nodeFactory); checkNotNull(balancePolicy); if (root == null) { return nodeFactory.createLeaf(entry); } else { return balancePolicy.balance(nodeFactory, root, insertMin(root.childOrNull(LEFT), entry, nodeFactory, balancePolicy), root.childOrNull(RIGHT)); } } /** * Inserts the specified entry into the tree as the maximum entry. Assumes that {@code * entry.getKey()} is greater than the key of all nodes in the subtree {@code root}. */ public static <N extends BstNode<?, N>> N insertMax(@Nullable N root, N entry, BstNodeFactory<N> nodeFactory, BstBalancePolicy<N> balancePolicy) { checkNotNull(entry); checkNotNull(nodeFactory); checkNotNull(balancePolicy); if (root == null) { return nodeFactory.createLeaf(entry); } else { return balancePolicy.balance(nodeFactory, root, root.childOrNull(LEFT), insertMax(root.childOrNull(RIGHT), entry, nodeFactory, balancePolicy)); } } }
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.Beta; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Equivalences; import com.google.common.base.Function; import com.google.common.collect.MapMakerInternalMap.ReferenceEntry; import java.util.concurrent.ConcurrentMap; /** * Contains static methods pertaining to instances of {@link Interner}. * * @author Kevin Bourrillion * @since 3.0 */ @Beta public final class Interners { private Interners() {} /** * Returns a new thread-safe interner which retains a strong reference to each instance it has * interned, thus preventing these instances from being garbage-collected. If this retention is * acceptable, this implementation may perform better than {@link #newWeakInterner}. Note that * unlike {@link String#intern}, using this interner does not consume memory in the permanent * generation. */ public static <E> Interner<E> newStrongInterner() { final ConcurrentMap<E, E> map = new MapMaker().makeMap(); return new Interner<E>() { @Override public E intern(E sample) { E canonical = map.putIfAbsent(checkNotNull(sample), sample); return (canonical == null) ? sample : canonical; } }; } /** * Returns a new thread-safe interner which retains a weak reference to each instance it has * interned, and so does not prevent these instances from being garbage-collected. This most * likely does not perform as well as {@link #newStrongInterner}, but is the best alternative * when the memory usage of that implementation is unacceptable. Note that unlike {@link * String#intern}, using this interner does not consume memory in the permanent generation. */ @GwtIncompatible("java.lang.ref.WeakReference") public static <E> Interner<E> newWeakInterner() { return new WeakInterner<E>(); } private static class WeakInterner<E> implements Interner<E> { // MapMaker is our friend, we know about this type private final MapMakerInternalMap<E, Dummy> map = new MapMaker() .weakKeys() .keyEquivalence(Equivalences.equals()) .makeCustomMap(); @Override public E intern(E sample) { while (true) { // trying to read the canonical... ReferenceEntry<E, Dummy> entry = map.getEntry(sample); if (entry != null) { E canonical = entry.getKey(); if (canonical != null) { // only matters if weak/soft keys are used return canonical; } } // didn't see it, trying to put it instead... Dummy sneaky = map.putIfAbsent(sample, Dummy.VALUE); if (sneaky == null) { return sample; } else { /* Someone beat us to it! Trying again... * * Technically this loop not guaranteed to terminate, so theoretically (extremely * unlikely) this thread might starve, but even then, there is always going to be another * thread doing progress here. */ } } } private enum Dummy { VALUE } } /** * Returns a function that delegates to the {@link Interner#intern} method of the given interner. * * @since 8.0 */ public static <E> Function<E, E> asFunction(Interner<E> interner) { return new InternerFunction<E>(checkNotNull(interner)); } private static class InternerFunction<E> implements Function<E, E> { private final Interner<E> interner; public InternerFunction(Interner<E> interner) { this.interner = interner; } @Override public E apply(E input) { return interner.intern(input); } @Override public int hashCode() { return interner.hashCode(); } @Override public boolean equals(Object other) { if (other instanceof InternerFunction<?>) { InternerFunction<?> that = (InternerFunction<?>) other; return interner.equals(that.interner); } return false; } } }
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.Iterator; import java.util.SortedSet; /** * This class provides a skeletal implementation of the {@link SortedMultiset} interface. * * <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 Louis Wasserman */ @GwtCompatible abstract class AbstractSortedMultiset<E> extends AbstractMultiset<E> implements SortedMultiset<E> { @GwtTransient final Comparator<? super E> comparator; // needed for serialization @SuppressWarnings("unchecked") AbstractSortedMultiset() { this((Comparator) Ordering.natural()); } AbstractSortedMultiset(Comparator<? super E> comparator) { this.comparator = checkNotNull(comparator); } @Override public SortedSet<E> elementSet() { return (SortedSet<E>) super.elementSet(); } @Override SortedSet<E> createElementSet() { return new SortedMultisets.ElementSet<E>() { @Override SortedMultiset<E> multiset() { return AbstractSortedMultiset.this; } }; } @Override public Comparator<? super E> comparator() { return comparator; } @Override public Entry<E> firstEntry() { Iterator<Entry<E>> entryIterator = entryIterator(); return entryIterator.hasNext() ? entryIterator.next() : null; } @Override public Entry<E> lastEntry() { Iterator<Entry<E>> entryIterator = descendingEntryIterator(); return entryIterator.hasNext() ? entryIterator.next() : null; } @Override public Entry<E> pollFirstEntry() { Iterator<Entry<E>> entryIterator = entryIterator(); if (entryIterator.hasNext()) { Entry<E> result = entryIterator.next(); result = Multisets.immutableEntry(result.getElement(), result.getCount()); entryIterator.remove(); return result; } return null; } @Override public Entry<E> pollLastEntry() { Iterator<Entry<E>> entryIterator = descendingEntryIterator(); if (entryIterator.hasNext()) { Entry<E> result = entryIterator.next(); result = Multisets.immutableEntry(result.getElement(), result.getCount()); entryIterator.remove(); return result; } return null; } @Override public SortedMultiset<E> subMultiset(E fromElement, BoundType fromBoundType, E toElement, BoundType toBoundType) { return tailMultiset(fromElement, fromBoundType).headMultiset(toElement, toBoundType); } abstract Iterator<Entry<E>> descendingEntryIterator(); Iterator<E> descendingIterator() { return Multisets.iteratorImpl(descendingMultiset()); } private transient SortedMultiset<E> descendingMultiset; @Override public SortedMultiset<E> descendingMultiset() { SortedMultiset<E> result = descendingMultiset; return (result == null) ? descendingMultiset = createDescendingMultiset() : result; } SortedMultiset<E> createDescendingMultiset() { return new SortedMultisets.DescendingMultiset<E>() { @Override SortedMultiset<E> forwardMultiset() { return AbstractSortedMultiset.this; } @Override Iterator<Entry<E>> entryIterator() { return descendingEntryIterator(); } @Override public Iterator<E> iterator() { return descendingIterator(); } }; } }
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 com.google.common.annotations.GwtIncompatible; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.LinkedHashMap; /** * A {@code Multiset} implementation with predictable iteration order. Its * iterator orders elements according to when the first occurrence of the * element was added. When the multiset contains multiple instances of an * element, those instances are consecutive in the iteration order. If all * occurrences of an element are removed, after which that element is added to * the multiset, the element will appear at the end of the iteration. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset"> * {@code Multiset}</a>. * * @author Kevin Bourrillion * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // we're overriding default serialization public final class LinkedHashMultiset<E> extends AbstractMapBasedMultiset<E> { /** * Creates a new, empty {@code LinkedHashMultiset} using the default initial * capacity. */ public static <E> LinkedHashMultiset<E> create() { return new LinkedHashMultiset<E>(); } /** * Creates a new, empty {@code LinkedHashMultiset} with the specified expected * number of distinct elements. * * @param distinctElements the expected number of distinct elements * @throws IllegalArgumentException if {@code distinctElements} is negative */ public static <E> LinkedHashMultiset<E> create(int distinctElements) { return new LinkedHashMultiset<E>(distinctElements); } /** * Creates a new {@code LinkedHashMultiset} 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 */ public static <E> LinkedHashMultiset<E> create( Iterable<? extends E> elements) { LinkedHashMultiset<E> multiset = create(Multisets.inferDistinctElements(elements)); Iterables.addAll(multiset, elements); return multiset; } private LinkedHashMultiset() { super(new LinkedHashMap<E, Count>()); } private LinkedHashMultiset(int distinctElements) { // Could use newLinkedHashMapWithExpectedSize() if it existed super(new LinkedHashMap<E, Count>(Maps.capacity(distinctElements))); } /** * @serialData the number of distinct elements, the first element, its count, * the second element, its count, and so on */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); Serialization.writeMultiset(this, stream); } @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); int distinctElements = Serialization.readCount(stream); setBackingMap(new LinkedHashMap<E, Count>( Maps.capacity(distinctElements))); Serialization.populateMultiset(this, stream, distinctElements); } @GwtIncompatible("not needed in emulated source") 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.InvalidObjectException; import java.io.ObjectInputStream; import java.io.Serializable; /** * List returned by {@link ImmutableCollection#asList} when the collection isn't * an {@link ImmutableList} or an {@link ImmutableSortedSet}. * * @author Jared Levy */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") final class ImmutableAsList<E> extends RegularImmutableList<E> { private final transient ImmutableCollection<E> collection; ImmutableAsList(Object[] array, ImmutableCollection<E> collection) { super(array, 0, array.length); this.collection = collection; } @Override public boolean contains(Object target) { // The collection's contains() is at least as fast as RegularImmutableList's // and is often faster. return collection.contains(target); } /** * Serialized form that leads to the same performance as the original list. */ static class SerializedForm implements Serializable { final ImmutableCollection<?> collection; SerializedForm(ImmutableCollection<?> collection) { this.collection = collection; } Object readResolve() { return collection.asList(); } private static final long serialVersionUID = 0; } private void readObject(ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Use SerializedForm"); } @Override Object writeReplace() { return new SerializedForm(collection); } }
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.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.Map.Entry; import java.util.TreeMap; import javax.annotation.Nullable; /** * An immutable {@link SetMultimap} with reliable user-specified key and value * iteration order. Does not permit null keys or values. * * <p>Unlike {@link Multimaps#unmodifiableSetMultimap(SetMultimap)}, which is * a <i>view</i> of a separate multimap which can still change, an instance of * {@code ImmutableSetMultimap} contains its own data and will <i>never</i> * change. {@code ImmutableSetMultimap} is convenient for * {@code public static final} multimaps ("constant multimaps") and also lets * you easily make a "defensive copy" of a multimap provided to your class by * a caller. * * <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 Mike Ward * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V> implements SetMultimap<K, V> { /** Returns the empty multimap. */ // Casting is safe because the multimap will never hold any elements. @SuppressWarnings("unchecked") public static <K, V> ImmutableSetMultimap<K, V> of() { return (ImmutableSetMultimap<K, V>) EmptyImmutableSetMultimap.INSTANCE; } /** * Returns an immutable multimap containing a single entry. */ public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1) { ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder(); builder.put(k1, v1); return builder.build(); } /** * Returns an immutable multimap containing the given entries, in order. * Repeated occurrences of an entry (according to {@link Object#equals}) after * the first are ignored. */ public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2) { ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder(); builder.put(k1, v1); builder.put(k2, v2); return builder.build(); } /** * Returns an immutable multimap containing the given entries, in order. * Repeated occurrences of an entry (according to {@link Object#equals}) after * the first are ignored. */ public static <K, V> ImmutableSetMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3) { ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder(); builder.put(k1, v1); builder.put(k2, v2); builder.put(k3, v3); return builder.build(); } /** * Returns an immutable multimap containing the given entries, in order. * Repeated occurrences of an entry (according to {@link Object#equals}) after * the first are ignored. */ public static <K, V> ImmutableSetMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder(); builder.put(k1, v1); builder.put(k2, v2); builder.put(k3, v3); builder.put(k4, v4); return builder.build(); } /** * Returns an immutable multimap containing the given entries, in order. * Repeated occurrences of an entry (according to {@link Object#equals}) after * the first are ignored. */ public static <K, V> ImmutableSetMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder(); builder.put(k1, v1); builder.put(k2, v2); builder.put(k3, v3); builder.put(k4, v4); builder.put(k5, v5); return builder.build(); } // looking for of() with > 5 entries? Use the builder instead. /** * Returns a new {@link Builder}. */ public static <K, V> Builder<K, V> builder() { return new Builder<K, V>(); } /** * Multimap for {@link ImmutableSetMultimap.Builder} that maintains key * and value orderings and performs better than {@link LinkedHashMultimap}. */ private static class BuilderMultimap<K, V> extends AbstractMultimap<K, V> { BuilderMultimap() { super(new LinkedHashMap<K, Collection<V>>()); } @Override Collection<V> createCollection() { return Sets.newLinkedHashSet(); } private static final long serialVersionUID = 0; } /** * Multimap for {@link ImmutableSetMultimap.Builder} that sorts keys and * maintains value orderings. */ private static class SortedKeyBuilderMultimap<K, V> extends AbstractMultimap<K, V> { SortedKeyBuilderMultimap( Comparator<? super K> keyComparator, Multimap<K, V> multimap) { super(new TreeMap<K, Collection<V>>(keyComparator)); putAll(multimap); } @Override Collection<V> createCollection() { return Sets.newLinkedHashSet(); } private static final long serialVersionUID = 0; } /** * A builder for creating immutable {@code SetMultimap} instances, especially * {@code public static final} multimaps ("constant multimaps"). Example: * <pre> {@code * * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP = * new ImmutableSetMultimap.Builder<String, Integer>() * .put("one", 1) * .putAll("several", 1, 2, 3) * .putAll("many", 1, 2, 3, 4, 5) * .build();}</pre> * * Builder instances can be reused; it is safe to call {@link #build} multiple * times to build multiple multimaps in series. Each multimap contains the * key-value mappings in the previously created multimaps. * * @since 2.0 (imported from Google Collections Library) */ public static final class Builder<K, V> extends ImmutableMultimap.Builder<K, V> { /** * Creates a new builder. The returned builder is equivalent to the builder * generated by {@link ImmutableSetMultimap#builder}. */ public Builder() { builderMultimap = new BuilderMultimap<K, V>(); } /** * Adds a key-value mapping to the built multimap if it is not already * present. */ @Override public Builder<K, V> put(K key, V value) { builderMultimap.put(checkNotNull(key), checkNotNull(value)); return this; } /** * Adds an entry to the built multimap if it is not already present. * * @since 11.0 */ @Override public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { builderMultimap.put( checkNotNull(entry.getKey()), checkNotNull(entry.getValue())); return this; } @Override public Builder<K, V> putAll(K key, Iterable<? extends V> values) { Collection<V> collection = builderMultimap.get(checkNotNull(key)); for (V value : values) { collection.add(checkNotNull(value)); } return this; } @Override public Builder<K, V> putAll(K key, V... values) { return putAll(key, Arrays.asList(values)); } @Override public Builder<K, V> putAll( Multimap<? extends K, ? extends V> multimap) { for (Entry<? extends K, ? extends Collection<? extends V>> entry : multimap.asMap().entrySet()) { putAll(entry.getKey(), entry.getValue()); } return this; } /** * {@inheritDoc} * * @since 8.0 */ @Beta @Override public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) { builderMultimap = new SortedKeyBuilderMultimap<K, V>( checkNotNull(keyComparator), builderMultimap); return this; } /** * Specifies the ordering of the generated multimap's values for each key. * * <p>If this method is called, the sets returned by the {@code get()} * method of the generated multimap and its {@link Multimap#asMap()} view * are {@link ImmutableSortedSet} instances. However, serialization does not * preserve that property, though it does maintain the key and value * ordering. * * @since 8.0 */ // TODO: Make serialization behavior consistent. @Beta @Override public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) { super.orderValuesBy(valueComparator); return this; } /** * Returns a newly-created immutable set multimap. */ @Override public ImmutableSetMultimap<K, V> build() { return copyOf(builderMultimap, valueComparator); } } /** * Returns an immutable set multimap containing the same mappings as * {@code multimap}. The generated multimap's key and value orderings * correspond to the iteration ordering of the {@code multimap.asMap()} view. * Repeated occurrences of an entry in the multimap after the first are * ignored. * * <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. * * @throws NullPointerException if any key or value in {@code multimap} is * null */ public static <K, V> ImmutableSetMultimap<K, V> copyOf( Multimap<? extends K, ? extends V> multimap) { return copyOf(multimap, null); } private static <K, V> ImmutableSetMultimap<K, V> copyOf( Multimap<? extends K, ? extends V> multimap, Comparator<? super V> valueComparator) { checkNotNull(multimap); // eager for GWT if (multimap.isEmpty() && valueComparator == null) { return of(); } if (multimap instanceof ImmutableSetMultimap) { @SuppressWarnings("unchecked") // safe since multimap is not writable ImmutableSetMultimap<K, V> kvMultimap = (ImmutableSetMultimap<K, V>) multimap; if (!kvMultimap.isPartialView()) { return kvMultimap; } } ImmutableMap.Builder<K, ImmutableSet<V>> builder = ImmutableMap.builder(); int size = 0; for (Entry<? extends K, ? extends Collection<? extends V>> entry : multimap.asMap().entrySet()) { K key = entry.getKey(); Collection<? extends V> values = entry.getValue(); ImmutableSet<V> set = (valueComparator == null) ? ImmutableSet.copyOf(values) : ImmutableSortedSet.copyOf(valueComparator, values); if (!set.isEmpty()) { builder.put(key, set); size += set.size(); } } return new ImmutableSetMultimap<K, V>( builder.build(), size, valueComparator); } // Returned by get() when values are sorted and a missing key is provided. private final transient ImmutableSortedSet<V> emptySet; ImmutableSetMultimap(ImmutableMap<K, ImmutableSet<V>> map, int size, @Nullable Comparator<? super V> valueComparator) { super(map, size); this.emptySet = (valueComparator == null) ? null : ImmutableSortedSet.<V>emptySet(valueComparator); } // views /** * Returns an immutable set of the values for the given key. If no mappings * in the multimap have the provided key, an empty immutable set is returned. * The values are in the same order as the parameters used to build this * multimap. */ @Override public ImmutableSet<V> get(@Nullable K key) { // This cast is safe as its type is known in constructor. ImmutableSet<V> set = (ImmutableSet<V>) map.get(key); if (set != null) { return set; } else if (emptySet != null) { return emptySet; } else { return ImmutableSet.<V>of(); } } private transient ImmutableSetMultimap<V, K> inverse; /** * {@inheritDoc} * * <p>Because an inverse of a set multimap cannot contain multiple pairs with the same key and * value, this method returns an {@code ImmutableSetMultimap} rather than the * {@code ImmutableMultimap} specified in the {@code ImmutableMultimap} class. * * @since 11 */ @Beta public ImmutableSetMultimap<V, K> inverse() { ImmutableSetMultimap<V, K> result = inverse; return (result == null) ? (inverse = invert()) : result; } private ImmutableSetMultimap<V, K> invert() { Builder<V, K> builder = builder(); for (Entry<K, V> entry : entries()) { builder.put(entry.getValue(), entry.getKey()); } ImmutableSetMultimap<V, K> invertedMultimap = builder.build(); invertedMultimap.inverse = this; return invertedMultimap; } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always */ @Override public ImmutableSet<V> removeAll(Object key) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always */ @Override public ImmutableSet<V> replaceValues( K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } private transient ImmutableSet<Entry<K, V>> entries; /** * Returns an immutable collection of all key-value pairs in the multimap. * Its iterator traverses the values for the first key, the values for the * second key, and so on. */ // TODO(kevinb): Fix this so that two copies of the entries are not created. @Override public ImmutableSet<Entry<K, V>> entries() { ImmutableSet<Entry<K, V>> result = entries; return (result == null) ? (entries = ImmutableSet.copyOf(super.entries())) : result; } /** * @serialData number of distinct keys, and then for each distinct key: the * key, the number of values for that key, and the key's values */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); Serialization.writeMultimap(this, stream); } @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); int keyCount = stream.readInt(); if (keyCount < 0) { throw new InvalidObjectException("Invalid key count " + keyCount); } ImmutableMap.Builder<Object, ImmutableSet<Object>> builder = ImmutableMap.builder(); int tmpSize = 0; for (int i = 0; i < keyCount; i++) { Object key = stream.readObject(); int valueCount = stream.readInt(); if (valueCount <= 0) { throw new InvalidObjectException("Invalid value count " + valueCount); } Object[] array = new Object[valueCount]; for (int j = 0; j < valueCount; j++) { array[j] = stream.readObject(); } ImmutableSet<Object> valueSet = ImmutableSet.copyOf(array); if (valueSet.size() != array.length) { throw new InvalidObjectException( "Duplicate key-value pairs exist for key " + key); } builder.put(key, valueSet); tmpSize += valueCount; } ImmutableMap<Object, ImmutableSet<Object>> tmpMap; try { tmpMap = builder.build(); } catch (IllegalArgumentException e) { throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e); } FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap); FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize); } @GwtIncompatible("not needed in emulated source.") 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.Iterator; /** * An iterator which forwards all its method calls to another 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 Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingIterator<T> extends ForwardingObject implements Iterator<T> { /** Constructor for use by subclasses. */ protected ForwardingIterator() {} @Override protected abstract Iterator<T> delegate(); @Override public boolean hasNext() { return delegate().hasNext(); } @Override public T next() { return delegate().next(); } @Override public void remove() { delegate().remove(); } }
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.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Queue; import java.util.RandomAccess; import java.util.Set; import java.util.SortedSet; import javax.annotation.Nullable; /** * This class contains static utility methods that operate on or return objects * of type {@code Iterable}. Except as noted, each method has a corresponding * {@link Iterator}-based method in the {@link Iterators} class. * * <p><i>Performance notes:</i> Unless otherwise noted, all of the iterables * produced in this class are <i>lazy</i>, which means that their iterators * only advance the backing iteration when absolutely necessary. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Iterables"> * {@code Iterables}</a>. * * @author Kevin Bourrillion * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class Iterables { private Iterables() {} /** Returns an unmodifiable view of {@code iterable}. */ public static <T> Iterable<T> unmodifiableIterable( final Iterable<T> iterable) { checkNotNull(iterable); if (iterable instanceof UnmodifiableIterable || iterable instanceof ImmutableCollection) { return iterable; } return new UnmodifiableIterable<T>(iterable); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <E> Iterable<E> unmodifiableIterable( ImmutableCollection<E> iterable) { return checkNotNull(iterable); } private static final class UnmodifiableIterable<T> implements Iterable<T> { private final Iterable<T> iterable; private UnmodifiableIterable(Iterable<T> iterable) { this.iterable = iterable; } @Override public Iterator<T> iterator() { return Iterators.unmodifiableIterator(iterable.iterator()); } @Override public String toString() { return iterable.toString(); } // no equals and hashCode; it would break the contract! } /** * Returns the number of elements in {@code iterable}. */ public static int size(Iterable<?> iterable) { return (iterable instanceof Collection) ? ((Collection<?>) iterable).size() : Iterators.size(iterable.iterator()); } /** * Returns {@code true} if {@code iterable} contains {@code element}; that is, * any object for which {@code equals(element)} is true. */ public static boolean contains(Iterable<?> iterable, @Nullable Object element) { if (iterable instanceof Collection) { Collection<?> collection = (Collection<?>) iterable; try { return collection.contains(element); } catch (NullPointerException e) { return false; } catch (ClassCastException e) { return false; } } return Iterators.contains(iterable.iterator(), element); } /** * Removes, from an iterable, every element that belongs to the provided * collection. * * <p>This method calls {@link Collection#removeAll} if {@code iterable} is a * collection, and {@link Iterators#removeAll} otherwise. * * @param removeFrom the iterable to (potentially) remove elements from * @param elementsToRemove the elements to remove * @return {@code true} if any element was removed from {@code iterable} */ public static boolean removeAll( Iterable<?> removeFrom, Collection<?> elementsToRemove) { return (removeFrom instanceof Collection) ? ((Collection<?>) removeFrom).removeAll(checkNotNull(elementsToRemove)) : Iterators.removeAll(removeFrom.iterator(), elementsToRemove); } /** * Removes, from an iterable, every element that does not belong to the * provided collection. * * <p>This method calls {@link Collection#retainAll} if {@code iterable} is a * collection, and {@link Iterators#retainAll} otherwise. * * @param removeFrom the iterable to (potentially) remove elements from * @param elementsToRetain the elements to retain * @return {@code true} if any element was removed from {@code iterable} */ public static boolean retainAll( Iterable<?> removeFrom, Collection<?> elementsToRetain) { return (removeFrom instanceof Collection) ? ((Collection<?>) removeFrom).retainAll(checkNotNull(elementsToRetain)) : Iterators.retainAll(removeFrom.iterator(), elementsToRetain); } /** * Removes, from an iterable, every element that satisfies the provided * predicate. * * @param removeFrom the iterable to (potentially) remove elements from * @param predicate a predicate that determines whether an element should * be removed * @return {@code true} if any elements were removed from the iterable * * @throws UnsupportedOperationException if the iterable does not support * {@code remove()}. * @since 2.0 */ public static <T> boolean removeIf( Iterable<T> removeFrom, Predicate<? super T> predicate) { if (removeFrom instanceof RandomAccess && removeFrom instanceof List) { return removeIfFromRandomAccessList( (List<T>) removeFrom, checkNotNull(predicate)); } return Iterators.removeIf(removeFrom.iterator(), predicate); } private static <T> boolean removeIfFromRandomAccessList( List<T> list, Predicate<? super T> predicate) { // Note: Not all random access lists support set() so we need to deal with // those that don't and attempt the slower remove() based solution. int from = 0; int to = 0; for (; from < list.size(); from++) { T element = list.get(from); if (!predicate.apply(element)) { if (from > to) { try { list.set(to, element); } catch (UnsupportedOperationException e) { slowRemoveIfForRemainingElements(list, predicate, to, from); return true; } } to++; } } // Clear the tail of any remaining items list.subList(to, list.size()).clear(); return from != to; } private static <T> void slowRemoveIfForRemainingElements(List<T> list, Predicate<? super T> predicate, int to, int from) { // Here we know that: // * (to < from) and that both are valid indices. // * Everything with (index < to) should be kept. // * Everything with (to <= index < from) should be removed. // * The element with (index == from) should be kept. // * Everything with (index > from) has not been checked yet. // Check from the end of the list backwards (minimize expected cost of // moving elements when remove() is called). Stop before 'from' because // we already know that should be kept. for (int n = list.size() - 1; n > from; n--) { if (predicate.apply(list.get(n))) { list.remove(n); } } // And now remove everything in the range [to, from) (going backwards). for (int n = from - 1; n >= to; n--) { list.remove(n); } } /** * Determines whether two iterables contain equal elements in the same order. * More specifically, this method returns {@code true} if {@code iterable1} * and {@code iterable2} contain the same number of elements and every element * of {@code iterable1} is equal to the corresponding element of * {@code iterable2}. */ public static boolean elementsEqual( Iterable<?> iterable1, Iterable<?> iterable2) { return Iterators.elementsEqual(iterable1.iterator(), iterable2.iterator()); } /** * Returns a string representation of {@code iterable}, with the format * {@code [e1, e2, ..., en]}. */ public static String toString(Iterable<?> iterable) { return Iterators.toString(iterable.iterator()); } /** * Returns the single element contained in {@code iterable}. * * @throws NoSuchElementException if the iterable is empty * @throws IllegalArgumentException if the iterable contains multiple * elements */ public static <T> T getOnlyElement(Iterable<T> iterable) { return Iterators.getOnlyElement(iterable.iterator()); } /** * Returns the single element contained in {@code iterable}, or {@code * defaultValue} if the iterable is empty. * * @throws IllegalArgumentException if the iterator contains multiple * elements */ public static <T> T getOnlyElement( Iterable<T> iterable, @Nullable T defaultValue) { return Iterators.getOnlyElement(iterable.iterator(), defaultValue); } /** * Copies an iterable's elements into an array. * * @param iterable the iterable to copy * @param type the type of the elements * @return a newly-allocated array into which all the elements of the iterable * have been copied */ @GwtIncompatible("Array.newInstance(Class, int)") public static <T> T[] toArray(Iterable<? extends T> iterable, Class<T> type) { Collection<? extends T> collection = toCollection(iterable); T[] array = ObjectArrays.newArray(type, collection.size()); return collection.toArray(array); } /** * Copies an iterable's elements into an array. * * @param iterable the iterable to copy * @return a newly-allocated array into which all the elements of the iterable * have been copied */ static Object[] toArray(Iterable<?> iterable) { return toCollection(iterable).toArray(); } /** * Converts an iterable into a collection. If the iterable is already a * collection, it is returned. Otherwise, an {@link java.util.ArrayList} is * created with the contents of the iterable in the same iteration order. */ private static <E> Collection<E> toCollection(Iterable<E> iterable) { return (iterable instanceof Collection) ? (Collection<E>) iterable : Lists.newArrayList(iterable.iterator()); } /** * Adds all elements in {@code iterable} to {@code collection}. * * @return {@code true} if {@code collection} was modified as a result of this * operation. */ public static <T> boolean addAll( Collection<T> addTo, Iterable<? extends T> elementsToAdd) { if (elementsToAdd instanceof Collection) { Collection<? extends T> c = Collections2.cast(elementsToAdd); return addTo.addAll(c); } return Iterators.addAll(addTo, elementsToAdd.iterator()); } /** * Returns the number of elements in the specified iterable that equal the * specified object. This implementation avoids a full iteration when the * iterable is a {@link Multiset} or {@link Set}. * * @see Collections#frequency */ public static int frequency(Iterable<?> iterable, @Nullable Object element) { if ((iterable instanceof Multiset)) { return ((Multiset<?>) iterable).count(element); } if ((iterable instanceof Set)) { return ((Set<?>) iterable).contains(element) ? 1 : 0; } return Iterators.frequency(iterable.iterator(), element); } /** * Returns an iterable whose iterators cycle indefinitely over the elements of * {@code 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 {@code iterable}. The iterator's * {@code hasNext()} method returns {@code true} until {@code 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. * * <p>To cycle over the iterable {@code n} times, use the following: * {@code Iterables.concat(Collections.nCopies(n, iterable))} */ public static <T> Iterable<T> cycle(final Iterable<T> iterable) { checkNotNull(iterable); return new Iterable<T>() { @Override public Iterator<T> iterator() { return Iterators.cycle(iterable); } @Override public String toString() { return iterable.toString() + " (cycled)"; } }; } /** * Returns an iterable whose iterators cycle indefinitely over the provided * elements. * * <p>After {@code remove} is invoked on a generated iterator, the removed * element will no longer appear in either that iterator or any other iterator * created from the same source iterable. That is, this method behaves exactly * as {@code Iterables.cycle(Lists.newArrayList(elements))}. The iterator's * {@code hasNext} method returns {@code true} until all of the original * elements have been removed. * * <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. * * <p>To cycle over the elements {@code n} times, use the following: * {@code Iterables.concat(Collections.nCopies(n, Arrays.asList(elements)))} */ public static <T> Iterable<T> cycle(T... elements) { return cycle(Lists.newArrayList(elements)); } /** * Combines two iterables into a single iterable. The returned iterable has an * iterator that traverses the elements in {@code a}, followed by the elements * in {@code b}. The source iterators are not polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the * corresponding input iterator supports it. */ @SuppressWarnings("unchecked") public static <T> Iterable<T> concat( Iterable<? extends T> a, Iterable<? extends T> b) { checkNotNull(a); checkNotNull(b); return concat(Arrays.asList(a, b)); } /** * Combines three iterables into a single iterable. The returned iterable has * an iterator that traverses the elements in {@code a}, followed by the * elements in {@code b}, followed by the elements in {@code c}. The source * iterators are not polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the * corresponding input iterator supports it. */ @SuppressWarnings("unchecked") public static <T> Iterable<T> concat(Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c) { checkNotNull(a); checkNotNull(b); checkNotNull(c); return concat(Arrays.asList(a, b, c)); } /** * Combines four iterables into a single iterable. The returned iterable has * an iterator that traverses the elements in {@code a}, followed by the * elements in {@code b}, followed by the elements in {@code c}, followed by * the elements in {@code d}. The source iterators are not polled until * necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the * corresponding input iterator supports it. */ @SuppressWarnings("unchecked") public static <T> Iterable<T> concat(Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c, Iterable<? extends T> d) { checkNotNull(a); checkNotNull(b); checkNotNull(c); checkNotNull(d); return concat(Arrays.asList(a, b, c, d)); } /** * Combines multiple iterables into a single iterable. The returned iterable * has an iterator that traverses the elements of each iterable in * {@code inputs}. The input iterators are not polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the * corresponding input iterator supports it. * * @throws NullPointerException if any of the provided iterables is null */ public static <T> Iterable<T> concat(Iterable<? extends T>... inputs) { return concat(ImmutableList.copyOf(inputs)); } /** * Combines multiple iterables into a single iterable. The returned iterable * has an iterator that traverses the elements of each iterable in * {@code inputs}. The input iterators are not polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the * corresponding input iterator supports it. The methods of the returned * iterable may throw {@code NullPointerException} if any of the input * iterators is null. */ public static <T> Iterable<T> concat( final Iterable<? extends Iterable<? extends T>> inputs) { checkNotNull(inputs); return new IterableWithToString<T>() { @Override public Iterator<T> iterator() { return Iterators.concat(iterators(inputs)); } }; } /** * Returns an iterator over the iterators of the given iterables. */ private static <T> UnmodifiableIterator<Iterator<? extends T>> iterators( Iterable<? extends Iterable<? extends T>> iterables) { final Iterator<? extends Iterable<? extends T>> iterableIterator = iterables.iterator(); return new UnmodifiableIterator<Iterator<? extends T>>() { @Override public boolean hasNext() { return iterableIterator.hasNext(); } @Override public Iterator<? extends T> next() { return iterableIterator.next().iterator(); } }; } /** * Divides an iterable into unmodifiable sublists of the given size (the final * iterable may be smaller). For example, partitioning an iterable containing * {@code [a, b, c, d, e]} with a partition size of 3 yields {@code * [[a, b, c], [d, e]]} -- an outer iterable containing two inner lists of * three and two elements, all in the original order. * * <p>Iterators returned by the returned iterable do not support the {@link * Iterator#remove()} method. The returned lists implement {@link * RandomAccess}, whether or not the input list does. * * <p><b>Note:</b> if {@code iterable} is a {@link List}, use {@link * Lists#partition(List, int)} instead. * * @param iterable the iterable to return a partitioned view of * @param size the desired size of each partition (the last may be smaller) * @return an iterable of unmodifiable lists containing the elements of {@code * iterable} divided into partitions * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T> Iterable<List<T>> partition( final Iterable<T> iterable, final int size) { checkNotNull(iterable); checkArgument(size > 0); return new IterableWithToString<List<T>>() { @Override public Iterator<List<T>> iterator() { return Iterators.partition(iterable.iterator(), size); } }; } /** * Divides an iterable into unmodifiable sublists of the given size, padding * the final iterable with null values if necessary. For example, partitioning * an iterable containing {@code [a, b, c, d, e]} with a partition size of 3 * yields {@code [[a, b, c], [d, e, null]]} -- an outer iterable containing * two inner lists of three elements each, all in the original order. * * <p>Iterators returned by the returned iterable do not support the {@link * Iterator#remove()} method. * * @param iterable the iterable to return a partitioned view of * @param size the desired size of each partition * @return an iterable of unmodifiable lists containing the elements of {@code * iterable} divided into partitions (the final iterable may have * trailing null elements) * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T> Iterable<List<T>> paddedPartition( final Iterable<T> iterable, final int size) { checkNotNull(iterable); checkArgument(size > 0); return new IterableWithToString<List<T>>() { @Override public Iterator<List<T>> iterator() { return Iterators.paddedPartition(iterable.iterator(), size); } }; } /** * Returns the elements of {@code unfiltered} that satisfy a predicate. The * resulting iterable's iterator does not support {@code remove()}. */ public static <T> Iterable<T> filter( final Iterable<T> unfiltered, final Predicate<? super T> predicate) { checkNotNull(unfiltered); checkNotNull(predicate); return new IterableWithToString<T>() { @Override public Iterator<T> iterator() { return Iterators.filter(unfiltered.iterator(), predicate); } }; } /** * Returns all instances of class {@code type} in {@code unfiltered}. The * returned iterable has elements whose class is {@code type} or a subclass of * {@code type}. The returned iterable's iterator does not support * {@code remove()}. * * @param unfiltered an iterable containing objects of any type * @param type the type of elements desired * @return an unmodifiable iterable containing all elements of the original * iterable that were of the requested type */ @GwtIncompatible("Class.isInstance") public static <T> Iterable<T> filter( final Iterable<?> unfiltered, final Class<T> type) { checkNotNull(unfiltered); checkNotNull(type); return new IterableWithToString<T>() { @Override public Iterator<T> iterator() { return Iterators.filter(unfiltered.iterator(), type); } }; } /** * Returns {@code true} if one or more elements in {@code iterable} satisfy * the predicate. */ public static <T> boolean any( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.any(iterable.iterator(), predicate); } /** * Returns {@code true} if every element in {@code iterable} satisfies the * predicate. If {@code iterable} is empty, {@code true} is returned. */ public static <T> boolean all( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.all(iterable.iterator(), predicate); } /** * Returns the first element in {@code iterable} that satisfies the given * predicate; use this method only when such an element is known to exist. If * it is possible that <i>no</i> element will match, use {@link * #tryFind)} or {@link #find(Iterable, Predicate, T)} instead. * * @throws NoSuchElementException if no element in {@code iterable} matches * the given predicate */ public static <T> T find(Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.find(iterable.iterator(), predicate); } /** * Returns the first element in {@code iterable} that satisfies the given * predicate, or {@code defaultValue} if none found. Note that this can * usually be handled more naturally using {@code * tryFind(iterable, predicate).or(defaultValue)}. * * @since 7.0 */ public static <T> T find(Iterable<T> iterable, Predicate<? super T> predicate, @Nullable T defaultValue) { return Iterators.find(iterable.iterator(), predicate, defaultValue); } /** * Returns an {@link Optional} containing the first element in {@code * 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 {@code iterable}, a * NullPointerException will be thrown. * * @since 11.0 */ public static <T> Optional<T> tryFind(Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.tryFind(iterable.iterator(), predicate); } /** * Returns the index in {@code iterable} of the first element that satisfies * the provided {@code predicate}, or {@code -1} if the Iterable has no such * elements. * * <p>More formally, returns the lowest index {@code i} such that * {@code predicate.apply(Iterables.get(iterable, i))} returns {@code true}, * or {@code -1} if there is no such index. * * @since 2.0 */ public static <T> int indexOf( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.indexOf(iterable.iterator(), predicate); } /** * Returns an iterable that applies {@code function} to each element of {@code * fromIterable}. * * <p>The returned iterable's iterator supports {@code remove()} if the * provided iterator does. After a successful {@code remove()} call, * {@code fromIterable} no longer contains the corresponding element. * * <p>If the input {@code Iterable} is known to be a {@code List} or other * {@code Collection}, consider {@link Lists#transform} and {@link * Collections2#transform}. */ public static <F, T> Iterable<T> transform(final Iterable<F> fromIterable, final Function<? super F, ? extends T> function) { checkNotNull(fromIterable); checkNotNull(function); return new IterableWithToString<T>() { @Override public Iterator<T> iterator() { return Iterators.transform(fromIterable.iterator(), function); } }; } /** * Returns the element at the specified position in an iterable. * * @param position position of the element to return * @return the element at the specified position in {@code iterable} * @throws IndexOutOfBoundsException if {@code position} is negative or * greater than or equal to the size of {@code iterable} */ public static <T> T get(Iterable<T> iterable, int position) { checkNotNull(iterable); if (iterable instanceof List) { return ((List<T>) iterable).get(position); } if (iterable instanceof Collection) { // Can check both ends Collection<T> collection = (Collection<T>) iterable; Preconditions.checkElementIndex(position, collection.size()); } else { // Can only check the lower end checkNonnegativeIndex(position); } return Iterators.get(iterable.iterator(), position); } private static void checkNonnegativeIndex(int position) { if (position < 0) { throw new IndexOutOfBoundsException( "position cannot be negative: " + position); } } /** * Returns the element at the specified position in an iterable or a default * value otherwise. * * @param position position of the element to return * @param defaultValue the default value to return if {@code position} is * greater than or equal to the size of the iterable * @return the element at the specified position in {@code iterable} or * {@code defaultValue} if {@code iterable} contains fewer than * {@code position + 1} elements. * @throws IndexOutOfBoundsException if {@code position} is negative * @since 4.0 */ public static <T> T get(Iterable<T> iterable, int position, @Nullable T defaultValue) { checkNotNull(iterable); checkNonnegativeIndex(position); try { return get(iterable, position); } catch (IndexOutOfBoundsException e) { return defaultValue; } } /** * Returns the first element in {@code iterable} or {@code defaultValue} if * the iterable is empty. The {@link Iterators} analog to this method is * {@link Iterators#getNext}. * * @param defaultValue the default value to return if the iterable is empty * @return the first element of {@code iterable} or the default value * @since 7.0 */ public static <T> T getFirst(Iterable<T> iterable, @Nullable T defaultValue) { return Iterators.getNext(iterable.iterator(), defaultValue); } /** * Returns the last element of {@code iterable}. * * @return the last element of {@code iterable} * @throws NoSuchElementException if the iterable is empty */ public static <T> T getLast(Iterable<T> iterable) { // TODO(kevinb): Support a concurrently modified collection? if (iterable instanceof List) { List<T> list = (List<T>) iterable; if (list.isEmpty()) { throw new NoSuchElementException(); } return getLastInNonemptyList(list); } /* * 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<T> sortedSet = (SortedSet<T>) iterable; return sortedSet.last(); } return Iterators.getLast(iterable.iterator()); } /** * Returns the last element of {@code iterable} or {@code defaultValue} if * the iterable is empty. * * @param defaultValue the value to return if {@code iterable} is empty * @return the last element of {@code iterable} or the default value * @since 3.0 */ public static <T> T getLast(Iterable<T> iterable, @Nullable T defaultValue) { if (iterable instanceof Collection) { Collection<T> collection = (Collection<T>) iterable; if (collection.isEmpty()) { return defaultValue; } } if (iterable instanceof List) { List<T> list = (List<T>) iterable; return getLastInNonemptyList(list); } /* * 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<T> sortedSet = (SortedSet<T>) iterable; return sortedSet.last(); } return Iterators.getLast(iterable.iterator(), defaultValue); } private static <T> T getLastInNonemptyList(List<T> list) { return list.get(list.size() - 1); } /** * Returns a view of {@code iterable} that skips its first * {@code numberToSkip} elements. If {@code iterable} contains fewer than * {@code numberToSkip} elements, the returned iterable skips all of its * elements. * * <p>Modifications to the underlying {@link Iterable} before a call to * {@code iterator()} are reflected in the returned iterator. That is, the * iterator skips the first {@code numberToSkip} elements that exist when the * {@code Iterator} is created, not when {@code skip()} is called. * * <p>The returned iterable's iterator supports {@code remove()} if the * iterator of the underlying iterable supports it. Note that it is * <i>not</i> possible to delete the last skipped element by immediately * calling {@code remove()} on that iterator, as the {@code Iterator} * contract states that a call to {@code remove()} before a call to * {@code next()} will throw an {@link IllegalStateException}. * * @since 3.0 */ public static <T> Iterable<T> skip(final Iterable<T> iterable, final int numberToSkip) { checkNotNull(iterable); checkArgument(numberToSkip >= 0, "number to skip cannot be negative"); if (iterable instanceof List) { final List<T> list = (List<T>) iterable; return new IterableWithToString<T>() { @Override public Iterator<T> iterator() { // TODO(kevinb): Support a concurrently modified collection? return (numberToSkip >= list.size()) ? Iterators.<T>emptyIterator() : list.subList(numberToSkip, list.size()).iterator(); } }; } return new IterableWithToString<T>() { @Override public Iterator<T> iterator() { final Iterator<T> iterator = iterable.iterator(); Iterators.skip(iterator, numberToSkip); /* * We can't just return the iterator because an immediate call to its * remove() method would remove one of the skipped elements instead of * throwing an IllegalStateException. */ return new Iterator<T>() { boolean atStart = true; @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } try { return iterator.next(); } finally { atStart = false; } } @Override public void remove() { if (atStart) { throw new IllegalStateException(); } iterator.remove(); } }; } }; } /** * Creates an iterable with the first {@code limitSize} elements of the given * iterable. If the original iterable does not contain that many elements, the * returned iterator will have the same behavior as the original iterable. The * returned iterable's iterator supports {@code remove()} if the original * iterator does. * * @param iterable the iterable to limit * @param limitSize the maximum number of elements in the returned iterator * @throws IllegalArgumentException if {@code limitSize} is negative * @since 3.0 */ public static <T> Iterable<T> limit( final Iterable<T> iterable, final int limitSize) { checkNotNull(iterable); checkArgument(limitSize >= 0, "limit is negative"); return new IterableWithToString<T>() { @Override public Iterator<T> iterator() { return Iterators.limit(iterable.iterator(), limitSize); } }; } /** * Returns a view of the supplied iterable that wraps each generated * {@link Iterator} through {@link Iterators#consumingIterator(Iterator)}. * * <p>Note: If {@code iterable} is a {@link Queue}, the returned iterable will * get entries from {@link Queue#remove()} since {@link Queue}'s iteration * order is undefined. Calling {@link Iterator#hasNext()} on a generated * iterator from the returned iterable may cause an item to be immediately * dequeued for return on a subsequent call to {@link Iterator#next()}. * * @param iterable the iterable to wrap * @return a view of the supplied iterable that wraps each generated iterator * through {@link Iterators#consumingIterator(Iterator)}; for queues, * an iterable that generates iterators that return and consume the * queue's elements in queue order * * @see Iterators#consumingIterator(Iterator) * @since 2.0 */ public static <T> Iterable<T> consumingIterable(final Iterable<T> iterable) { if (iterable instanceof Queue) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new ConsumingQueueIterator<T>((Queue<T>) iterable); } }; } checkNotNull(iterable); return new Iterable<T>() { @Override public Iterator<T> iterator() { return Iterators.consumingIterator(iterable.iterator()); } }; } private static class ConsumingQueueIterator<T> extends AbstractIterator<T> { private final Queue<T> queue; private ConsumingQueueIterator(Queue<T> queue) { this.queue = queue; } @Override public T computeNext() { try { return queue.remove(); } catch (NoSuchElementException e) { return endOfData(); } } } // Methods only in Iterables, not in Iterators /** * Adapts a list to an iterable with reversed iteration order. It is * especially useful in foreach-style loops: <pre> {@code * * List<String> mylist = ... * for (String str : Iterables.reverse(mylist)) { * ... * }}</pre> * * There is no corresponding method in {@link Iterators}, since {@link * Iterable#iterator} can simply be invoked on the result of calling this * method. * * @return an iterable with the same elements as the list, in reverse * * @deprecated use {@link Lists#reverse(List)} or {@link * ImmutableList#reverse()}. <b>This method is scheduled for deletion in * July 2012.</b> */ @Deprecated public static <T> Iterable<T> reverse(final List<T> list) { return Lists.reverse(list); } /** * Determines if the given iterable contains no elements. * * <p>There is no precise {@link Iterator} equivalent to this method, since * one can only ask an iterator whether it has any elements <i>remaining</i> * (which one does using {@link Iterator#hasNext}). * * @return {@code true} if the iterable contains no elements */ public static boolean isEmpty(Iterable<?> iterable) { if (iterable instanceof Collection) { return ((Collection<?>) iterable).isEmpty(); } return !iterable.iterator().hasNext(); } // Non-public /** * Removes the specified element from the specified iterable. * * <p>This method iterates over the iterable, checking each element returned * by the iterator in turn to see if it equals the object {@code o}. If they * are equal, it is removed from the iterable with the iterator's * {@code remove} method. At most one element is removed, even if the iterable * contains multiple members that equal {@code o}. * * <p><b>Warning:</b> Do not use this method for a collection, such as a * {@link HashSet}, that has a fast {@code remove} method. * * @param iterable the iterable from which to remove * @param o an element to remove from the collection * @return {@code true} if the iterable changed as a result * @throws UnsupportedOperationException if the iterator does not support the * {@code remove} method and the iterable contains the object */ static boolean remove(Iterable<?> iterable, @Nullable Object o) { Iterator<?> i = iterable.iterator(); while (i.hasNext()) { if (Objects.equal(i.next(), o)) { i.remove(); return true; } } return false; } abstract static class IterableWithToString<E> implements Iterable<E> { @Override public String toString() { return Iterables.toString(this); } } /** * Returns an iterable over the merged contents of all given * {@code iterables}. Equivalent entries will not be de-duplicated. * * <p>Callers must ensure that the source {@code iterables} are in * non-descending order as this method does not sort its input. * * <p>For any equivalent elements across all {@code iterables}, it is * undefined which element is returned first. * * @since 11.0 */ @Beta public static <T> Iterable<T> mergeSorted( final Iterable<? extends Iterable<? extends T>> iterables, final Comparator<? super T> comparator) { checkNotNull(iterables, "iterables"); checkNotNull(comparator, "comparator"); Iterable<T> iterable = new Iterable<T>() { @Override public Iterator<T> iterator() { return Iterators.mergeSorted( Iterables.transform(iterables, Iterables.<T>toIterator()), comparator); } }; return new UnmodifiableIterable<T>(iterable); } // TODO(user): Is this the best place for this? Move to fluent functions? // Useful as a public method? private static <T> Function<Iterable<? extends T>, Iterator<? extends T>> toIterator() { return new Function<Iterable<? extends T>, Iterator<? extends T>>() { @Override public Iterator<? extends T> apply(Iterable<? extends T> iterable) { return iterable.iterator(); } }; } }
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.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Collections2.FilteredCollection; import com.google.common.math.IntMath; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.AbstractSet; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.Nullable; /** * Static utility methods pertaining to {@link Set} instances. Also see this * class's counterparts {@link Lists} and {@link Maps}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Sets"> * {@code Sets}</a>. * * @author Kevin Bourrillion * @author Jared Levy * @author Chris Povirk * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class Sets { private Sets() {} /** * Returns an immutable set instance containing the given enum elements. * Internally, the returned set will be backed by an {@link EnumSet}. * * <p>The iteration order of the returned set follows the enum's iteration * order, not the order in which the elements are provided to the method. * * @param anElement one of the elements the set should contain * @param otherElements the rest of the elements the set should contain * @return an immutable set containing those elements, minus duplicates */ // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028 @GwtCompatible(serializable = true) public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet( E anElement, E... otherElements) { return new ImmutableEnumSet<E>(EnumSet.of(anElement, otherElements)); } /** * Returns an immutable set instance containing the given enum elements. * Internally, the returned set will be backed by an {@link EnumSet}. * * <p>The iteration order of the returned set follows the enum's iteration * order, not the order in which the elements appear in the given collection. * * @param elements the elements, all of the same {@code enum} type, that the * set should contain * @return an immutable set containing those elements, minus duplicates */ // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028 @GwtCompatible(serializable = true) public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet( Iterable<E> elements) { Iterator<E> iterator = elements.iterator(); if (!iterator.hasNext()) { return ImmutableSet.of(); } if (elements instanceof EnumSet) { EnumSet<E> enumSetClone = EnumSet.copyOf((EnumSet<E>) elements); return new ImmutableEnumSet<E>(enumSetClone); } E first = iterator.next(); EnumSet<E> set = EnumSet.of(first); while (iterator.hasNext()) { set.add(iterator.next()); } return new ImmutableEnumSet<E>(set); } /** * Returns a new {@code EnumSet} instance containing the given elements. * Unlike {@link EnumSet#copyOf(Collection)}, this method does not produce an * exception on an empty collection, and it may be called on any iterable, not * just a {@code Collection}. */ public static <E extends Enum<E>> EnumSet<E> newEnumSet(Iterable<E> iterable, Class<E> elementType) { /* * TODO(cpovirk): noneOf() and addAll() will both throw * NullPointerExceptions when appropriate. However, NullPointerTester will * fail on this method because it passes in Class.class instead of an enum * type. This means that, when iterable is null but elementType is not, * noneOf() will throw a ClassCastException before addAll() has a chance to * throw a NullPointerException. NullPointerTester considers this a failure. * Ideally the test would be fixed, but it would require a special case for * Class<E> where E extends Enum. Until that happens (if ever), leave * checkNotNull() here. For now, contemplate the irony that checking * elementType, the problem argument, is harmful, while checking iterable, * the innocent bystander, is effective. */ checkNotNull(iterable); EnumSet<E> set = EnumSet.noneOf(elementType); Iterables.addAll(set, iterable); return set; } // HashSet /** * Creates a <i>mutable</i>, empty {@code HashSet} instance. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableSet#of()} instead. * * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link * EnumSet#noneOf} instead. * * @return a new, empty {@code HashSet} */ public static <E> HashSet<E> newHashSet() { return new HashSet<E>(); } /** * Creates a <i>mutable</i> {@code HashSet} instance containing the given * elements in unspecified order. * * <p><b>Note:</b> if mutability is not required and the elements are * non-null, use an overload of {@link ImmutableSet#of()} (for varargs) or * {@link ImmutableSet#copyOf(Object[])} (for an array) instead. * * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link * EnumSet#of(Enum, Enum[])} instead. * * @param elements the elements that the set should contain * @return a new {@code HashSet} containing those elements (minus duplicates) */ public static <E> HashSet<E> newHashSet(E... elements) { HashSet<E> set = newHashSetWithExpectedSize(elements.length); Collections.addAll(set, elements); return set; } /** * Creates a {@code HashSet} instance, with a high enough "initial capacity" * that it <i>should</i> hold {@code expectedSize} elements without growth. * This behavior cannot be broadly guaranteed, but it is observed to be true * for OpenJDK 1.6. It also can't be guaranteed that the method isn't * inadvertently <i>oversizing</i> the returned set. * * @param expectedSize the number of elements you expect to add to the * returned set * @return a new, empty {@code HashSet} with enough capacity to hold {@code * expectedSize} elements without resizing * @throws IllegalArgumentException if {@code expectedSize} is negative */ public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize) { return new HashSet<E>(Maps.capacity(expectedSize)); } /** * Creates a <i>mutable</i> {@code HashSet} instance containing the given * elements in unspecified order. * * <p><b>Note:</b> if mutability is not required and the elements are * non-null, use {@link ImmutableSet#copyOf(Iterable)} instead. * * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use * {@link #newEnumSet(Iterable, Class)} instead. * * @param elements the elements that the set should contain * @return a new {@code HashSet} containing those elements (minus duplicates) */ public static <E> HashSet<E> newHashSet(Iterable<? extends E> elements) { return (elements instanceof Collection) ? new HashSet<E>(Collections2.cast(elements)) : newHashSet(elements.iterator()); } /** * Creates a <i>mutable</i> {@code HashSet} instance containing the given * elements in unspecified order. * * <p><b>Note:</b> if mutability is not required and the elements are * non-null, use {@link ImmutableSet#copyOf(Iterable)} instead. * * <p><b>Note:</b> if {@code E} is an {@link Enum} type, you should create an * {@link EnumSet} instead. * * @param elements the elements that the set should contain * @return a new {@code HashSet} containing those elements (minus duplicates) */ public static <E> HashSet<E> newHashSet(Iterator<? extends E> elements) { HashSet<E> set = newHashSet(); while (elements.hasNext()) { set.add(elements.next()); } return set; } // LinkedHashSet /** * Creates a <i>mutable</i>, empty {@code LinkedHashSet} instance. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableSet#of()} instead. * * @return a new, empty {@code LinkedHashSet} */ public static <E> LinkedHashSet<E> newLinkedHashSet() { return new LinkedHashSet<E>(); } /** * Creates a {@code LinkedHashSet} instance, with a high enough "initial * capacity" that it <i>should</i> hold {@code expectedSize} elements without * growth. This behavior cannot be broadly guaranteed, but it is observed to * be true for OpenJDK 1.6. It also can't be guaranteed that the method isn't * inadvertently <i>oversizing</i> the returned set. * * @param expectedSize the number of elements you expect to add to the * returned set * @return a new, empty {@code LinkedHashSet} with enough capacity to hold * {@code expectedSize} elements without resizing * @throws IllegalArgumentException if {@code expectedSize} is negative * @since 11.0 */ public static <E> LinkedHashSet<E> newLinkedHashSetWithExpectedSize( int expectedSize) { return new LinkedHashSet<E>(Maps.capacity(expectedSize)); } /** * Creates a <i>mutable</i> {@code LinkedHashSet} instance containing the * given elements in order. * * <p><b>Note:</b> if mutability is not required and the elements are * non-null, use {@link ImmutableSet#copyOf(Iterable)} instead. * * @param elements the elements that the set should contain, in order * @return a new {@code LinkedHashSet} containing those elements (minus * duplicates) */ public static <E> LinkedHashSet<E> newLinkedHashSet( Iterable<? extends E> elements) { if (elements instanceof Collection) { return new LinkedHashSet<E>(Collections2.cast(elements)); } LinkedHashSet<E> set = newLinkedHashSet(); for (E element : elements) { set.add(element); } return set; } // TreeSet /** * Creates a <i>mutable</i>, empty {@code TreeSet} instance sorted by the * natural sort ordering of its elements. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableSortedSet#of()} instead. * * @return a new, empty {@code TreeSet} */ public static <E extends Comparable> TreeSet<E> newTreeSet() { return new TreeSet<E>(); } /** * Creates a <i>mutable</i> {@code TreeSet} instance containing the given * elements sorted by their natural ordering. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableSortedSet#copyOf(Iterable)} instead. * * <p><b>Note:</b> If {@code elements} is a {@code SortedSet} with an explicit * comparator, this method has different behavior than * {@link TreeSet#TreeSet(SortedSet)}, which returns a {@code TreeSet} with * that comparator. * * @param elements the elements that the set should contain * @return a new {@code TreeSet} containing those elements (minus duplicates) */ public static <E extends Comparable> TreeSet<E> newTreeSet( Iterable<? extends E> elements) { TreeSet<E> set = newTreeSet(); for (E element : elements) { set.add(element); } return set; } /** * Creates a <i>mutable</i>, empty {@code TreeSet} instance with the given * comparator. * * <p><b>Note:</b> if mutability is not required, use {@code * ImmutableSortedSet.orderedBy(comparator).build()} instead. * * @param comparator the comparator to use to sort the set * @return a new, empty {@code TreeSet} * @throws NullPointerException if {@code comparator} is null */ public static <E> TreeSet<E> newTreeSet(Comparator<? super E> comparator) { return new TreeSet<E>(checkNotNull(comparator)); } /** * Creates an empty {@code Set} that uses identity to determine equality. It * compares object references, instead of calling {@code equals}, to * determine whether a provided object matches an element in the set. For * example, {@code contains} returns {@code false} when passed an object that * equals a set member, but isn't the same instance. This behavior is similar * to the way {@code IdentityHashMap} handles key lookups. * * @since 8.0 */ public static <E> Set<E> newIdentityHashSet() { return Sets.newSetFromMap(Maps.<E, Boolean>newIdentityHashMap()); } /** * Creates an {@code EnumSet} consisting of all enum values that are not in * the specified collection. If the collection is an {@link EnumSet}, this * method has the same behavior as {@link EnumSet#complementOf}. Otherwise, * the specified collection must contain at least one element, in order to * determine the element type. If the collection could be empty, use * {@link #complementOf(Collection, Class)} instead of this method. * * @param collection the collection whose complement should be stored in the * enum set * @return a new, modifiable {@code EnumSet} containing all values of the enum * that aren't present in the given collection * @throws IllegalArgumentException if {@code collection} is not an * {@code EnumSet} instance and contains no elements */ public static <E extends Enum<E>> EnumSet<E> complementOf( Collection<E> collection) { if (collection instanceof EnumSet) { return EnumSet.complementOf((EnumSet<E>) collection); } checkArgument(!collection.isEmpty(), "collection is empty; use the other version of this method"); Class<E> type = collection.iterator().next().getDeclaringClass(); return makeComplementByHand(collection, type); } /** * Creates an {@code EnumSet} consisting of all enum values that are not in * the specified collection. This is equivalent to * {@link EnumSet#complementOf}, but can act on any input collection, as long * as the elements are of enum type. * * @param collection the collection whose complement should be stored in the * {@code EnumSet} * @param type the type of the elements in the set * @return a new, modifiable {@code EnumSet} initially containing all the * values of the enum not present in the given collection */ public static <E extends Enum<E>> EnumSet<E> complementOf( Collection<E> collection, Class<E> type) { checkNotNull(collection); return (collection instanceof EnumSet) ? EnumSet.complementOf((EnumSet<E>) collection) : makeComplementByHand(collection, type); } private static <E extends Enum<E>> EnumSet<E> makeComplementByHand( Collection<E> collection, Class<E> type) { EnumSet<E> result = EnumSet.allOf(type); result.removeAll(collection); return result; } /* * Regarding newSetForMap() and SetFromMap: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ /** * Returns a set backed by the specified map. The resulting set displays * the same ordering, concurrency, and performance characteristics as the * backing map. In essence, this factory method provides a {@link Set} * implementation corresponding to any {@link Map} implementation. There is no * need to use this method on a {@link Map} implementation that already has a * corresponding {@link Set} implementation (such as {@link java.util.HashMap} * or {@link java.util.TreeMap}). * * <p>Each method invocation on the set returned by this method results in * exactly one method invocation on the backing map or its {@code keySet} * view, with one exception. The {@code addAll} method is implemented as a * sequence of {@code put} invocations on the backing map. * * <p>The specified map must be empty at the time this method is invoked, * and should not be accessed directly after this method returns. These * conditions are ensured if the map is created empty, passed directly * to this method, and no reference to the map is retained, as illustrated * in the following code fragment: <pre> {@code * * Set<Object> identityHashSet = Sets.newSetFromMap( * new IdentityHashMap<Object, Boolean>());}</pre> * * This method has the same behavior as the JDK 6 method * {@code Collections.newSetFromMap()}. The returned set is serializable if * the backing map is. * * @param map the backing map * @return the set backed by the map * @throws IllegalArgumentException if {@code map} is not empty */ public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) { return new SetFromMap<E>(map); } private static class SetFromMap<E> extends AbstractSet<E> implements Set<E>, Serializable { private final Map<E, Boolean> m; // The backing map private transient Set<E> s; // Its keySet SetFromMap(Map<E, Boolean> map) { checkArgument(map.isEmpty(), "Map is non-empty"); m = map; s = map.keySet(); } @Override public void clear() { m.clear(); } @Override public int size() { return m.size(); } @Override public boolean isEmpty() { return m.isEmpty(); } @Override public boolean contains(Object o) { return m.containsKey(o); } @Override public boolean remove(Object o) { return m.remove(o) != null; } @Override public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; } @Override public Iterator<E> iterator() { return s.iterator(); } @Override public Object[] toArray() { return s.toArray(); } @Override public <T> T[] toArray(T[] a) { return s.toArray(a); } @Override public String toString() { return s.toString(); } @Override public int hashCode() { return s.hashCode(); } @Override public boolean equals(@Nullable Object object) { return this == object || this.s.equals(object); } @Override public boolean containsAll(Collection<?> c) { return s.containsAll(c); } @Override public boolean removeAll(Collection<?> c) { return s.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return s.retainAll(c); } // addAll is the only inherited implementation @GwtIncompatible("not needed in emulated source") private static final long serialVersionUID = 0; @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); s = m.keySet(); } } /** * An unmodifiable view of a set which may be backed by other sets; this view * will change as the backing sets do. Contains methods to copy the data into * a new set which will then remain stable. There is usually no reason to * retain a reference of type {@code SetView}; typically, you either use it * as a plain {@link Set}, or immediately invoke {@link #immutableCopy} or * {@link #copyInto} and forget the {@code SetView} itself. * * @since 2.0 (imported from Google Collections Library) */ public abstract static class SetView<E> extends AbstractSet<E> { private SetView() {} // no subclasses but our own /** * Returns an immutable copy of the current contents of this set view. * Does not support null elements. * * <p><b>Warning:</b> this may have unexpected results if a backing set of * this view uses a nonstandard notion of equivalence, for example if it is * a {@link TreeSet} using a comparator that is inconsistent with {@link * Object#equals(Object)}. */ public ImmutableSet<E> immutableCopy() { return ImmutableSet.copyOf(this); } /** * Copies the current contents of this set view into an existing set. This * method has equivalent behavior to {@code set.addAll(this)}, assuming that * all the sets involved are based on the same notion of equivalence. * * @return a reference to {@code set}, for convenience */ // Note: S should logically extend Set<? super E> but can't due to either // some javac bug or some weirdness in the spec, not sure which. public <S extends Set<E>> S copyInto(S set) { set.addAll(this); return set; } } /** * Returns an unmodifiable <b>view</b> of the union of two sets. The returned * set contains all elements that are contained in either backing set. * Iterating over the returned set iterates first over all the elements of * {@code set1}, then over each element of {@code set2}, in order, that is not * contained in {@code set1}. * * <p>Results are undefined if {@code set1} and {@code set2} are sets based on * different equivalence relations (as {@link HashSet}, {@link TreeSet}, and * the {@link Map#keySet} of an {@code IdentityHashMap} all are). * * <p><b>Note:</b> The returned view performs better when {@code set1} is the * smaller of the two sets. If you have reason to believe one of your sets * will generally be smaller than the other, pass it first. */ public static <E> SetView<E> union( final Set<? extends E> set1, final Set<? extends E> set2) { checkNotNull(set1, "set1"); checkNotNull(set2, "set2"); final Set<? extends E> set2minus1 = difference(set2, set1); return new SetView<E>() { @Override public int size() { return set1.size() + set2minus1.size(); } @Override public boolean isEmpty() { return set1.isEmpty() && set2.isEmpty(); } @Override public Iterator<E> iterator() { return Iterators.unmodifiableIterator( Iterators.concat(set1.iterator(), set2minus1.iterator())); } @Override public boolean contains(Object object) { return set1.contains(object) || set2.contains(object); } @Override public <S extends Set<E>> S copyInto(S set) { set.addAll(set1); set.addAll(set2); return set; } @Override public ImmutableSet<E> immutableCopy() { return new ImmutableSet.Builder<E>() .addAll(set1).addAll(set2).build(); } }; } /** * Returns an unmodifiable <b>view</b> of the intersection of two sets. The * returned set contains all elements that are contained by both backing sets. * The iteration order of the returned set matches that of {@code set1}. * * <p>Results are undefined if {@code set1} and {@code set2} are sets based * on different equivalence relations (as {@code HashSet}, {@code TreeSet}, * and the keySet of an {@code IdentityHashMap} all are). * * <p><b>Note:</b> The returned view performs slightly better when {@code * set1} is the smaller of the two sets. If you have reason to believe one of * your sets will generally be smaller than the other, pass it first. * Unfortunately, since this method sets the generic type of the returned set * based on the type of the first set passed, this could in rare cases force * you to make a cast, for example: <pre> {@code * * Set<Object> aFewBadObjects = ... * Set<String> manyBadStrings = ... * * // impossible for a non-String to be in the intersection * SuppressWarnings("unchecked") * Set<String> badStrings = (Set) Sets.intersection( * aFewBadObjects, manyBadStrings);}</pre> * * This is unfortunate, but should come up only very rarely. */ public static <E> SetView<E> intersection( final Set<E> set1, final Set<?> set2) { checkNotNull(set1, "set1"); checkNotNull(set2, "set2"); final Predicate<Object> inSet2 = Predicates.in(set2); return new SetView<E>() { @Override public Iterator<E> iterator() { return Iterators.filter(set1.iterator(), inSet2); } @Override public int size() { return Iterators.size(iterator()); } @Override public boolean isEmpty() { return !iterator().hasNext(); } @Override public boolean contains(Object object) { return set1.contains(object) && set2.contains(object); } @Override public boolean containsAll(Collection<?> collection) { return set1.containsAll(collection) && set2.containsAll(collection); } }; } /** * Returns an unmodifiable <b>view</b> of the difference of two sets. The * returned set contains all elements that are contained by {@code set1} and * not contained by {@code set2}. {@code set2} may also contain elements not * present in {@code set1}; these are simply ignored. The iteration order of * the returned set matches that of {@code set1}. * * <p>Results are undefined if {@code set1} and {@code set2} are sets based * on different equivalence relations (as {@code HashSet}, {@code TreeSet}, * and the keySet of an {@code IdentityHashMap} all are). */ public static <E> SetView<E> difference( final Set<E> set1, final Set<?> set2) { checkNotNull(set1, "set1"); checkNotNull(set2, "set2"); final Predicate<Object> notInSet2 = Predicates.not(Predicates.in(set2)); return new SetView<E>() { @Override public Iterator<E> iterator() { return Iterators.filter(set1.iterator(), notInSet2); } @Override public int size() { return Iterators.size(iterator()); } @Override public boolean isEmpty() { return set2.containsAll(set1); } @Override public boolean contains(Object element) { return set1.contains(element) && !set2.contains(element); } }; } /** * Returns an unmodifiable <b>view</b> of the symmetric difference of two * sets. The returned set contains all elements that are contained in either * {@code set1} or {@code set2} but not in both. The iteration order of the * returned set is undefined. * * <p>Results are undefined if {@code set1} and {@code set2} are sets based * on different equivalence relations (as {@code HashSet}, {@code TreeSet}, * and the keySet of an {@code IdentityHashMap} all are). * * @since 3.0 */ public static <E> SetView<E> symmetricDifference( Set<? extends E> set1, Set<? extends E> set2) { checkNotNull(set1, "set1"); checkNotNull(set2, "set2"); // TODO(kevinb): Replace this with a more efficient implementation return difference(union(set1, set2), intersection(set1, set2)); } /** * Returns the elements of {@code unfiltered} that satisfy a predicate. The * returned set is a live view of {@code unfiltered}; changes to one affect * the other. * * <p>The resulting set's iterator does not support {@code remove()}, but all * other set methods are supported. When given an element that doesn't satisfy * the predicate, the set's {@code add()} and {@code addAll()} methods throw * an {@link IllegalArgumentException}. When methods such as {@code * removeAll()} and {@code clear()} are called on the filtered set, only * elements that satisfy the filter will be removed from the underlying set. * * <p>The returned set isn't threadsafe or serializable, even if * {@code unfiltered} is. * * <p>Many of the filtered set's methods, such as {@code size()}, iterate * across every element in the underlying set and determine which elements * satisfy the filter. When a live view is <i>not</i> needed, it may be faster * to copy {@code Iterables.filter(unfiltered, predicate)} and use the copy. * * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, * as documented at {@link Predicate#apply}. Do not provide a predicate such * as {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent * with equals. (See {@link Iterables#filter(Iterable, Class)} for related * functionality.) */ // TODO(kevinb): how to omit that last sentence when building GWT javadoc? public static <E> Set<E> filter( Set<E> unfiltered, Predicate<? super E> predicate) { if (unfiltered instanceof SortedSet) { return filter((SortedSet<E>) unfiltered, predicate); } if (unfiltered instanceof FilteredSet) { // Support clear(), removeAll(), and retainAll() when filtering a filtered // collection. FilteredSet<E> filtered = (FilteredSet<E>) unfiltered; Predicate<E> combinedPredicate = Predicates.<E>and(filtered.predicate, predicate); return new FilteredSet<E>( (Set<E>) filtered.unfiltered, combinedPredicate); } return new FilteredSet<E>( checkNotNull(unfiltered), checkNotNull(predicate)); } private static class FilteredSet<E> extends FilteredCollection<E> implements Set<E> { FilteredSet(Set<E> unfiltered, Predicate<? super E> predicate) { super(unfiltered, predicate); } @Override public boolean equals(@Nullable Object object) { return equalsImpl(this, object); } @Override public int hashCode() { return hashCodeImpl(this); } } /** * Returns the elements of a {@code SortedSet}, {@code unfiltered}, that * satisfy a predicate. The returned set is a live view of {@code unfiltered}; * changes to one affect the other. * * <p>The resulting set's iterator does not support {@code remove()}, but all * other set methods are supported. When given an element that doesn't satisfy * the predicate, the set's {@code add()} and {@code addAll()} methods throw * an {@link IllegalArgumentException}. When methods such as * {@code removeAll()} and {@code clear()} are called on the filtered set, * only elements that satisfy the filter will be removed from the underlying * set. * * <p>The returned set isn't threadsafe or serializable, even if * {@code unfiltered} is. * * <p>Many of the filtered set's methods, such as {@code size()}, iterate across * every element in the underlying set and determine which elements satisfy * the filter. When a live view is <i>not</i> needed, it may be faster to copy * {@code Iterables.filter(unfiltered, predicate)} and use the copy. * * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, * as documented at {@link Predicate#apply}. Do not provide a predicate such as * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with * equals. (See {@link Iterables#filter(Iterable, Class)} for related * functionality.) * * @since 11.0 */ @Beta @SuppressWarnings("unchecked") public static <E> SortedSet<E> filter( SortedSet<E> unfiltered, Predicate<? super E> predicate) { if (unfiltered instanceof FilteredSet) { // Support clear(), removeAll(), and retainAll() when filtering a filtered // collection. FilteredSet<E> filtered = (FilteredSet<E>) unfiltered; Predicate<E> combinedPredicate = Predicates.<E>and(filtered.predicate, predicate); return new FilteredSortedSet<E>( (SortedSet<E>) filtered.unfiltered, combinedPredicate); } return new FilteredSortedSet<E>( checkNotNull(unfiltered), checkNotNull(predicate)); } private static class FilteredSortedSet<E> extends FilteredCollection<E> implements SortedSet<E> { FilteredSortedSet(SortedSet<E> unfiltered, Predicate<? super E> predicate) { super(unfiltered, predicate); } @Override public boolean equals(@Nullable Object object) { return equalsImpl(this, object); } @Override public int hashCode() { return hashCodeImpl(this); } @Override public Comparator<? super E> comparator() { return ((SortedSet<E>) unfiltered).comparator(); } @Override public SortedSet<E> subSet(E fromElement, E toElement) { return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).subSet(fromElement, toElement), predicate); } @Override public SortedSet<E> headSet(E toElement) { return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).headSet(toElement), predicate); } @Override public SortedSet<E> tailSet(E fromElement) { return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).tailSet(fromElement), predicate); } @Override public E first() { return iterator().next(); } @Override public E last() { SortedSet<E> sortedUnfiltered = (SortedSet<E>) unfiltered; while (true) { E element = sortedUnfiltered.last(); if (predicate.apply(element)) { return element; } sortedUnfiltered = sortedUnfiltered.headSet(element); } } } /** * Returns every possible list that can be formed by choosing one element * from each of the given sets in order; the "n-ary * <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian * product</a>" of the sets. For example: <pre> {@code * * Sets.cartesianProduct(ImmutableList.of( * ImmutableSet.of(1, 2), * ImmutableSet.of("A", "B", "C")))}</pre> * * returns a set containing six lists: * * <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> * * The order in which these lists are returned is not guaranteed, however the * position of an element inside a tuple always corresponds to the position of * the set from which it came in the input list. Note that if any input set is * empty, the Cartesian product will also be empty. If no sets 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 sets of size * {@code m, n, p} is a set of size {@code m x n x p}, its actual memory * consumption is much smaller. When the cartesian set is constructed, the * input sets are merely copied. Only as the resulting set is iterated are the * individual lists created, and these are not retained after iteration. * * @param sets the sets to choose elements from, in the order that * the elements chosen from those sets 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 set containing immutable * lists * @throws NullPointerException if {@code sets}, any one of the {@code sets}, * or any element of a provided set is null * @since 2.0 */ public static <B> Set<List<B>> cartesianProduct( List<? extends Set<? extends B>> sets) { for (Set<? extends B> set : sets) { if (set.isEmpty()) { return ImmutableSet.of(); } } CartesianSet<B> cartesianSet = new CartesianSet<B>(sets); return cartesianSet; } /** * Returns every possible list that can be formed by choosing one element * from each of the given sets in order; the "n-ary * <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian * product</a>" of the sets. For example: <pre> {@code * * Sets.cartesianProduct( * ImmutableSet.of(1, 2), * ImmutableSet.of("A", "B", "C"))}</pre> * * returns a set containing six lists: * * <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> * * The order in which these lists are returned is not guaranteed, however the * position of an element inside a tuple always corresponds to the position of * the set from which it came in the input list. Note that if any input set is * empty, the Cartesian product will also be empty. If no sets at all are * provided, 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 sets of size * {@code m, n, p} is a set of size {@code m x n x p}, its actual memory * consumption is much smaller. When the cartesian set is constructed, the * input sets are merely copied. Only as the resulting set is iterated are the * individual lists created, and these are not retained after iteration. * * @param sets the sets to choose elements from, in the order that * the elements chosen from those sets 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 set containing immutable * lists * @throws NullPointerException if {@code sets}, any one of the {@code sets}, * or any element of a provided set is null * @since 2.0 */ public static <B> Set<List<B>> cartesianProduct( Set<? extends B>... sets) { return cartesianProduct(Arrays.asList(sets)); } private static class CartesianSet<B> extends AbstractSet<List<B>> { final ImmutableList<Axis> axes; final int size; CartesianSet(List<? extends Set<? extends B>> sets) { int dividend = 1; ImmutableList.Builder<Axis> builder = ImmutableList.builder(); try { for (Set<? extends B> set : sets) { Axis axis = new Axis(set, dividend); builder.add(axis); dividend = IntMath.checkedMultiply(dividend, axis.size()); } } catch (ArithmeticException overflow) { throw new IllegalArgumentException("cartesian product too big"); } this.axes = builder.build(); size = dividend; } @Override public int size() { return size; } @Override public UnmodifiableIterator<List<B>> iterator() { return new UnmodifiableIterator<List<B>>() { int index; @Override public boolean hasNext() { return index < size; } @Override public List<B> next() { if (!hasNext()) { throw new NoSuchElementException(); } Object[] tuple = new Object[axes.size()]; for (int i = 0 ; i < tuple.length; i++) { tuple[i] = axes.get(i).getForIndex(index); } index++; @SuppressWarnings("unchecked") // only B's are put in here List<B> result = (ImmutableList<B>) ImmutableList.copyOf(tuple); return result; } }; } @Override public boolean contains(Object element) { if (!(element instanceof List<?>)) { return false; } List<?> tuple = (List<?>) element; int dimensions = axes.size(); if (tuple.size() != dimensions) { return false; } for (int i = 0; i < dimensions; i++) { if (!axes.get(i).contains(tuple.get(i))) { return false; } } return true; } @Override public boolean equals(@Nullable Object object) { // Warning: this is broken if size() == 0, so it is critical that we // substitute an empty ImmutableSet to the user in place of this if (object instanceof CartesianSet) { CartesianSet<?> that = (CartesianSet<?>) object; return this.axes.equals(that.axes); } return super.equals(object); } @Override public int hashCode() { // Warning: this is broken if size() == 0, so it is critical that we // substitute an empty ImmutableSet to the user in place of this // It's a weird formula, but tests prove it works. int adjust = size - 1; for (int i = 0; i < axes.size(); i++) { adjust *= 31; } return axes.hashCode() + adjust; } private class Axis { final ImmutableSet<? extends B> choices; final ImmutableList<? extends B> choicesList; final int dividend; Axis(Set<? extends B> set, int dividend) { choices = ImmutableSet.copyOf(set); choicesList = choices.asList(); this.dividend = dividend; } int size() { return choices.size(); } B getForIndex(int index) { return choicesList.get(index / dividend % size()); } boolean contains(Object target) { return choices.contains(target); } @Override public boolean equals(Object obj) { if (obj instanceof CartesianSet.Axis) { CartesianSet.Axis that = (CartesianSet.Axis) obj; return this.choices.equals(that.choices); // dividends must be equal or we wouldn't have gotten this far } return false; } @Override public int hashCode() { // Because Axis instances are not exposed, we can // opportunistically choose whatever bizarre formula happens // to make CartesianSet.hashCode() as simple as possible. return size / choices.size() * choices.hashCode(); } } } /** * Returns the set of all possible subsets of {@code set}. For example, * {@code powerSet(ImmutableSet.of(1, 2))} returns the set {@code {{}, * {1}, {2}, {1, 2}}}. * * <p>Elements appear in these subsets in the same iteration order as they * appeared in the input set. The order in which these subsets appear in the * outer set is undefined. Note that the power set of the empty set is not the * empty set, but a one-element set containing the empty set. * * <p>The returned set and its constituent sets use {@code equals} to decide * whether two elements are identical, even if the input set uses a different * concept of equivalence. * * <p><i>Performance notes:</i> while the power set of a set with size {@code * n} is of size {@code 2^n}, its memory usage is only {@code O(n)}. When the * power set is constructed, the input set is merely copied. Only as the * power set is iterated are the individual subsets created, and these subsets * themselves occupy only a few bytes of memory regardless of their size. * * @param set the set of elements to construct a power set from * @return the power set, as an immutable set of immutable sets * @throws IllegalArgumentException if {@code set} has more than 30 unique * elements (causing the power set size to exceed the {@code int} range) * @throws NullPointerException if {@code set} is or contains {@code null} * @see <a href="http://en.wikipedia.org/wiki/Power_set">Power set article at * Wikipedia</a> * @since 4.0 */ @GwtCompatible(serializable = false) public static <E> Set<Set<E>> powerSet(Set<E> set) { ImmutableSet<E> input = ImmutableSet.copyOf(set); checkArgument(input.size() <= 30, "Too many elements to create power set: %s > 30", input.size()); return new PowerSet<E>(input); } private static final class PowerSet<E> extends AbstractSet<Set<E>> { final ImmutableSet<E> inputSet; final ImmutableList<E> inputList; final int powerSetSize; PowerSet(ImmutableSet<E> input) { this.inputSet = input; this.inputList = input.asList(); this.powerSetSize = 1 << input.size(); } @Override public int size() { return powerSetSize; } @Override public boolean isEmpty() { return false; } @Override public Iterator<Set<E>> iterator() { return new AbstractIndexedListIterator<Set<E>>(powerSetSize) { @Override protected Set<E> get(final int setBits) { return new AbstractSet<E>() { @Override public int size() { return Integer.bitCount(setBits); } @Override public Iterator<E> iterator() { return new BitFilteredSetIterator<E>(inputList, setBits); } }; } }; } private static final class BitFilteredSetIterator<E> extends UnmodifiableIterator<E> { final ImmutableList<E> input; int remainingSetBits; BitFilteredSetIterator(ImmutableList<E> input, int allSetBits) { this.input = input; this.remainingSetBits = allSetBits; } @Override public boolean hasNext() { return remainingSetBits != 0; } @Override public E next() { int index = Integer.numberOfTrailingZeros(remainingSetBits); if (index == 32) { throw new NoSuchElementException(); } int currentElementMask = 1 << index; remainingSetBits &= ~currentElementMask; return input.get(index); } } @Override public boolean contains(@Nullable Object obj) { if (obj instanceof Set) { Set<?> set = (Set<?>) obj; return inputSet.containsAll(set); } return false; } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof PowerSet) { PowerSet<?> that = (PowerSet<?>) obj; return inputSet.equals(that.inputSet); } return super.equals(obj); } @Override public int hashCode() { /* * The sum of the sums of the hash codes in each subset is just the sum of * each input element's hash code times the number of sets that element * appears in. Each element appears in exactly half of the 2^n sets, so: */ return inputSet.hashCode() << (inputSet.size() - 1); } @Override public String toString() { return "powerSet(" + inputSet + ")"; } } /** * An implementation for {@link Set#hashCode()}. */ static int hashCodeImpl(Set<?> s) { int hashCode = 0; for (Object o : s) { hashCode += o != null ? o.hashCode() : 0; } return hashCode; } /** * An implementation for {@link Set#equals(Object)}. */ static boolean equalsImpl(Set<?> s, @Nullable Object object){ if (s == object) { return true; } if (object instanceof Set) { Set<?> o = (Set<?>) object; try { return s.size() == o.size() && s.containsAll(o); } catch (NullPointerException ignored) { return false; } catch (ClassCastException ignored) { return false; } } return false; } /** * Creates a view of Set<B> for a Set<A>, given a bijection between A and B. * (Modelled for now as InvertibleFunction<A, B>, can't be Converter<A, B> * because that's not in Guava, though both designs are less than optimal). * Note that the bijection is treated as undefined for values not in the * given Set<A> - it doesn't have to define a true bijection for those. * * <p>Note that the returned Set's contains method is unsafe - * you *must* pass an instance of B to it, since the bijection * can only invert B's (not any Object) back to A, so we can * then delegate the call to the original Set<A>. */ static <A, B> Set<B> transform( Set<A> set, InvertibleFunction<A, B> bijection) { return new TransformedSet<A, B>( Preconditions.checkNotNull(set, "set"), Preconditions.checkNotNull(bijection, "bijection") ); } /** * Stop-gap measure since there is no bijection related type in Guava. */ abstract static class InvertibleFunction<A, B> implements Function<A, B> { abstract A invert(B b); public InvertibleFunction<B, A> inverse() { return new InvertibleFunction<B, A>() { @Override public A apply(B b) { return InvertibleFunction.this.invert(b); } @Override B invert(A a) { return InvertibleFunction.this.apply(a); } // Not required per se, but just for good karma. @Override public InvertibleFunction<A, B> inverse() { return InvertibleFunction.this; } }; } } private static class TransformedSet<A, B> extends AbstractSet<B> { final Set<A> delegate; final InvertibleFunction<A, B> bijection; TransformedSet(Set<A> delegate, InvertibleFunction<A, B> bijection) { this.delegate = delegate; this.bijection = bijection; } @Override public Iterator<B> iterator() { return Iterators.transform(delegate.iterator(), bijection); } @Override public int size() { return delegate.size(); } @SuppressWarnings("unchecked") // unsafe, passed object *must* be B @Override public boolean contains(Object o) { B b = (B) o; A a = bijection.invert(b); /* * Mathematically, Converter<A, B> defines a bijection between ALL A's * on ALL B's. Here we concern ourselves with a subset * of this relation: we only want the part that is defined by a *subset* * of all A's (defined by that Set<A> delegate), and the image * of *that* on B (which is this set). We don't care whether * the converter is *not* a bijection for A's that are not in Set<A> * or B's not in this Set<B>. * * We only want to return true if and only f the user passes a B instance * that is contained in precisely in the image of Set<A>. * * The first test is whether the inverse image of this B is indeed * in Set<A>. But we don't know whether that B belongs in this Set<B> * or not; if not, the converter is free to return * anything it wants, even an element of Set<A> (and this relationship * is not part of the Set<A> <--> Set<B> bijection), and we must not * be confused by that. So we have to do a final check to see if the * image of that A is really equivalent to the passed B, which proves * that the given B belongs indeed in the image of Set<A>. */ return delegate.contains(a) && Objects.equal(bijection.apply(a), o); } @Override public boolean add(B b) { return delegate.add(bijection.invert(b)); } @SuppressWarnings("unchecked") // unsafe, passed object *must* be B @Override public boolean remove(Object o) { return contains(o) && delegate.remove(bijection.invert((B) o)); } @Override public void clear() { delegate.clear(); } } /** * Returns an unmodifiable view of the specified navigable set. This method * allows modules to provide users with "read-only" access to internal * navigable sets. Query operations on the returned set "read through" to the * specified set, and attempts to modify the returned set, whether direct or * via its collection views, result in an * {@code UnsupportedOperationException}. * * <p>The returned navigable set will be serializable if the specified * navigable set is serializable. * * @param set the navigable set for which an unmodifiable view is to be * returned * @return an unmodifiable view of the specified navigable set * @since 12.0 */ @GwtIncompatible("NavigableSet") public static <E> NavigableSet<E> unmodifiableNavigableSet( NavigableSet<E> set) { if (set instanceof ImmutableSortedSet || set instanceof UnmodifiableNavigableSet) { return set; } return new UnmodifiableNavigableSet<E>(set); } @GwtIncompatible("NavigableSet") static final class UnmodifiableNavigableSet<E> extends ForwardingSortedSet<E> implements NavigableSet<E>, Serializable { private final NavigableSet<E> delegate; UnmodifiableNavigableSet(NavigableSet<E> delegate) { this.delegate = checkNotNull(delegate); } @Override protected SortedSet<E> delegate() { return Collections.unmodifiableSortedSet(delegate); } @Override public E lower(E e) { return delegate.lower(e); } @Override public E floor(E e) { return delegate.floor(e); } @Override public E ceiling(E e) { return delegate.ceiling(e); } @Override public E higher(E e) { return delegate.higher(e); } @Override public E pollFirst() { throw new UnsupportedOperationException(); } @Override public E pollLast() { throw new UnsupportedOperationException(); } private transient UnmodifiableNavigableSet<E> descendingSet; @Override public NavigableSet<E> descendingSet() { UnmodifiableNavigableSet<E> result = descendingSet; if (result == null) { result = descendingSet = new UnmodifiableNavigableSet<E>( delegate.descendingSet()); result.descendingSet = this; } return result; } @Override public Iterator<E> descendingIterator() { return Iterators.unmodifiableIterator(delegate.descendingIterator()); } @Override public NavigableSet<E> subSet( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return unmodifiableNavigableSet(delegate.subSet( fromElement, fromInclusive, toElement, toInclusive)); } @Override public NavigableSet<E> headSet(E toElement, boolean inclusive) { return unmodifiableNavigableSet(delegate.headSet(toElement, inclusive)); } @Override public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { return unmodifiableNavigableSet( delegate.tailSet(fromElement, inclusive)); } private static final long serialVersionUID = 0; } /** * Remove each element in an iterable from a set. */ static boolean removeAllImpl(Set<?> set, Iterable<?> iterable) { // TODO(jlevy): Have ForwardingSet.standardRemoveAll() call this method. boolean changed = false; for (Object o : iterable) { changed |= set.remove(o); } return changed; } @GwtIncompatible("NavigableSet") static class DescendingSet<E> extends ForwardingNavigableSet<E> { private final NavigableSet<E> forward; DescendingSet(NavigableSet<E> forward) { this.forward = forward; } @Override protected NavigableSet<E> delegate() { return forward; } @Override public E lower(E e) { return forward.higher(e); } @Override public E floor(E e) { return forward.ceiling(e); } @Override public E ceiling(E e) { return forward.floor(e); } @Override public E higher(E e) { return forward.lower(e); } @Override public E pollFirst() { return forward.pollLast(); } @Override public E pollLast() { return forward.pollFirst(); } @Override public NavigableSet<E> descendingSet() { return forward; } @Override public Iterator<E> descendingIterator() { return forward.iterator(); } @Override public NavigableSet<E> subSet( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return forward.subSet(toElement, toInclusive, fromElement, fromInclusive).descendingSet(); } @Override public NavigableSet<E> headSet(E toElement, boolean inclusive) { return forward.tailSet(toElement, inclusive).descendingSet(); } @Override public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { return forward.headSet(fromElement, inclusive).descendingSet(); } @SuppressWarnings("unchecked") @Override public Comparator<? super E> comparator() { Comparator<? super E> forwardComparator = forward.comparator(); if (forwardComparator == null) { return (Comparator) Ordering.natural().reverse(); } else { return reverse(forwardComparator); } } // If we inline this, we get a javac error. private static <T> Ordering<T> reverse(Comparator<T> forward) { return Ordering.from(forward).reverse(); } @Override public E first() { return forward.last(); } @Override public SortedSet<E> headSet(E toElement) { return standardHeadSet(toElement); } @Override public E last() { return forward.first(); } @Override public SortedSet<E> subSet(E fromElement, E toElement) { return standardSubSet(fromElement, toElement); } @Override public SortedSet<E> tailSet(E fromElement) { return standardTailSet(fromElement); } @Override public Iterator<E> iterator() { return forward.descendingIterator(); } @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } @Override public String toString() { return standardToString(); } } }
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 java.util.NoSuchElementException; import java.util.Queue; /** * A queue which forwards all its method calls to another queue. Subclasses * should override one or more methods to modify the behavior of the backing * queue as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><b>Warning:</b> The methods of {@code ForwardingQueue} forward * <b>indiscriminately</b> to the methods of the delegate. For example, * overriding {@link #add} alone <b>will not</b> change the behavior of {@link * #offer} which can lead to unexpected behavior. 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 Mike Bostock * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingQueue<E> extends ForwardingCollection<E> implements Queue<E> { /** Constructor for use by subclasses. */ protected ForwardingQueue() {} @Override protected abstract Queue<E> delegate(); @Override public boolean offer(E o) { return delegate().offer(o); } @Override public E poll() { return delegate().poll(); } @Override public E remove() { return delegate().remove(); } @Override public E peek() { return delegate().peek(); } @Override public E element() { return delegate().element(); } /** * A sensible definition of {@link #offer} in terms of {@link #add}. If you * override {@link #add}, you may wish to override {@link #offer} to forward * to this implementation. * * @since 7.0 */ @Beta protected boolean standardOffer(E e) { try { return add(e); } catch (IllegalStateException caught) { return false; } } /** * A sensible definition of {@link #peek} in terms of {@link #element}. If you * override {@link #element}, you may wish to override {@link #peek} to * forward to this implementation. * * @since 7.0 */ @Beta protected E standardPeek() { try { return element(); } catch (NoSuchElementException caught) { return null; } } /** * A sensible definition of {@link #poll} in terms of {@link #remove}. If you * override {@link #remove}, you may wish to override {@link #poll} to forward * to this implementation. * * @since 7.0 */ @Beta protected E standardPoll() { try { return remove(); } catch (NoSuchElementException caught) { return null; } } }
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.lang.reflect.Array; /** * Methods factored out so that they can be emulated differently in GWT. * * @author Hayward Chan */ @GwtCompatible(emulated = true) class Platform { /** * Clone the given array using {@link Object#clone()}. It is factored out so * that it can be emulated in GWT. */ static <T> T[] clone(T[] array) { return array.clone(); } /** * Wrapper around {@link System#arraycopy} so that it can be emulated * correctly in GWT. * * <p>It is only intended for the case {@code src} and {@code dest} are * different. It also doesn't validate the types and indices. * * <p>As of GWT 2.0, The built-in {@link System#arraycopy} doesn't work * in general case. See * http://code.google.com/p/google-web-toolkit/issues/detail?id=3621 * for more details. */ static void unsafeArrayCopy( Object[] src, int srcPos, Object[] dest, int destPos, int length) { System.arraycopy(src, srcPos, dest, destPos, length); } /** * Returns a new array of the given length with the specified component type. * * @param type the component type * @param length the length of the new array */ @GwtIncompatible("Array.newInstance(Class, int)") @SuppressWarnings("unchecked") static <T> T[] newArray(Class<T> type, int length) { return (T[]) Array.newInstance(type, length); } /** * Returns a new array of the given length with the same type as a reference * array. * * @param reference any array of the desired type * @param length the length of the new array */ static <T> T[] newArray(T[] reference, int length) { Class<?> type = reference.getClass().getComponentType(); // the cast is safe because // result.getClass() == reference.getClass().getComponentType() @SuppressWarnings("unchecked") T[] result = (T[]) Array.newInstance(type, length); return result; } /** * Configures the given map maker to use weak keys, if possible; does nothing * otherwise (i.e., in GWT). This is sometimes acceptable, when only * server-side code could generate enough volume that reclamation becomes * important. */ static MapMaker tryWeakKeys(MapMaker mapMaker) { return mapMaker.weakKeys(); } private Platform() {} }
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.collect.MapConstraints.ConstrainedMap; import com.google.common.primitives.Primitives; import java.util.HashMap; import java.util.Map; /** * A mutable class-to-instance map backed by an arbitrary user-provided map. * See also {@link ImmutableClassToInstanceMap}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#ClassToInstanceMap"> * {@code ClassToInstanceMap}</a>. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ public final class MutableClassToInstanceMap<B> extends ConstrainedMap<Class<? extends B>, B> implements ClassToInstanceMap<B> { /** * Returns a new {@code MutableClassToInstanceMap} instance backed by a {@link * HashMap} using the default initial capacity and load factor. */ public static <B> MutableClassToInstanceMap<B> create() { return new MutableClassToInstanceMap<B>( new HashMap<Class<? extends B>, B>()); } /** * Returns a new {@code MutableClassToInstanceMap} instance backed by a given * empty {@code backingMap}. The caller surrenders control of the backing map, * and thus should not allow any direct references to it to remain accessible. */ public static <B> MutableClassToInstanceMap<B> create( Map<Class<? extends B>, B> backingMap) { return new MutableClassToInstanceMap<B>(backingMap); } private MutableClassToInstanceMap(Map<Class<? extends B>, B> delegate) { super(delegate, VALUE_CAN_BE_CAST_TO_KEY); } private static final MapConstraint<Class<?>, Object> VALUE_CAN_BE_CAST_TO_KEY = new MapConstraint<Class<?>, Object>() { @Override public void checkKeyValue(Class<?> key, Object value) { cast(key, value); } }; @Override public <T extends B> T putInstance(Class<T> type, T value) { return cast(type, put(type, value)); } @Override public <T extends B> T getInstance(Class<T> type) { return cast(type, get(type)); } private static <B, T extends B> T cast(Class<T> type, B value) { return Primitives.wrap(type).cast(value); } 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; import java.io.Serializable; import javax.annotation.Nullable; /** * @see com.google.common.collect.Maps#immutableEntry(Object, Object) */ @GwtCompatible(serializable = true) class ImmutableEntry<K, V> extends AbstractMapEntry<K, V> implements Serializable { private final K key; private final V value; ImmutableEntry(@Nullable K key, @Nullable V value) { this.key = key; this.value = value; } @Nullable @Override public K getKey() { return key; } @Nullable @Override public V getValue() { return value; } @Override public final V setValue(V value){ throw new UnsupportedOperationException(); } 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.Map; import java.util.Map.Entry; import javax.annotation.Nullable; /** * A map entry which forwards all its method calls to another map entry. * Subclasses should override one or more methods to modify the behavior of the * backing map entry as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><i>Warning:</i> The methods of {@code ForwardingMapEntry} forward * <i>indiscriminately</i> to the methods of the delegate. For example, * overriding {@link #getValue} alone <i>will not</i> change the behavior of * {@link #equals}, which can lead to unexpected behavior. In this case, you * should override {@code equals} as well, either providing your own * implementation, or delegating to the provided {@code standardEquals} 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 the entry of a {@code SortedMap} whose comparator is * not consistent with {@code equals}. * * <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 Mike Bostock * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingMapEntry<K, V> extends ForwardingObject implements Map.Entry<K, V> { // TODO(user): identify places where thread safety is actually lost /** Constructor for use by subclasses. */ protected ForwardingMapEntry() {} @Override protected abstract Map.Entry<K, V> delegate(); @Override public K getKey() { return delegate().getKey(); } @Override public V getValue() { return delegate().getValue(); } @Override public V setValue(V value) { return delegate().setValue(value); } @Override public boolean equals(@Nullable Object object) { return delegate().equals(object); } @Override public int hashCode() { return delegate().hashCode(); } /** * A sensible definition of {@link #equals(Object)} in terms of {@link * #getKey()} and {@link #getValue()}. If you override either of these * methods, you may wish to override {@link #equals(Object)} to forward to * this implementation. * * @since 7.0 */ @Beta protected boolean standardEquals(@Nullable Object object) { if (object instanceof Entry) { Entry<?, ?> that = (Entry<?, ?>) object; return Objects.equal(this.getKey(), that.getKey()) && Objects.equal(this.getValue(), that.getValue()); } return false; } /** * A sensible definition of {@link #hashCode()} in terms of {@link #getKey()} * and {@link #getValue()}. If you override either of these methods, you may * wish to override {@link #hashCode()} to forward to this implementation. * * @since 7.0 */ @Beta protected int standardHashCode() { K k = getKey(); V v = getValue(); return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode()); } /** * A sensible definition of {@link #toString} in terms of {@link * #getKey} and {@link #getValue}. If you override either of these * methods, you may wish to override {@link #equals} to forward to this * implementation. * * @since 7.0 */ @Beta protected String standardToString() { return getKey() + "=" + getValue(); } }
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 com.google.common.annotations.Beta; import java.util.Iterator; import java.util.NavigableSet; import java.util.SortedSet; import javax.annotation.Nullable; /** * A navigable set which forwards all its method calls to another navigable set. Subclasses should * override one or more methods to modify the behavior of the backing set as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><i>Warning:</i> The methods of {@code ForwardingNavigableSet} forward <i>indiscriminately</i> * to the methods of the delegate. For example, overriding {@link #add} alone <i>will not</i> * change the behavior of {@link #addAll}, which can lead to unexpected behavior. In this case, you * should override {@code addAll} as well, either providing your own implementation, or delegating * to the provided {@code standardAddAll} method. * * <p>Each of the {@code standard} methods uses the set'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 Set} 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 */ @Beta public abstract class ForwardingNavigableSet<E> extends ForwardingSortedSet<E> implements NavigableSet<E> { /** Constructor for use by subclasses. */ protected ForwardingNavigableSet() {} @Override protected abstract NavigableSet<E> delegate(); @Override public E lower(E e) { return delegate().lower(e); } /** * A sensible definition of {@link #lower} in terms of the {@code descendingIterator} method of * {@link #headSet(Object, boolean)}. If you override {@link #headSet(Object, boolean)}, you may * wish to override {@link #lower} to forward to this implementation. */ protected E standardLower(E e) { return Iterators.getNext(headSet(e, false).descendingIterator(), null); } @Override public E floor(E e) { return delegate().floor(e); } /** * A sensible definition of {@link #floor} in terms of the {@code descendingIterator} method of * {@link #headSet(Object, boolean)}. If you override {@link #headSet(Object, boolean)}, you may * wish to override {@link #floor} to forward to this implementation. */ protected E standardFloor(E e) { return Iterators.getNext(headSet(e, true).descendingIterator(), null); } @Override public E ceiling(E e) { return delegate().ceiling(e); } /** * A sensible definition of {@link #ceiling} in terms of the {@code iterator} method of * {@link #tailSet(Object, boolean)}. If you override {@link #tailSet(Object, boolean)}, you may * wish to override {@link #ceiling} to forward to this implementation. */ protected E standardCeiling(E e) { return Iterators.getNext(tailSet(e, true).iterator(), null); } @Override public E higher(E e) { return delegate().higher(e); } /** * A sensible definition of {@link #higher} in terms of the {@code iterator} method of * {@link #tailSet(Object, boolean)}. If you override {@link #tailSet(Object, boolean)}, you may * wish to override {@link #higher} to forward to this implementation. */ protected E standardHigher(E e) { return Iterators.getNext(tailSet(e, false).iterator(), null); } @Override public E pollFirst() { return delegate().pollFirst(); } /** * A sensible definition of {@link #pollFirst} in terms of the {@code iterator} method. If you * override {@link #iterator} you may wish to override {@link #pollFirst} to forward to this * implementation. */ protected E standardPollFirst() { return poll(iterator()); } @Override public E pollLast() { return delegate().pollLast(); } /** * A sensible definition of {@link #pollLast} in terms of the {@code descendingIterator} method. * If you override {@link #descendingIterator} you may wish to override {@link #pollLast} to * forward to this implementation. */ protected E standardPollLast() { return poll(delegate().descendingIterator()); } protected E standardFirst() { return iterator().next(); } protected E standardLast() { return descendingIterator().next(); } @Override public NavigableSet<E> descendingSet() { return delegate().descendingSet(); } /** * A sensible implementation of {@link #descendingSet} in terms of the other methods of * {@link NavigableSet}, notably including {@link NavigableSet#descendingIterator}. * * <p>In many cases, you may wish to override {@link #descendingSet} to forward to this * implementation or a subclass thereof. * * @since 12.0 */ @Beta protected class StandardDescendingSet extends Sets.DescendingSet<E> { /** Constructor for use by subclasses. */ public StandardDescendingSet() { super(ForwardingNavigableSet.this); } } @Override public Iterator<E> descendingIterator() { return delegate().descendingIterator(); } @Override public NavigableSet<E> subSet( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return delegate().subSet(fromElement, fromInclusive, toElement, toInclusive); } /** * A sensible definition of {@link #subSet(Object, boolean, Object, boolean)} in terms of the * {@code headSet} and {@code tailSet} methods. In many cases, you may wish to override * {@link #subSet(Object, boolean, Object, boolean)} to forward to this implementation. */ protected NavigableSet<E> standardSubSet( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return tailSet(fromElement, fromInclusive).headSet(toElement, toInclusive); } /** * A sensible definition of {@link #subSet(Object, Object)} in terms of the * {@link #subSet(Object, boolean, Object, boolean)} method. If you override * {@link #subSet(Object, boolean, Object, boolean)}, you may wish to override * {@link #subSet(Object, Object)} to forward to this implementation. */ @Override protected SortedSet<E> standardSubSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); } @Override public NavigableSet<E> headSet(E toElement, boolean inclusive) { return delegate().headSet(toElement, inclusive); } /** * A sensible definition of {@link #headSet(Object)} in terms of the * {@link #headSet(Object, boolean)} method. If you override * {@link #headSet(Object, boolean)}, you may wish to override * {@link #headSet(Object)} to forward to this implementation. */ protected SortedSet<E> standardHeadSet(E toElement) { return headSet(toElement, false); } @Override public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { return delegate().tailSet(fromElement, inclusive); } /** * A sensible definition of {@link #tailSet(Object)} in terms of the * {@link #tailSet(Object, boolean)} method. If you override * {@link #tailSet(Object, boolean)}, you may wish to override * {@link #tailSet(Object)} to forward to this implementation. */ protected SortedSet<E> standardTailSet(E fromElement) { return tailSet(fromElement, true); } @Nullable private E poll(Iterator<E> iterator) { if (iterator.hasNext()) { E result = iterator.next(); iterator.remove(); return result; } return 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.collect; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.Iterator; import javax.annotation.Nullable; /** * An ordering which sorts iterables by comparing corresponding elements * pairwise. */ @GwtCompatible(serializable = true) final class LexicographicalOrdering<T> extends Ordering<Iterable<T>> implements Serializable { final Ordering<? super T> elementOrder; LexicographicalOrdering(Ordering<? super T> elementOrder) { this.elementOrder = elementOrder; } @Override public int compare( Iterable<T> leftIterable, Iterable<T> rightIterable) { Iterator<T> left = leftIterable.iterator(); Iterator<T> right = rightIterable.iterator(); while (left.hasNext()) { if (!right.hasNext()) { return LEFT_IS_GREATER; // because it's longer } int result = elementOrder.compare(left.next(), right.next()); if (result != 0) { return result; } } if (right.hasNext()) { return RIGHT_IS_GREATER; // because it's longer } return 0; } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof LexicographicalOrdering) { LexicographicalOrdering<?> that = (LexicographicalOrdering<?>) object; return this.elementOrder.equals(that.elementOrder); } return false; } @Override public int hashCode() { return elementOrder.hashCode() ^ 2075626741; // meaningless } @Override public String toString() { return elementOrder + ".lexicographical()"; } 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 java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.SortedMap; import javax.annotation.Nullable; /** * A sorted map which forwards all its method calls to another sorted map. * Subclasses should override one or more methods to modify the behavior of * the backing sorted 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 ForwardingSortedMap} 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 the * comparator of the map to test equality for both keys and values, unlike * {@code ForwardingMap}. * * <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 Mike Bostock * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingSortedMap<K, V> extends ForwardingMap<K, V> implements SortedMap<K, V> { // TODO(user): identify places where thread safety is actually lost /** Constructor for use by subclasses. */ protected ForwardingSortedMap() {} @Override protected abstract SortedMap<K, V> delegate(); @Override public Comparator<? super K> comparator() { return delegate().comparator(); } @Override public K firstKey() { return delegate().firstKey(); } @Override public SortedMap<K, V> headMap(K toKey) { return delegate().headMap(toKey); } @Override public K lastKey() { return delegate().lastKey(); } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { return delegate().subMap(fromKey, toKey); } @Override public SortedMap<K, V> tailMap(K fromKey) { return delegate().tailMap(fromKey); } // unsafe, but worst case is a CCE is thrown, which callers will be expecting @SuppressWarnings("unchecked") private int unsafeCompare(Object k1, Object k2) { Comparator<? super K> comparator = comparator(); if (comparator == null) { return ((Comparable<Object>) k1).compareTo(k2); } else { return ((Comparator<Object>) comparator).compare(k1, k2); } } /** * A sensible definition of {@link #containsKey} in terms of the {@code * firstKey()} method of {@link #tailMap}. If you override {@link #tailMap}, * you may wish to override {@link #containsKey} to forward to this * implementation. * * @since 7.0 */ @Override @Beta protected boolean standardContainsKey(@Nullable Object key) { try { // any CCE will be caught @SuppressWarnings("unchecked") SortedMap<Object, V> self = (SortedMap<Object, V>) this; Object ceilingKey = self.tailMap(key).firstKey(); return unsafeCompare(ceilingKey, key) == 0; } catch (ClassCastException e) { return false; } catch (NoSuchElementException e) { return false; } catch (NullPointerException e) { return false; } } /** * A sensible definition of {@link #remove} in terms of the {@code * iterator()} of the {@code entrySet()} of {@link #tailMap}. If you override * {@link #tailMap}, you may wish to override {@link #remove} to forward * to this implementation. * * @since 7.0 */ @Override @Beta protected V standardRemove(@Nullable Object key) { try { // any CCE will be caught @SuppressWarnings("unchecked") SortedMap<Object, V> self = (SortedMap<Object, V>) this; Iterator<Entry<Object, V>> entryIterator = self.tailMap(key).entrySet().iterator(); if (entryIterator.hasNext()) { Entry<Object, V> ceilingEntry = entryIterator.next(); if (unsafeCompare(ceilingEntry.getKey(), key) == 0) { V value = ceilingEntry.getValue(); entryIterator.remove(); return value; } } } catch (ClassCastException e) { return null; } catch (NullPointerException e) { return null; } return null; } /** * A sensible default implementation of {@link #subMap(Object, Object)} in * terms of {@link #headMap(Object)} and {@link #tailMap(Object)}. In some * situations, you may wish to override {@link #subMap(Object, Object)} to * forward to this implementation. * * @since 7.0 */ @Beta protected SortedMap<K, V> standardSubMap(K fromKey, K toKey) { return tailMap(fromKey).headMap(toKey); } }
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 java.util.Set; import javax.annotation.Nullable; /** * A bimap (or "bidirectional map") is a map that preserves the uniqueness of * its values as well as that of its keys. This constraint enables bimaps to * support an "inverse view", which is another bimap containing the same entries * as this bimap but with reversed keys and values. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap"> * {@code BiMap}</a>. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public interface BiMap<K, V> extends Map<K, V> { // Modification Operations /** * {@inheritDoc} * * @throws IllegalArgumentException if the given value is already bound to a * different key in this bimap. The bimap will remain unmodified in this * event. To avoid this exception, call {@link #forcePut} instead. */ @Override V put(@Nullable K key, @Nullable V value); /** * An alternate form of {@code put} that silently removes any existing entry * with the value {@code value} before proceeding with the {@link #put} * operation. If the bimap previously contained the provided key-value * mapping, this method has no effect. * * <p>Note that a successful call to this method could cause the size of the * bimap to increase by one, stay the same, or even decrease by one. * * <p><b>Warning:</b> If an existing entry with this value is removed, the key * for that entry is discarded and not returned. * * @param key the key with which the specified value is to be associated * @param value the value to be associated with the specified key * @return the value which was previously associated with the key, which may * be {@code null}, or {@code null} if there was no previous entry */ V forcePut(@Nullable K key, @Nullable V value); // Bulk Operations /** * {@inheritDoc} * * <p><b>Warning:</b> the results of calling this method may vary depending on * the iteration order of {@code map}. * * @throws IllegalArgumentException if an attempt to {@code put} any * entry fails. Note that some map entries may have been added to the * bimap before the exception was thrown. */ @Override void putAll(Map<? extends K, ? extends V> map); // Views /** * {@inheritDoc} * * <p>Because a bimap has unique values, this method returns a {@link Set}, * instead of the {@link java.util.Collection} specified in the {@link Map} * interface. */ @Override Set<V> values(); /** * Returns the inverse view of this bimap, which maps each of this bimap's * values to its associated key. The two bimaps are backed by the same data; * any changes to one will appear in the other. * * <p><b>Note:</b>There is no guaranteed correspondence between the iteration * order of a bimap and that of its inverse. * * @return the inverse view of this bimap */ BiMap<V, K> inverse(); }
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.annotations.GwtIncompatible; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collection; import java.util.Comparator; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; /** * Implementation of {@code Multimap} whose keys and values are ordered by * their natural ordering or by supplied comparators. In all cases, this * implementation uses {@link Comparable#compareTo} or {@link * Comparator#compare} instead of {@link Object#equals} to determine * equivalence of instances. * * <p><b>Warning:</b> The comparators or comparables used must be <i>consistent * with equals</i> as explained by the {@link Comparable} class specification. * Otherwise, the resulting multiset will violate the general contract of {@link * SetMultimap}, which it is specified in terms of {@link Object#equals}. * * <p>The collections returned by {@code keySet} and {@code asMap} iterate * through the keys according to the key comparator ordering or the natural * ordering of the keys. Similarly, {@code get}, {@code removeAll}, and {@code * replaceValues} return collections that iterate through the values according * to the value comparator ordering or the natural ordering of the values. The * collections generated by {@code entries}, {@code keys}, and {@code values} * iterate across the keys according to the above key ordering, and for each * key they iterate across the values according to the value ordering. * * <p>The multimap does not store duplicate key-value pairs. Adding a new * key-value pair equal to an existing key-value pair has no effect. * * <p>Null keys and values are permitted (provided, of course, that the * respective comparators support them). All optional multimap methods are * supported, and all returned views are modifiable. * * <p>This class is not threadsafe when any concurrent operations update the * multimap. Concurrent read operations will work correctly. To allow concurrent * update operations, wrap your multimap with a call to {@link * Multimaps#synchronizedSortedSetMultimap}. * * <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(serializable = true, emulated = true) public class TreeMultimap<K, V> extends AbstractSortedSetMultimap<K, V> { private transient Comparator<? super K> keyComparator; private transient Comparator<? super V> valueComparator; /** * Creates an empty {@code TreeMultimap} ordered by the natural ordering of * its keys and values. */ public static <K extends Comparable, V extends Comparable> TreeMultimap<K, V> create() { return new TreeMultimap<K, V>(Ordering.natural(), Ordering.natural()); } /** * Creates an empty {@code TreeMultimap} instance using explicit comparators. * Neither comparator may be null; use {@link Ordering#natural()} to specify * natural order. * * @param keyComparator the comparator that determines the key ordering * @param valueComparator the comparator that determines the value ordering */ public static <K, V> TreeMultimap<K, V> create( Comparator<? super K> keyComparator, Comparator<? super V> valueComparator) { return new TreeMultimap<K, V>(checkNotNull(keyComparator), checkNotNull(valueComparator)); } /** * Constructs a {@code TreeMultimap}, ordered by the natural ordering of its * keys and values, with the same mappings as the specified multimap. * * @param multimap the multimap whose contents are copied to this multimap */ public static <K extends Comparable, V extends Comparable> TreeMultimap<K, V> create(Multimap<? extends K, ? extends V> multimap) { return new TreeMultimap<K, V>(Ordering.natural(), Ordering.natural(), multimap); } TreeMultimap(Comparator<? super K> keyComparator, Comparator<? super V> valueComparator) { super(new TreeMap<K, Collection<V>>(keyComparator)); this.keyComparator = keyComparator; this.valueComparator = valueComparator; } private TreeMultimap(Comparator<? super K> keyComparator, Comparator<? super V> valueComparator, Multimap<? extends K, ? extends V> multimap) { this(keyComparator, valueComparator); putAll(multimap); } /** * {@inheritDoc} * * <p>Creates an empty {@code TreeSet} for a collection of values for one key. * * @return a new {@code TreeSet} containing a collection of values for one * key */ @Override SortedSet<V> createCollection() { return new TreeSet<V>(valueComparator); } /** * Returns the comparator that orders the multimap keys. */ public Comparator<? super K> keyComparator() { return keyComparator; } @Override public Comparator<? super V> valueComparator() { return valueComparator; } /** * {@inheritDoc} * * <p>Because a {@code TreeMultimap} has unique sorted keys, this method * returns a {@link SortedSet}, instead of the {@link java.util.Set} specified * in the {@link Multimap} interface. */ @Override public SortedSet<K> keySet() { return (SortedSet<K>) super.keySet(); } /** * {@inheritDoc} * * <p>Because a {@code TreeMultimap} has unique sorted keys, this method * returns a {@link SortedMap}, instead of the {@link java.util.Map} specified * in the {@link Multimap} interface. */ @Override public SortedMap<K, Collection<V>> asMap() { return (SortedMap<K, Collection<V>>) super.asMap(); } /** * @serialData key comparator, value comparator, number of distinct keys, and * then for each distinct key: the key, number of values for that key, and * key values */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(keyComparator()); stream.writeObject(valueComparator()); Serialization.writeMultimap(this, stream); } @GwtIncompatible("java.io.ObjectInputStream") @SuppressWarnings("unchecked") // reading data stored by writeObject private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); keyComparator = checkNotNull((Comparator<? super K>) stream.readObject()); valueComparator = checkNotNull((Comparator<? super V>) stream.readObject()); setMap(new TreeMap<K, Collection<V>>(keyComparator)); Serialization.populateMultimap(this, stream); } @GwtIncompatible("not needed in emulated source") 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 javax.annotation.Nullable; /** * A constraint on the keys and values that may be added to a {@code Map} or * {@code Multimap}. For example, {@link MapConstraints#notNull()}, which * prevents a map from including any null keys or values, could be implemented * like this: <pre> {@code * * public void checkKeyValue(Object key, Object value) { * if (key == null || value == null) { * throw new NullPointerException(); * } * }}</pre> * * In order to be effective, constraints should be deterministic; that is, they * should not depend on state that can change (such as external state, random * variables, and time) and should only depend on the value of the passed-in key * and value. A non-deterministic constraint cannot reliably enforce that all * the collection's elements meet the constraint, since the constraint is only * enforced when elements are added. * * @author Mike Bostock * @see MapConstraints * @see Constraint * @since 3.0 */ @GwtCompatible @Beta public interface MapConstraint<K, V> { /** * Throws a suitable {@code RuntimeException} if the specified key or value is * illegal. Typically this is either a {@link NullPointerException}, an * {@link IllegalArgumentException}, or a {@link ClassCastException}, though * an application-specific exception class may be used if appropriate. */ void checkKeyValue(@Nullable K key, @Nullable V value); /** * Returns a brief human readable description of this constraint, such as * "Not null". */ @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. */ /** * This package contains generic collection interfaces and implementations, and * other utilities for working with collections. It is a part of the open-source * <a href="http://guava-libraries.googlecode.com">Guava libraries</a>. * * <h2>Collection Types</h2> * * <dl> * <dt>{@link com.google.common.collect.BiMap} * <dd>An extension of {@link java.util.Map} that guarantees the uniqueness of * its values as well as that of its keys. This is sometimes called an * "invertible map," since the restriction on values enables it to support * an {@linkplain com.google.common.collect.BiMap#inverse inverse view} -- * which is another instance of {@code BiMap}. * * <dt>{@link com.google.common.collect.Multiset} * <dd>An extension of {@link java.util.Collection} that may contain duplicate * values like a {@link java.util.List}, yet has order-independent equality * like a {@link java.util.Set}. One typical use for a multiset is to * represent a histogram. * * <dt>{@link com.google.common.collect.Multimap} * <dd>A new type, which is similar to {@link java.util.Map}, but may contain * multiple entries with the same key. Some behaviors of * {@link com.google.common.collect.Multimap} are left unspecified and are * provided only by the subtypes mentioned below. * * <dt>{@link com.google.common.collect.ListMultimap} * <dd>An extension of {@link com.google.common.collect.Multimap} which permits * duplicate entries, supports random access of values for a particular key, * and has <i>partially order-dependent equality</i> as defined by * {@link com.google.common.collect.ListMultimap#equals(Object)}. {@code * ListMultimap} takes its name from the fact that the {@linkplain * com.google.common.collect.ListMultimap#get collection of values} * associated with a given key fulfills the {@link java.util.List} contract. * * <dt>{@link com.google.common.collect.SetMultimap} * <dd>An extension of {@link com.google.common.collect.Multimap} which has * order-independent equality and does not allow duplicate entries; that is, * while a key may appear twice in a {@code SetMultimap}, each must map to a * different value. {@code SetMultimap} takes its name from the fact that * the {@linkplain com.google.common.collect.SetMultimap#get collection of * values} associated with a given key fulfills the {@link java.util.Set} * contract. * * <dt>{@link com.google.common.collect.SortedSetMultimap} * <dd>An extension of {@link com.google.common.collect.SetMultimap} for which * the {@linkplain com.google.common.collect.SortedSetMultimap#get * collection values} associated with a given key is a * {@link java.util.SortedSet}. * * <dt>{@link com.google.common.collect.Table} * <dd>A new type, which is similar to {@link java.util.Map}, but which indexes * its values by an ordered pair of keys, a row key and column key. * * <dt>{@link com.google.common.collect.ClassToInstanceMap} * <dd>An extension of {@link java.util.Map} that associates a raw type with an * instance of that type. * </dl> * * <h2>Collection Implementations</h2> * * <h3>of {@link java.util.List}</h3> * <ul> * <li>{@link com.google.common.collect.ImmutableList} * </ul> * * <h3>of {@link java.util.Set}</h3> * <ul> * <li>{@link com.google.common.collect.ImmutableSet} * <li>{@link com.google.common.collect.ImmutableSortedSet} * <li>{@link com.google.common.collect.ContiguousSet} (see {@code Ranges}) * </ul> * * <h3>of {@link java.util.Map}</h3> * <ul> * <li>{@link com.google.common.collect.ImmutableMap} * <li>{@link com.google.common.collect.ImmutableSortedMap} * <li>{@link com.google.common.collect.MapMaker} * </ul> * * <h3>of {@link com.google.common.collect.BiMap}</h3> * <ul> * <li>{@link com.google.common.collect.ImmutableBiMap} * <li>{@link com.google.common.collect.HashBiMap} * <li>{@link com.google.common.collect.EnumBiMap} * <li>{@link com.google.common.collect.EnumHashBiMap} * </ul> * * <h3>of {@link com.google.common.collect.Multiset}</h3> * <ul> * <li>{@link com.google.common.collect.ImmutableMultiset} * <li>{@link com.google.common.collect.HashMultiset} * <li>{@link com.google.common.collect.LinkedHashMultiset} * <li>{@link com.google.common.collect.TreeMultiset} * <li>{@link com.google.common.collect.EnumMultiset} * <li>{@link com.google.common.collect.ConcurrentHashMultiset} * </ul> * * <h3>of {@link com.google.common.collect.Multimap}</h3> * <ul> * <li>{@link com.google.common.collect.ImmutableMultimap} * <li>{@link com.google.common.collect.ImmutableListMultimap} * <li>{@link com.google.common.collect.ImmutableSetMultimap} * <li>{@link com.google.common.collect.ArrayListMultimap} * <li>{@link com.google.common.collect.HashMultimap} * <li>{@link com.google.common.collect.TreeMultimap} * <li>{@link com.google.common.collect.LinkedHashMultimap} * <li>{@link com.google.common.collect.LinkedListMultimap} * </ul> * * <h3>of {@link com.google.common.collect.Table}</h3> * <ul> * <li>{@link com.google.common.collect.ImmutableTable} * <li>{@link com.google.common.collect.ArrayTable} * <li>{@link com.google.common.collect.HashBasedTable} * <li>{@link com.google.common.collect.TreeBasedTable} * </ul> * * <h3>of {@link com.google.common.collect.ClassToInstanceMap}</h3> * <ul> * <li>{@link com.google.common.collect.ImmutableClassToInstanceMap} * <li>{@link com.google.common.collect.MutableClassToInstanceMap} * </ul> * * <h2>Classes of static utility methods</h2> * * <ul> * <li>{@link com.google.common.collect.Collections2} * <li>{@link com.google.common.collect.Iterators} * <li>{@link com.google.common.collect.Iterables} * <li>{@link com.google.common.collect.Lists} * <li>{@link com.google.common.collect.Maps} * <li>{@link com.google.common.collect.Sets} * <li>{@link com.google.common.collect.Multisets} * <li>{@link com.google.common.collect.Multimaps} * <li>{@link com.google.common.collect.SortedMaps} * <li>{@link com.google.common.collect.Tables} * <li>{@link com.google.common.collect.ObjectArrays} * </ul> * * <h2>Comparison</h2> * * <ul> * <li>{@link com.google.common.collect.Ordering} * <li>{@link com.google.common.collect.ComparisonChain} * </ul> * * <h2>Abstract implementations</h2> * * <ul> * <li>{@link com.google.common.collect.AbstractIterator} * <li>{@link com.google.common.collect.AbstractSequentialIterator} * <li>{@link com.google.common.collect.ImmutableCollection} * <li>{@link com.google.common.collect.UnmodifiableIterator} * <li>{@link com.google.common.collect.UnmodifiableListIterator} * </ul> * * <h2>Ranges</h2> * * <ul> * <li>{@link com.google.common.collect.Range} * <li>{@link com.google.common.collect.Ranges} * <li>{@link com.google.common.collect.DiscreteDomain} * <li>{@link com.google.common.collect.DiscreteDomains} * <li>{@link com.google.common.collect.ContiguousSet} * </ul> * * <h2>Other</h2> * * <ul> * <li>{@link com.google.common.collect.Interner}, * {@link com.google.common.collect.Interners} * <li>{@link com.google.common.collect.Constraint}, * {@link com.google.common.collect.Constraints} * <li>{@link com.google.common.collect.MapConstraint}, * {@link com.google.common.collect.MapConstraints} * <li>{@link com.google.common.collect.MapDifference}, * {@link com.google.common.collect.SortedMapDifference} * <li>{@link com.google.common.collect.MinMaxPriorityQueue} * <li>{@link com.google.common.collect.PeekingIterator} * </ul> * * <h2>Forwarding collections</h2> * * <ul> * <li>{@link com.google.common.collect.ForwardingCollection} * <li>{@link com.google.common.collect.ForwardingConcurrentMap} * <li>{@link com.google.common.collect.ForwardingIterator} * <li>{@link com.google.common.collect.ForwardingList} * <li>{@link com.google.common.collect.ForwardingListIterator} * <li>{@link com.google.common.collect.ForwardingListMultimap} * <li>{@link com.google.common.collect.ForwardingMap} * <li>{@link com.google.common.collect.ForwardingMapEntry} * <li>{@link com.google.common.collect.ForwardingMultimap} * <li>{@link com.google.common.collect.ForwardingMultiset} * <li>{@link com.google.common.collect.ForwardingObject} * <li>{@link com.google.common.collect.ForwardingQueue} * <li>{@link com.google.common.collect.ForwardingSet} * <li>{@link com.google.common.collect.ForwardingSetMultimap} * <li>{@link com.google.common.collect.ForwardingSortedMap} * <li>{@link com.google.common.collect.ForwardingSortedMultiset} * <li>{@link com.google.common.collect.ForwardingSortedSet} * <li>{@link com.google.common.collect.ForwardingSortedSetMultimap} * <li>{@link com.google.common.collect.ForwardingTable} * </ul> */ @javax.annotation.ParametersAreNonnullByDefault package com.google.common.collect;
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 static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.Multisets.setCountImpl; import static java.util.Collections.unmodifiableList; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractSequentialList; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; /** * An implementation of {@code ListMultimap} that supports deterministic * iteration order for both keys and values. The iteration order is preserved * across non-distinct key values. For example, for the following multimap * definition: <pre> {@code * * Multimap<K, V> multimap = LinkedListMultimap.create(); * multimap.put(key1, foo); * multimap.put(key2, bar); * multimap.put(key1, baz);}</pre> * * ... the iteration order for {@link #keys()} is {@code [key1, key2, key1]}, * and similarly for {@link #entries()}. Unlike {@link LinkedHashMultimap}, the * iteration order is kept consistent between keys, entries and values. For * example, calling: <pre> {@code * * map.remove(key1, foo);}</pre> * * changes the entries iteration order to {@code [key2=bar, key1=baz]} and the * key iteration order to {@code [key2, key1]}. The {@link #entries()} iterator * returns mutable map entries, and {@link #replaceValues} attempts to preserve * iteration order as much as possible. * * <p>The collections returned by {@link #keySet()} and {@link #asMap} iterate * through the keys in the order they were first added to the multimap. * Similarly, {@link #get}, {@link #removeAll}, and {@link #replaceValues} * return collections that iterate through the values in the order they were * added. The collections generated by {@link #entries()}, {@link #keys()}, and * {@link #values} iterate across the key-value mappings in the order they were * added to the multimap. * * <p>The {@link #values()} and {@link #entries()} methods both return a * {@code List}, instead of the {@code Collection} specified by the {@link * ListMultimap} interface. * * <p>The methods {@link #get}, {@link #keySet()}, {@link #keys()}, * {@link #values}, {@link #entries()}, and {@link #asMap} return collections * that are views of the multimap. If the multimap is modified while an * iteration over any of those collections is in progress, except through the * iterator's methods, the results of the iteration are undefined. * * <p>Keys and values may be null. All optional multimap methods are supported, * and all returned views are modifiable. * * <p>This class is not threadsafe when any concurrent operations update the * multimap. Concurrent read operations will work correctly. To allow concurrent * update operations, wrap your multimap with a call to {@link * Multimaps#synchronizedListMultimap}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap"> * {@code Multimap}</a>. * * @author Mike Bostock * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public class LinkedListMultimap<K, V> implements ListMultimap<K, V>, Serializable { /* * Order is maintained using a linked list containing all key-value pairs. In * addition, a series of disjoint linked lists of "siblings", each containing * the values for a specific key, is used to implement {@link * ValueForKeyIterator} in constant time. */ private static final class Node<K, V> { final K key; V value; Node<K, V> next; // the next node (with any key) Node<K, V> previous; // the previous node (with any key) Node<K, V> nextSibling; // the next node with the same key Node<K, V> previousSibling; // the previous node with the same key Node(@Nullable K key, @Nullable V value) { this.key = key; this.value = value; } @Override public String toString() { return key + "=" + value; } } private transient Node<K, V> head; // the head for all keys private transient Node<K, V> tail; // the tail for all keys private transient Multiset<K> keyCount; // the number of values for each key private transient Map<K, Node<K, V>> keyToKeyHead; // the head for a given key private transient Map<K, Node<K, V>> keyToKeyTail; // the tail for a given key /** * Creates a new, empty {@code LinkedListMultimap} with the default initial * capacity. */ public static <K, V> LinkedListMultimap<K, V> create() { return new LinkedListMultimap<K, V>(); } /** * Constructs an empty {@code LinkedListMultimap} with enough capacity to hold * the specified number of keys without rehashing. * * @param expectedKeys the expected number of distinct keys * @throws IllegalArgumentException if {@code expectedKeys} is negative */ public static <K, V> LinkedListMultimap<K, V> create(int expectedKeys) { return new LinkedListMultimap<K, V>(expectedKeys); } /** * Constructs a {@code LinkedListMultimap} with the same mappings as the * specified {@code Multimap}. The new multimap has the same * {@link Multimap#entries()} iteration order as the input multimap. * * @param multimap the multimap whose contents are copied to this multimap */ public static <K, V> LinkedListMultimap<K, V> create( Multimap<? extends K, ? extends V> multimap) { return new LinkedListMultimap<K, V>(multimap); } LinkedListMultimap() { keyCount = LinkedHashMultiset.create(); keyToKeyHead = Maps.newHashMap(); keyToKeyTail = Maps.newHashMap(); } private LinkedListMultimap(int expectedKeys) { keyCount = LinkedHashMultiset.create(expectedKeys); keyToKeyHead = Maps.newHashMapWithExpectedSize(expectedKeys); keyToKeyTail = Maps.newHashMapWithExpectedSize(expectedKeys); } private LinkedListMultimap(Multimap<? extends K, ? extends V> multimap) { this(multimap.keySet().size()); putAll(multimap); } /** * Adds a new node for the specified key-value pair before the specified * {@code nextSibling} element, or at the end of the list if {@code * nextSibling} is null. Note: if {@code nextSibling} is specified, it MUST be * for an node for the same {@code key}! */ private Node<K, V> addNode( @Nullable K key, @Nullable V value, @Nullable Node<K, V> nextSibling) { Node<K, V> node = new Node<K, V>(key, value); if (head == null) { // empty list head = tail = node; keyToKeyHead.put(key, node); keyToKeyTail.put(key, node); } else if (nextSibling == null) { // non-empty list, add to tail tail.next = node; node.previous = tail; Node<K, V> keyTail = keyToKeyTail.get(key); if (keyTail == null) { // first for this key keyToKeyHead.put(key, node); } else { keyTail.nextSibling = node; node.previousSibling = keyTail; } keyToKeyTail.put(key, node); tail = node; } else { // non-empty list, insert before nextSibling node.previous = nextSibling.previous; node.previousSibling = nextSibling.previousSibling; node.next = nextSibling; node.nextSibling = nextSibling; if (nextSibling.previousSibling == null) { // nextSibling was key head keyToKeyHead.put(key, node); } else { nextSibling.previousSibling.nextSibling = node; } if (nextSibling.previous == null) { // nextSibling was head head = node; } else { nextSibling.previous.next = node; } nextSibling.previous = node; nextSibling.previousSibling = node; } keyCount.add(key); return node; } /** * Removes the specified node from the linked list. This method is only * intended to be used from the {@code Iterator} classes. See also {@link * LinkedListMultimap#removeAllNodes(Object)}. */ private void removeNode(Node<K, V> node) { if (node.previous != null) { node.previous.next = node.next; } else { // node was head head = node.next; } if (node.next != null) { node.next.previous = node.previous; } else { // node was tail tail = node.previous; } if (node.previousSibling != null) { node.previousSibling.nextSibling = node.nextSibling; } else if (node.nextSibling != null) { // node was key head keyToKeyHead.put(node.key, node.nextSibling); } else { keyToKeyHead.remove(node.key); // don't leak a key-null entry } if (node.nextSibling != null) { node.nextSibling.previousSibling = node.previousSibling; } else if (node.previousSibling != null) { // node was key tail keyToKeyTail.put(node.key, node.previousSibling); } else { keyToKeyTail.remove(node.key); // don't leak a key-null entry } keyCount.remove(node.key); } /** Removes all nodes for the specified key. */ private void removeAllNodes(@Nullable Object key) { for (Iterator<V> i = new ValueForKeyIterator(key); i.hasNext();) { i.next(); i.remove(); } } /** Helper method for verifying that an iterator element is present. */ private static void checkElement(@Nullable Object node) { if (node == null) { throw new NoSuchElementException(); } } /** An {@code Iterator} over all nodes. */ private class NodeIterator implements ListIterator<Node<K, V>> { int nextIndex; Node<K, V> next; Node<K, V> current; Node<K, V> previous; NodeIterator() { next = head; } NodeIterator(int index) { int size = size(); Preconditions.checkPositionIndex(index, size); if (index >= (size / 2)) { previous = tail; nextIndex = size; while (index++ < size) { previous(); } } else { next = head; while (index-- > 0) { next(); } } current = null; } @Override public boolean hasNext() { return next != null; } @Override public Node<K, V> next() { checkElement(next); previous = current = next; next = next.next; nextIndex++; return current; } @Override public void remove() { checkState(current != null); if (current != next) { // after call to next() previous = current.previous; nextIndex--; } else { // after call to previous() next = current.next; } removeNode(current); current = null; } @Override public boolean hasPrevious() { return previous != null; } @Override public Node<K, V> previous() { checkElement(previous); next = current = previous; previous = previous.previous; nextIndex--; return current; } @Override public int nextIndex() { return nextIndex; } @Override public int previousIndex() { return nextIndex - 1; } @Override public void set(Node<K, V> e) { throw new UnsupportedOperationException(); } @Override public void add(Node<K, V> e) { throw new UnsupportedOperationException(); } void setValue(V value) { checkState(current != null); current.value = value; } } /** An {@code Iterator} over distinct keys in key head order. */ private class DistinctKeyIterator implements Iterator<K> { final Set<K> seenKeys = Sets.<K>newHashSetWithExpectedSize(keySet().size()); Node<K, V> next = head; Node<K, V> current; @Override public boolean hasNext() { return next != null; } @Override public K next() { checkElement(next); current = next; seenKeys.add(current.key); do { // skip ahead to next unseen key next = next.next; } while ((next != null) && !seenKeys.add(next.key)); return current.key; } @Override public void remove() { checkState(current != null); removeAllNodes(current.key); current = null; } } /** A {@code ListIterator} over values for a specified key. */ private class ValueForKeyIterator implements ListIterator<V> { final Object key; int nextIndex; Node<K, V> next; Node<K, V> current; Node<K, V> previous; /** Constructs a new iterator over all values for the specified key. */ ValueForKeyIterator(@Nullable Object key) { this.key = key; next = keyToKeyHead.get(key); } /** * Constructs a new iterator over all values for the specified key starting * at the specified index. This constructor is optimized so that it starts * at either the head or the tail, depending on which is closer to the * specified index. This allows adds to the tail to be done in constant * time. * * @throws IndexOutOfBoundsException if index is invalid */ public ValueForKeyIterator(@Nullable Object key, int index) { int size = keyCount.count(key); Preconditions.checkPositionIndex(index, size); if (index >= (size / 2)) { previous = keyToKeyTail.get(key); nextIndex = size; while (index++ < size) { previous(); } } else { next = keyToKeyHead.get(key); while (index-- > 0) { next(); } } this.key = key; current = null; } @Override public boolean hasNext() { return next != null; } @Override public V next() { checkElement(next); previous = current = next; next = next.nextSibling; nextIndex++; return current.value; } @Override public boolean hasPrevious() { return previous != null; } @Override public V previous() { checkElement(previous); next = current = previous; previous = previous.previousSibling; nextIndex--; return current.value; } @Override public int nextIndex() { return nextIndex; } @Override public int previousIndex() { return nextIndex - 1; } @Override public void remove() { checkState(current != null); if (current != next) { // after call to next() previous = current.previousSibling; nextIndex--; } else { // after call to previous() next = current.nextSibling; } removeNode(current); current = null; } @Override public void set(V value) { checkState(current != null); current.value = value; } @Override @SuppressWarnings("unchecked") public void add(V value) { previous = addNode((K) key, value, next); nextIndex++; current = null; } } // Query Operations @Override public int size() { return keyCount.size(); } @Override public boolean isEmpty() { return head == null; } @Override public boolean containsKey(@Nullable Object key) { return keyToKeyHead.containsKey(key); } @Override public boolean containsValue(@Nullable Object value) { for (Iterator<Node<K, V>> i = new NodeIterator(); i.hasNext();) { if (Objects.equal(i.next().value, value)) { return true; } } return false; } @Override public boolean containsEntry(@Nullable Object key, @Nullable Object value) { for (Iterator<V> i = new ValueForKeyIterator(key); i.hasNext();) { if (Objects.equal(i.next(), value)) { return true; } } return false; } // Modification Operations /** * 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) { addNode(key, value, null); return true; } @Override public boolean remove(@Nullable Object key, @Nullable Object value) { Iterator<V> values = new ValueForKeyIterator(key); while (values.hasNext()) { if (Objects.equal(values.next(), value)) { values.remove(); return true; } } return false; } // Bulk Operations @Override public boolean putAll(@Nullable K key, Iterable<? extends V> values) { boolean changed = false; for (V value : values) { changed |= put(key, value); } return changed; } @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { boolean changed = false; for (Entry<? extends K, ? extends V> entry : multimap.entries()) { changed |= put(entry.getKey(), entry.getValue()); } return changed; } /** * {@inheritDoc} * * <p>If any entries for the specified {@code key} already exist in the * multimap, their values are changed in-place without affecting the iteration * order. * * <p>The returned list is immutable and implements * {@link java.util.RandomAccess}. */ @Override public List<V> replaceValues(@Nullable K key, Iterable<? extends V> values) { List<V> oldValues = getCopy(key); ListIterator<V> keyValues = new ValueForKeyIterator(key); Iterator<? extends V> newValues = values.iterator(); // Replace existing values, if any. while (keyValues.hasNext() && newValues.hasNext()) { keyValues.next(); keyValues.set(newValues.next()); } // Remove remaining old values, if any. while (keyValues.hasNext()) { keyValues.next(); keyValues.remove(); } // Add remaining new values, if any. while (newValues.hasNext()) { keyValues.add(newValues.next()); } return oldValues; } private List<V> getCopy(@Nullable Object key) { return unmodifiableList(Lists.newArrayList(new ValueForKeyIterator(key))); } /** * {@inheritDoc} * * <p>The returned list is immutable and implements * {@link java.util.RandomAccess}. */ @Override public List<V> removeAll(@Nullable Object key) { List<V> oldValues = getCopy(key); removeAllNodes(key); return oldValues; } @Override public void clear() { head = null; tail = null; keyCount.clear(); keyToKeyHead.clear(); keyToKeyTail.clear(); } // Views /** * {@inheritDoc} * * <p>If the multimap is modified while an iteration over the list is in * progress (except through the iterator's own {@code add}, {@code set} or * {@code remove} operations) the results of the iteration are undefined. * * <p>The returned list is not serializable and does not have random access. */ @Override public List<V> get(final @Nullable K key) { return new AbstractSequentialList<V>() { @Override public int size() { return keyCount.count(key); } @Override public ListIterator<V> listIterator(int index) { return new ValueForKeyIterator(key, index); } @Override public boolean removeAll(Collection<?> c) { return Iterators.removeAll(iterator(), c); } @Override public boolean retainAll(Collection<?> c) { return Iterators.retainAll(iterator(), c); } }; } private transient Set<K> keySet; @Override public Set<K> keySet() { Set<K> result = keySet; if (result == null) { keySet = result = new AbstractSet<K>() { @Override public int size() { return keyCount.elementSet().size(); } @Override public Iterator<K> iterator() { return new DistinctKeyIterator(); } @Override public boolean contains(Object key) { // for performance return keyCount.contains(key); } @Override public boolean removeAll(Collection<?> c) { checkNotNull(c); // eager for GWT return super.removeAll(c); } }; } return result; } private transient Multiset<K> keys; @Override public Multiset<K> keys() { Multiset<K> result = keys; if (result == null) { keys = result = new MultisetView(); } return result; } private class MultisetView extends AbstractCollection<K> implements Multiset<K> { @Override public int size() { return keyCount.size(); } @Override public Iterator<K> iterator() { final Iterator<Node<K, V>> nodes = new NodeIterator(); return new Iterator<K>() { @Override public boolean hasNext() { return nodes.hasNext(); } @Override public K next() { return nodes.next().key; } @Override public void remove() { nodes.remove(); } }; } @Override public int count(@Nullable Object key) { return keyCount.count(key); } @Override public int add(@Nullable K key, int occurrences) { throw new UnsupportedOperationException(); } @Override public int remove(@Nullable Object key, int occurrences) { checkArgument(occurrences >= 0); int oldCount = count(key); Iterator<V> values = new ValueForKeyIterator(key); while ((occurrences-- > 0) && values.hasNext()) { values.next(); values.remove(); } return oldCount; } @Override public int setCount(K element, int count) { return setCountImpl(this, element, count); } @Override public boolean setCount(K element, int oldCount, int newCount) { return setCountImpl(this, element, oldCount, newCount); } @Override public boolean removeAll(Collection<?> c) { return Iterators.removeAll(iterator(), c); } @Override public boolean retainAll(Collection<?> c) { return Iterators.retainAll(iterator(), c); } @Override public Set<K> elementSet() { return keySet(); } @Override public Set<Entry<K>> entrySet() { // TODO(jlevy): lazy init? return new AbstractSet<Entry<K>>() { @Override public int size() { return keyCount.elementSet().size(); } @Override public Iterator<Entry<K>> iterator() { final Iterator<K> keyIterator = new DistinctKeyIterator(); return new Iterator<Entry<K>>() { @Override public boolean hasNext() { return keyIterator.hasNext(); } @Override public Entry<K> next() { final K key = keyIterator.next(); return new Multisets.AbstractEntry<K>() { @Override public K getElement() { return key; } @Override public int getCount() { return keyCount.count(key); } }; } @Override public void remove() { keyIterator.remove(); } }; } }; } @Override public boolean equals(@Nullable Object object) { return keyCount.equals(object); } @Override public int hashCode() { return keyCount.hashCode(); } @Override public String toString() { return keyCount.toString(); // XXX observe order? } } private transient List<V> valuesList; /** * {@inheritDoc} * * <p>The iterator generated by the returned collection traverses the values * in the order they were added to the multimap. Because the values may have * duplicates and follow the insertion ordering, this method returns a {@link * List}, instead of the {@link Collection} specified in the {@link * ListMultimap} interface. */ @Override public List<V> values() { List<V> result = valuesList; if (result == null) { valuesList = result = new AbstractSequentialList<V>() { @Override public int size() { return keyCount.size(); } @Override public ListIterator<V> listIterator(int index) { final NodeIterator nodes = new NodeIterator(index); return new ListIterator<V>() { @Override public boolean hasNext() { return nodes.hasNext(); } @Override public V next() { return nodes.next().value; } @Override public boolean hasPrevious() { return nodes.hasPrevious(); } @Override public V previous() { return nodes.previous().value; } @Override public int nextIndex() { return nodes.nextIndex(); } @Override public int previousIndex() { return nodes.previousIndex(); } @Override public void remove() { nodes.remove(); } @Override public void set(V e) { nodes.setValue(e); } @Override public void add(V e) { throw new UnsupportedOperationException(); } }; } }; } return result; } private static <K, V> Entry<K, V> createEntry(final Node<K, V> node) { return new AbstractMapEntry<K, V>() { @Override public K getKey() { return node.key; } @Override public V getValue() { return node.value; } @Override public V setValue(V value) { V oldValue = node.value; node.value = value; return oldValue; } }; } private transient List<Entry<K, V>> entries; /** * {@inheritDoc} * * <p>The iterator generated by the returned collection traverses the entries * in the order they were added to the multimap. Because the entries may have * duplicates and follow the insertion ordering, this method returns a {@link * List}, instead of the {@link Collection} specified in the {@link * ListMultimap} interface. * * <p>An entry's {@link Entry#getKey} method always returns the same key, * regardless of what happens subsequently. As long as the corresponding * key-value mapping is not removed from the multimap, {@link Entry#getValue} * returns the value from the multimap, which may change over time, and {@link * Entry#setValue} modifies that value. Removing the mapping from the * multimap does not alter the value returned by {@code getValue()}, though a * subsequent {@code setValue()} call won't update the multimap but will lead * to a revised value being returned by {@code getValue()}. */ @Override public List<Entry<K, V>> entries() { List<Entry<K, V>> result = entries; if (result == null) { entries = result = new AbstractSequentialList<Entry<K, V>>() { @Override public int size() { return keyCount.size(); } @Override public ListIterator<Entry<K, V>> listIterator(int index) { final ListIterator<Node<K, V>> nodes = new NodeIterator(index); return new ListIterator<Entry<K, V>>() { @Override public boolean hasNext() { return nodes.hasNext(); } @Override public Entry<K, V> next() { return createEntry(nodes.next()); } @Override public void remove() { nodes.remove(); } @Override public boolean hasPrevious() { return nodes.hasPrevious(); } @Override public Map.Entry<K, V> previous() { return createEntry(nodes.previous()); } @Override public int nextIndex() { return nodes.nextIndex(); } @Override public int previousIndex() { return nodes.previousIndex(); } @Override public void set(Map.Entry<K, V> e) { throw new UnsupportedOperationException(); } @Override public void add(Map.Entry<K, V> e) { throw new UnsupportedOperationException(); } }; } }; } return result; } private class AsMapEntries extends AbstractSet<Entry<K, Collection<V>>> { @Override public int size() { return keyCount.elementSet().size(); } @Override public Iterator<Entry<K, Collection<V>>> iterator() { final Iterator<K> keyIterator = new DistinctKeyIterator(); return new Iterator<Entry<K, Collection<V>>>() { @Override public boolean hasNext() { return keyIterator.hasNext(); } @Override public Entry<K, Collection<V>> next() { final K key = keyIterator.next(); return new AbstractMapEntry<K, Collection<V>>() { @Override public K getKey() { return key; } @Override public Collection<V> getValue() { return LinkedListMultimap.this.get(key); } }; } @Override public void remove() { keyIterator.remove(); } }; } // TODO(jlevy): Override contains() and remove() for better performance. } private transient Map<K, Collection<V>> map; @Override public Map<K, Collection<V>> asMap() { Map<K, Collection<V>> result = map; if (result == null) { map = result = new AbstractMap<K, Collection<V>>() { Set<Entry<K, Collection<V>>> entrySet; @Override public Set<Entry<K, Collection<V>>> entrySet() { Set<Entry<K, Collection<V>>> result = entrySet; if (result == null) { entrySet = result = new AsMapEntries(); } return result; } // The following methods are included for performance. @Override public boolean containsKey(@Nullable Object key) { return LinkedListMultimap.this.containsKey(key); } @SuppressWarnings("unchecked") @Override public Collection<V> get(@Nullable Object key) { Collection<V> collection = LinkedListMultimap.this.get((K) key); return collection.isEmpty() ? null : collection; } @Override public Collection<V> remove(@Nullable Object key) { Collection<V> collection = removeAll(key); return collection.isEmpty() ? null : collection; } }; } return result; } // Comparison and hashing /** * 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 other) { if (other == this) { return true; } if (other instanceof Multimap) { Multimap<?, ?> that = (Multimap<?, ?>) other; return this.asMap().equals(that.asMap()); } return false; } /** * 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}. */ @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(); } /** * @serialData the number of distinct keys, and then for each distinct key: * the first key, the number of values for that key, and the key's values, * followed by successive keys and values from the entries() ordering */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeInt(size()); for (Entry<K, V> entry : entries()) { stream.writeObject(entry.getKey()); stream.writeObject(entry.getValue()); } } @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); keyCount = LinkedHashMultiset.create(); keyToKeyHead = Maps.newHashMap(); keyToKeyTail = Maps.newHashMap(); int size = stream.readInt(); for (int i = 0; i < size; i++) { @SuppressWarnings("unchecked") // reading data stored by writeObject K key = (K) stream.readObject(); @SuppressWarnings("unchecked") // reading data stored by writeObject V value = (V) stream.readObject(); put(key, value); } } @GwtIncompatible("java serialization not supported") 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.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtIncompatible; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; /** * An immutable {@code SortedMultiset} that stores its elements in a sorted array. Some instances * are ordered by an explicit comparator, while others follow the natural sort ordering of their * elements. Either way, null elements are not supported. * * <p>Unlike {@link Multisets#unmodifiableSortedMultiset}, which is a <i>view</i> of a separate * collection that can still change, an instance of {@code ImmutableSortedMultiset} contains its * own private data and will <i>never</i> change. This class is convenient for {@code public static * final} multisets ("constant multisets") and also lets you easily make a "defensive copy" of a * set provided to your class by a caller. * * <p>The multisets returned by the {@link #headMultiset}, {@link #tailMultiset}, and * {@link #subMultiset} methods share the same array as the original multiset, preventing that * array from being garbage collected. If this is a concern, the data may be copied into a * correctly-sized array by calling {@link #copyOfSorted}. * * <p><b>Note on element equivalence:</b> The {@link #contains(Object)}, * {@link #containsAll(Collection)}, and {@link #equals(Object)} implementations must check whether * a provided object is equivalent to an element in the collection. Unlike most collections, an * {@code ImmutableSortedMultiset} doesn't use {@link Object#equals} to determine if two elements * are equivalent. Instead, with an explicit comparator, the following relation determines whether * elements {@code x} and {@code y} are equivalent: * * <pre> {@code * * {(x, y) | comparator.compare(x, y) == 0}}</pre> * * With natural ordering of elements, the following relation determines whether two elements are * equivalent: * * <pre> {@code * * {(x, y) | x.compareTo(y) == 0}}</pre> * * <b>Warning:</b> Like most multisets, an {@code ImmutableSortedMultiset} will not function * correctly if an element is modified after being placed in the multiset. For this reason, and to * avoid general confusion, it is strongly recommended to place only immutable objects into this * collection. * * <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 type 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 Louis Wasserman */ @GwtIncompatible("hasn't been tested yet") abstract class ImmutableSortedMultiset<E> extends ImmutableSortedMultisetFauxverideShim<E> implements SortedMultiset<E> { // TODO(user): GWT compatibility private static final Comparator<Comparable> NATURAL_ORDER = Ordering.natural(); private static final ImmutableSortedMultiset<Comparable> NATURAL_EMPTY_MULTISET = new EmptyImmutableSortedMultiset<Comparable>(NATURAL_ORDER); /** * Returns the empty immutable sorted multiset. */ @SuppressWarnings("unchecked") public static <E> ImmutableSortedMultiset<E> of() { return (ImmutableSortedMultiset) NATURAL_EMPTY_MULTISET; } /** * Returns an immutable sorted multiset containing a single element. */ public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(E element) { return RegularImmutableSortedMultiset.createFromSorted( NATURAL_ORDER, ImmutableList.of(Multisets.immutableEntry(checkNotNull(element), 1))); } /** * Returns an immutable sorted multiset containing the given elements sorted by their natural * ordering. * * @throws NullPointerException if any element is null */ @SuppressWarnings("unchecked") public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(E e1, E e2) { return copyOf(Ordering.natural(), Arrays.asList(e1, e2)); } /** * Returns an immutable sorted multiset containing the given elements sorted by their natural * ordering. * * @throws NullPointerException if any element is null */ @SuppressWarnings("unchecked") public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(E e1, E e2, E e3) { return copyOf(Ordering.natural(), Arrays.asList(e1, e2, e3)); } /** * Returns an immutable sorted multiset containing the given elements sorted by their natural * ordering. * * @throws NullPointerException if any element is null */ @SuppressWarnings("unchecked") public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of( E e1, E e2, E e3, E e4) { return copyOf(Ordering.natural(), Arrays.asList(e1, e2, e3, e4)); } /** * Returns an immutable sorted multiset containing the given elements sorted by their natural * ordering. * * @throws NullPointerException if any element is null */ @SuppressWarnings("unchecked") public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of( E e1, E e2, E e3, E e4, E e5) { return copyOf(Ordering.natural(), Arrays.asList(e1, e2, e3, e4, e5)); } /** * Returns an immutable sorted multiset containing the given elements sorted by their natural * ordering. * * @throws NullPointerException if any element is null */ @SuppressWarnings("unchecked") public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E... remaining) { int size = remaining.length + 6; List<E> all = new ArrayList<E>(size); Collections.addAll(all, e1, e2, e3, e4, e5, e6); Collections.addAll(all, remaining); return copyOf(Ordering.natural(), all); } /** * Returns an immutable sorted multiset containing the given elements sorted by their natural * ordering. * * @throws NullPointerException if any of {@code elements} is null */ public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> copyOf(E[] elements) { return copyOf(Ordering.natural(), Arrays.asList(elements)); } /** * Returns an immutable sorted multiset containing the given elements sorted by their natural * ordering. To create a copy of a {@code SortedMultiset} that preserves the * comparator, call {@link #copyOfSorted} instead. This method iterates over {@code elements} at * most once. * * <p>Note that if {@code s} is a {@code multiset<String>}, then {@code * ImmutableSortedMultiset.copyOf(s)} returns an {@code ImmutableSortedMultiset<String>} * containing each of the strings in {@code s}, while {@code ImmutableSortedMultiset.of(s)} * returns an {@code ImmutableSortedMultiset<multiset<String>>} containing one element (the given * multiset itself). * * <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. * * <p>This method is not type-safe, as it may be called on elements that are not mutually * comparable. * * @throws ClassCastException if the elements are not mutually comparable * @throws NullPointerException if any of {@code elements} is null */ public static <E> ImmutableSortedMultiset<E> copyOf(Iterable<? extends E> elements) { // Hack around E not being a subtype of Comparable. // Unsafe, see ImmutableSortedMultisetFauxverideShim. @SuppressWarnings("unchecked") Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural(); return copyOf(naturalOrder, elements); } /** * Returns an immutable sorted multiset containing the given elements sorted by their natural * ordering. * * <p>This method is not type-safe, as it may be called on elements that are not mutually * comparable. * * @throws ClassCastException if the elements are not mutually comparable * @throws NullPointerException if any of {@code elements} is null */ public static <E> ImmutableSortedMultiset<E> copyOf(Iterator<? extends E> elements) { // Hack around E not being a subtype of Comparable. // Unsafe, see ImmutableSortedMultisetFauxverideShim. @SuppressWarnings("unchecked") Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural(); return copyOfInternal(naturalOrder, elements); } /** * Returns an immutable sorted multiset containing the given elements sorted by the given {@code * Comparator}. * * @throws NullPointerException if {@code comparator} or any of {@code elements} is null */ public static <E> ImmutableSortedMultiset<E> copyOf( Comparator<? super E> comparator, Iterator<? extends E> elements) { checkNotNull(comparator); return copyOfInternal(comparator, elements); } /** * Returns an immutable sorted multiset containing the given elements sorted by the given {@code * Comparator}. This method iterates over {@code elements} at most once. * * <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. * * @throws NullPointerException if {@code comparator} or any of {@code elements} is null */ public static <E> ImmutableSortedMultiset<E> copyOf( Comparator<? super E> comparator, Iterable<? extends E> elements) { checkNotNull(comparator); return copyOfInternal(comparator, elements); } /** * Returns an immutable sorted multiset containing the elements of a sorted multiset, sorted by * the same {@code Comparator}. That behavior differs from {@link #copyOf(Iterable)}, which * always uses the natural ordering of the elements. * * <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. * * <p>This method is safe to use even when {@code sortedMultiset} is a synchronized or concurrent * collection that is currently being modified by another thread. * * @throws NullPointerException if {@code sortedMultiset} or any of its elements is null */ @SuppressWarnings("unchecked") public static <E> ImmutableSortedMultiset<E> copyOfSorted(SortedMultiset<E> sortedMultiset) { Comparator<? super E> comparator = sortedMultiset.comparator(); if (comparator == null) { comparator = (Comparator<? super E>) NATURAL_ORDER; } return copyOfInternal(comparator, sortedMultiset); } @SuppressWarnings("unchecked") private static <E> ImmutableSortedMultiset<E> copyOfInternal( Comparator<? super E> comparator, Iterable<? extends E> iterable) { if (SortedIterables.hasSameComparator(comparator, iterable) && iterable instanceof ImmutableSortedMultiset<?>) { ImmutableSortedMultiset<E> multiset = (ImmutableSortedMultiset<E>) iterable; if (!multiset.isPartialView()) { return (ImmutableSortedMultiset<E>) iterable; } } ImmutableList<Entry<E>> entries = (ImmutableList) ImmutableList.copyOf(SortedIterables.sortedCounts(comparator, iterable)); if (entries.isEmpty()) { return emptyMultiset(comparator); } verifyEntries(entries); return RegularImmutableSortedMultiset.createFromSorted(comparator, entries); } private static <E> ImmutableSortedMultiset<E> copyOfInternal( Comparator<? super E> comparator, Iterator<? extends E> iterator) { @SuppressWarnings("unchecked") // We can safely cast from IL<Entry<? extends E>> to IL<Entry<E>> ImmutableList<Entry<E>> entries = (ImmutableList) ImmutableList.copyOf(SortedIterables.sortedCounts(comparator, iterator)); if (entries.isEmpty()) { return emptyMultiset(comparator); } verifyEntries(entries); return RegularImmutableSortedMultiset.createFromSorted(comparator, entries); } private static <E> void verifyEntries(Collection<Entry<E>> entries) { for (Entry<E> entry : entries) { checkNotNull(entry.getElement()); } } @SuppressWarnings("unchecked") static <E> ImmutableSortedMultiset<E> emptyMultiset(Comparator<? super E> comparator) { if (NATURAL_ORDER.equals(comparator)) { return (ImmutableSortedMultiset) NATURAL_EMPTY_MULTISET; } return new EmptyImmutableSortedMultiset<E>(comparator); } private final transient Comparator<? super E> comparator; ImmutableSortedMultiset(Comparator<? super E> comparator) { this.comparator = checkNotNull(comparator); } @Override public Comparator<? super E> comparator() { return comparator; } // Pretend the comparator can compare anything. If it turns out it can't // compare two elements, it'll throw a CCE. Only methods that are specified to // throw CCE should call this. @SuppressWarnings("unchecked") Comparator<Object> unsafeComparator() { return (Comparator<Object>) comparator; } private transient Comparator<? super E> reverseComparator; Comparator<? super E> reverseComparator() { Comparator<? super E> result = reverseComparator; if (result == null) { return reverseComparator = Ordering.from(comparator).<E>reverse(); } return result; } private transient ImmutableSortedSet<E> elementSet; @Override public ImmutableSortedSet<E> elementSet() { ImmutableSortedSet<E> result = elementSet; if (result == null) { return elementSet = createElementSet(); } return result; } abstract ImmutableSortedSet<E> createElementSet(); abstract ImmutableSortedSet<E> createDescendingElementSet(); transient ImmutableSortedMultiset<E> descendingMultiset; @Override public ImmutableSortedMultiset<E> descendingMultiset() { ImmutableSortedMultiset<E> result = descendingMultiset; if (result == null) { return descendingMultiset = new DescendingImmutableSortedMultiset<E>(this); } return result; } abstract UnmodifiableIterator<Entry<E>> descendingEntryIterator(); /** * {@inheritDoc} * * <p>This implementation is guaranteed to throw an {@link UnsupportedOperationException}. */ @Override public final Entry<E> pollFirstEntry() { throw new UnsupportedOperationException(); } /** * {@inheritDoc} * * <p>This implementation is guaranteed to throw an {@link UnsupportedOperationException}. */ @Override public Entry<E> pollLastEntry() { throw new UnsupportedOperationException(); } @Override public abstract ImmutableSortedMultiset<E> headMultiset(E upperBound, BoundType boundType); @Override public ImmutableSortedMultiset<E> subMultiset( E lowerBound, BoundType lowerBoundType, E upperBound, BoundType upperBoundType) { return tailMultiset(lowerBound, lowerBoundType).headMultiset(upperBound, upperBoundType); } @Override public abstract ImmutableSortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType); /** * Returns a builder that creates immutable sorted multisets with an explicit comparator. If the * comparator has a more general type than the set being generated, such as creating a {@code * SortedMultiset<Integer>} with a {@code Comparator<Number>}, use the {@link Builder} * constructor instead. * * @throws NullPointerException if {@code comparator} is null */ public static <E> Builder<E> orderedBy(Comparator<E> comparator) { return new Builder<E>(comparator); } /** * Returns a builder that creates immutable sorted multisets whose elements are ordered by the * reverse of their natural ordering. * * <p>Note: the type parameter {@code E} extends {@code Comparable<E>} rather than {@code * Comparable<? super E>} as a workaround for javac <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6468354">bug 6468354</a>. */ public static <E extends Comparable<E>> Builder<E> reverseOrder() { return new Builder<E>(Ordering.natural().reverse()); } /** * Returns a builder that creates immutable sorted multisets whose elements are ordered by their * natural ordering. The sorted multisets use {@link Ordering#natural()} as the comparator. This * method provides more type-safety than {@link #builder}, as it can be called only for classes * that implement {@link Comparable}. * * <p>Note: the type parameter {@code E} extends {@code Comparable<E>} rather than {@code * Comparable<? super E>} as a workaround for javac <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6468354">bug 6468354</a>. */ public static <E extends Comparable<E>> Builder<E> naturalOrder() { return new Builder<E>(Ordering.natural()); } /** * A builder for creating immutable multiset instances, especially {@code public static final} * multisets ("constant multisets"). Example: * * <pre> {@code * * public static final ImmutableSortedMultiset<Bean> BEANS = * new ImmutableSortedMultiset.Builder<Bean>() * .addCopies(Bean.COCOA, 4) * .addCopies(Bean.GARDEN, 6) * .addCopies(Bean.RED, 8) * .addCopies(Bean.BLACK_EYED, 10) * .build();}</pre> * * Builder instances can be reused; it is safe to call {@link #build} multiple times to build * multiple multisets in series. */ public static class Builder<E> extends ImmutableMultiset.Builder<E> { private final Comparator<? super E> comparator; /** * Creates a new builder. The returned builder is equivalent to the builder generated by * {@link ImmutableSortedMultiset#orderedBy(Comparator)}. */ public Builder(Comparator<? super E> comparator) { super(TreeMultiset.<E>create(comparator)); this.comparator = checkNotNull(comparator); } /** * Adds {@code element} to the {@code ImmutableSortedMultiset}. * * @param element the element to add * @return this {@code Builder} object * @throws NullPointerException if {@code element} is null */ @Override public Builder<E> add(E element) { super.add(element); return this; } /** * Adds a number of occurrences of an element to this {@code ImmutableSortedMultiset}. * * @param element the element to add * @param occurrences the number of occurrences of the element to add. May be zero, in which * case no change will be made. * @return this {@code Builder} object * @throws NullPointerException if {@code element} is null * @throws IllegalArgumentException if {@code occurrences} is negative, or if this operation * would result in more than {@link Integer#MAX_VALUE} occurrences of the element */ @Override public Builder<E> addCopies(E element, int occurrences) { super.addCopies(element, occurrences); return this; } /** * Adds or removes the necessary occurrences of an element such that the element attains the * desired count. * * @param element the element to add or remove occurrences of * @param count the desired count of the element in this multiset * @return this {@code Builder} object * @throws NullPointerException if {@code element} is null * @throws IllegalArgumentException if {@code count} is negative */ @Override public Builder<E> setCount(E element, int count) { super.setCount(element, count); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableSortedMultiset}. * * @param elements the elements to add * @return this {@code Builder} object * @throws NullPointerException if {@code elements} is null or contains a null element */ @Override public Builder<E> add(E... elements) { super.add(elements); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableSortedMultiset}. * * @param elements the {@code Iterable} to add to the {@code ImmutableSortedMultiset} * @return this {@code Builder} object * @throws NullPointerException if {@code elements} is null or contains a null element */ @Override public Builder<E> addAll(Iterable<? extends E> elements) { super.addAll(elements); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableSortedMultiset}. * * @param elements the elements to add to the {@code ImmutableSortedMultiset} * @return this {@code Builder} object * @throws NullPointerException if {@code elements} is null or contains a null element */ @Override public Builder<E> addAll(Iterator<? extends E> elements) { super.addAll(elements); return this; } /** * Returns a newly-created {@code ImmutableSortedMultiset} based on the contents of the {@code * Builder}. */ @Override public ImmutableSortedMultiset<E> build() { return copyOf(comparator, contents); } } private static final class SerializedForm implements Serializable { Comparator comparator; Object[] elements; int[] counts; SerializedForm(SortedMultiset<?> multiset) { this.comparator = multiset.comparator(); int n = multiset.entrySet().size(); elements = new Object[n]; counts = new int[n]; int i = 0; for (Entry<?> entry : multiset.entrySet()) { elements[i] = entry.getElement(); counts[i] = entry.getCount(); i++; } } @SuppressWarnings("unchecked") Object readResolve() { int n = elements.length; Builder<Object> builder = orderedBy(comparator); for (int i = 0; i < n; i++) { builder.addCopies(elements[i], counts[i]); } return builder.build(); } } @Override Object writeReplace() { return new SerializedForm(this); } }
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; /** * A collection similar to a {@code Map}, but which may associate multiple * values with a single key. If you call {@link #put} twice, with the same key * but different values, the multimap contains mappings from the key to both * values. * * <p>The methods {@link #get}, {@link #keySet}, {@link #keys}, {@link #values}, * {@link #entries}, and {@link #asMap} return collections that are views of the * multimap. If the multimap is modifiable, updating it can change the contents * of those collections, and updating the collections will change the multimap. * In contrast, {@link #replaceValues} and {@link #removeAll} return collections * that are independent of subsequent multimap changes. * * <p>Depending on the implementation, a multimap may or may not allow duplicate * key-value pairs. In other words, the multimap contents after adding the same * key and value twice varies between implementations. In multimaps allowing * duplicates, the multimap will contain two mappings, and {@code get} will * return a collection that includes the value twice. In multimaps not * supporting duplicates, the multimap will contain a single mapping from the * key to the value, and {@code get} will return a collection that includes the * value once. * * <p>All methods that alter the multimap are optional, and the views returned * by the multimap may or may not be modifiable. When modification isn't * supported, those methods will throw an {@link UnsupportedOperationException}. * * <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 * @param <K> the type of keys maintained by this multimap * @param <V> the type of mapped values * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public interface Multimap<K, V> { // Query Operations /** Returns the number of key-value pairs in the multimap. */ int size(); /** Returns {@code true} if the multimap contains no key-value pairs. */ boolean isEmpty(); /** * Returns {@code true} if the multimap contains any values for the specified * key. * * @param key key to search for in multimap */ boolean containsKey(@Nullable Object key); /** * Returns {@code true} if the multimap contains the specified value for any * key. * * @param value value to search for in multimap */ boolean containsValue(@Nullable Object value); /** * Returns {@code true} if the multimap contains the specified key-value pair. * * @param key key to search for in multimap * @param value value to search for in multimap */ boolean containsEntry(@Nullable Object key, @Nullable Object value); // Modification Operations /** * Stores a key-value pair in the multimap. * * <p>Some multimap implementations allow duplicate key-value pairs, in which * case {@code put} always adds a new key-value pair and increases the * multimap size by 1. Other implementations prohibit duplicates, and storing * a key-value pair that's already in the multimap has no effect. * * @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 and * doesn't allow duplicates */ boolean put(@Nullable K key, @Nullable V value); /** * Removes a key-value pair from the multimap. * * @param key key of entry to remove from the multimap * @param value value of entry to remove the multimap * @return {@code true} if the multimap changed */ boolean remove(@Nullable Object key, @Nullable Object value); // Bulk Operations /** * Stores a collection of values with the same key. * * @param key key to store in the multimap * @param values values to store in the multimap * @return {@code true} if the multimap changed */ boolean putAll(@Nullable K key, Iterable<? extends V> values); /** * Copies all of another multimap's key-value pairs into this multimap. The * order in which the mappings are added is determined by * {@code multimap.entries()}. * * @param multimap mappings to store in this multimap * @return {@code true} if the multimap changed */ boolean putAll(Multimap<? extends K, ? extends V> multimap); /** * Stores a collection of values with the same key, replacing any existing * values for that key. * * @param key key to store in the multimap * @param values values to store in the multimap * @return the collection of replaced values, or an empty collection if no * values were previously associated with the key. The collection * <i>may</i> be modifiable, but updating it will have no effect on the * multimap. */ Collection<V> replaceValues(@Nullable K key, Iterable<? extends V> values); /** * Removes all values associated with a given key. * * @param key key of entries to remove from the multimap * @return the collection of removed values, or an empty collection if no * values were associated with the provided key. The collection * <i>may</i> be modifiable, but updating it will have no effect on the * multimap. */ Collection<V> removeAll(@Nullable Object key); /** * Removes all key-value pairs from the multimap. */ void clear(); // Views /** * 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. * * @param key key to search for in multimap * @return the collection of values that the key maps to */ Collection<V> get(@Nullable K key); /** * Returns the set of all keys, each appearing once in the returned set. * Changes to the returned set will update the underlying multimap, and vice * versa. * * @return the collection of distinct keys */ Set<K> keySet(); /** * Returns a collection, which may contain duplicates, of all keys. The number * of times of key appears in the returned multiset equals the number of * mappings the key has in the multimap. Changes to the returned multiset will * update the underlying multimap, and vice versa. * * @return a multiset with keys corresponding to the distinct keys of the * multimap and frequencies corresponding to the number of values that * each key maps to */ Multiset<K> keys(); /** * Returns a collection of all values in the multimap. Changes to the returned * collection will update the underlying multimap, and vice versa. * * @return collection of values, which may include the same value multiple * times if it occurs in multiple mappings */ Collection<V> values(); /** * Returns a collection of all key-value pairs. Changes to the returned * collection will update the underlying multimap, and vice versa. The entries * collection does not support the {@code add} or {@code addAll} operations. * * @return collection of map entries consisting of key-value pairs */ Collection<Map.Entry<K, V>> entries(); /** * 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. * * @return a map view from a key to its collection of values */ Map<K, Collection<V>> asMap(); // Comparison and hashing /** * Compares the specified object with this multimap for equality. Two * multimaps are equal when their map views, as returned by {@link #asMap}, * are also equal. * * <p>In general, two multimaps with identical key-value mappings may or may * not be equal, depending on the implementation. For example, two * {@link SetMultimap} instances with the same key-value mappings are equal, * but equality of two {@link ListMultimap} instances depends on the ordering * of the values for each key. * * <p>A non-empty {@link SetMultimap} cannot be equal to a non-empty * {@link ListMultimap}, since their {@link #asMap} views contain unequal * collections as values. However, any two empty multimaps are equal, because * they both have empty {@link #asMap} views. */ @Override boolean equals(@Nullable Object obj); /** * 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}. */ @Override int hashCode(); }
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.checkElementIndex; import static com.google.common.base.Preconditions.checkPositionIndex; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.annotations.GwtCompatible; import java.util.Collection; import java.util.List; import java.util.NoSuchElementException; import javax.annotation.Nullable; /** * An empty immutable list. * * @author Kevin Bourrillion */ @GwtCompatible(serializable = true, emulated = true) final class EmptyImmutableList extends ImmutableList<Object> { static final EmptyImmutableList INSTANCE = new EmptyImmutableList(); static final UnmodifiableListIterator<Object> ITERATOR = new UnmodifiableListIterator<Object>() { @Override public boolean hasNext() { return false; } @Override public boolean hasPrevious() { return false; } @Override public Object next() { throw new NoSuchElementException(); } @Override public int nextIndex() { return 0; } @Override public Object previous() { throw new NoSuchElementException(); } @Override public int previousIndex() { return -1; } }; private EmptyImmutableList() {} @Override public int size() { return 0; } @Override public boolean isEmpty() { return true; } @Override boolean isPartialView() { return false; } @Override public boolean contains(Object target) { return false; } @Override public UnmodifiableIterator<Object> iterator() { return Iterators.emptyIterator(); } private static final Object[] EMPTY_ARRAY = new Object[0]; @Override public Object[] toArray() { return EMPTY_ARRAY; } @Override public <T> T[] toArray(T[] a) { if (a.length > 0) { a[0] = null; } return a; } @Override public Object get(int index) { // guaranteed to fail, but at least we get a consistent message checkElementIndex(index, 0); throw new AssertionError("unreachable"); } @Override public int indexOf(@Nullable Object target) { return -1; } @Override public int lastIndexOf(@Nullable Object target) { return -1; } @Override public ImmutableList<Object> subList(int fromIndex, int toIndex) { checkPositionIndexes(fromIndex, toIndex, 0); return this; } @Override public ImmutableList<Object> reverse() { return this; } @Override public UnmodifiableListIterator<Object> listIterator(){ return ITERATOR; } @Override public UnmodifiableListIterator<Object> listIterator(int start) { checkPositionIndex(start, 0); return ITERATOR; } @Override public boolean containsAll(Collection<?> targets) { return targets.isEmpty(); } @Override public boolean equals(@Nullable Object object) { if (object instanceof List) { List<?> that = (List<?>) object; return that.isEmpty(); } return false; } @Override public int hashCode() { return 1; } @Override public String toString() { return "[]"; } 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.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import java.io.Serializable; import java.util.AbstractSet; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedSet; import javax.annotation.Nullable; 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.collect.Multiset.Entry; import com.google.common.primitives.Ints; /** * Provides static utility methods for creating and working with {@link * Multiset} instances. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Multisets"> * {@code Multisets}</a>. * * @author Kevin Bourrillion * @author Mike Bostock * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public final class Multisets { private Multisets() {} /** * Returns an unmodifiable view of the specified multiset. Query operations on * the returned multiset "read through" to the specified multiset, and * attempts to modify the returned multiset result in an * {@link UnsupportedOperationException}. * * <p>The returned multiset will be serializable if the specified multiset is * serializable. * * @param multiset the multiset for which an unmodifiable view is to be * generated * @return an unmodifiable view of the multiset */ public static <E> Multiset<E> unmodifiableMultiset( Multiset<? extends E> multiset) { if (multiset instanceof UnmodifiableMultiset || multiset instanceof ImmutableMultiset) { // Since it's unmodifiable, the covariant cast is safe @SuppressWarnings("unchecked") Multiset<E> result = (Multiset<E>) multiset; return result; } return new UnmodifiableMultiset<E>(checkNotNull(multiset)); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <E> Multiset<E> unmodifiableMultiset( ImmutableMultiset<E> multiset) { return checkNotNull(multiset); } static class UnmodifiableMultiset<E> extends ForwardingMultiset<E> implements Serializable { final Multiset<? extends E> delegate; UnmodifiableMultiset(Multiset<? extends E> delegate) { this.delegate = delegate; } @SuppressWarnings("unchecked") @Override protected Multiset<E> delegate() { // This is safe because all non-covariant methods are overriden return (Multiset<E>) delegate; } transient Set<E> elementSet; Set<E> createElementSet() { return Collections.<E>unmodifiableSet(delegate.elementSet()); } @Override public Set<E> elementSet() { Set<E> es = elementSet; return (es == null) ? elementSet = createElementSet() : es; } transient Set<Multiset.Entry<E>> entrySet; @SuppressWarnings("unchecked") @Override public Set<Multiset.Entry<E>> entrySet() { Set<Multiset.Entry<E>> es = entrySet; return (es == null) // Safe because the returned set is made unmodifiable and Entry // itself is readonly ? entrySet = (Set) Collections.unmodifiableSet(delegate.entrySet()) : es; } @SuppressWarnings("unchecked") @Override public Iterator<E> iterator() { // Safe because the returned Iterator is made unmodifiable return (Iterator<E>) Iterators.unmodifiableIterator(delegate.iterator()); } @Override public boolean add(E element) { throw new UnsupportedOperationException(); } @Override public int add(E element, int occurences) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends E> elementsToAdd) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object element) { throw new UnsupportedOperationException(); } @Override public int remove(Object element, int occurrences) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> elementsToRemove) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> elementsToRetain) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public int setCount(E element, int count) { throw new UnsupportedOperationException(); } @Override public boolean setCount(E element, int oldCount, int newCount) { throw new UnsupportedOperationException(); } private static final long serialVersionUID = 0; } /** * Returns an unmodifiable view of the specified sorted multiset. Query * operations on the returned multiset "read through" to the specified * multiset, and attempts to modify the returned multiset result in an {@link * UnsupportedOperationException}. * * <p>The returned multiset will be serializable if the specified multiset is * serializable. * * @param sortedMultiset the sorted multiset for which an unmodifiable view is * to be generated * @return an unmodifiable view of the multiset * @since 11.0 */ @Beta public static <E> SortedMultiset<E> unmodifiableSortedMultiset( SortedMultiset<E> sortedMultiset) { return new UnmodifiableSortedMultiset<E>(checkNotNull(sortedMultiset)); } private static final class UnmodifiableSortedMultiset<E> extends UnmodifiableMultiset<E> implements SortedMultiset<E> { private UnmodifiableSortedMultiset(SortedMultiset<E> delegate) { super(delegate); } @Override protected SortedMultiset<E> delegate() { return (SortedMultiset<E>) super.delegate(); } @Override public Comparator<? super E> comparator() { return delegate().comparator(); } @Override SortedSet<E> createElementSet() { return Collections.unmodifiableSortedSet(delegate().elementSet()); } @Override public SortedSet<E> elementSet() { return (SortedSet<E>) super.elementSet(); } private transient UnmodifiableSortedMultiset<E> descendingMultiset; @Override public SortedMultiset<E> descendingMultiset() { UnmodifiableSortedMultiset<E> result = descendingMultiset; if (result == null) { result = new UnmodifiableSortedMultiset<E>( delegate().descendingMultiset()); result.descendingMultiset = this; return descendingMultiset = result; } return result; } @Override public Entry<E> firstEntry() { return delegate().firstEntry(); } @Override public Entry<E> lastEntry() { return delegate().lastEntry(); } @Override public Entry<E> pollFirstEntry() { throw new UnsupportedOperationException(); } @Override public Entry<E> pollLastEntry() { throw new UnsupportedOperationException(); } @Override public SortedMultiset<E> headMultiset(E upperBound, BoundType boundType) { return unmodifiableSortedMultiset( delegate().headMultiset(upperBound, boundType)); } @Override public SortedMultiset<E> subMultiset( E lowerBound, BoundType lowerBoundType, E upperBound, BoundType upperBoundType) { return unmodifiableSortedMultiset(delegate().subMultiset( lowerBound, lowerBoundType, upperBound, upperBoundType)); } @Override public SortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) { return unmodifiableSortedMultiset( delegate().tailMultiset(lowerBound, boundType)); } private static final long serialVersionUID = 0; } /** * Returns an immutable multiset entry with the specified element and count. * The entry will be serializable if {@code e} is. * * @param e the element to be associated with the returned entry * @param n the count to be associated with the returned entry * @throws IllegalArgumentException if {@code n} is negative */ public static <E> Multiset.Entry<E> immutableEntry(@Nullable E e, int n) { return new ImmutableEntry<E>(e, n); } static final class ImmutableEntry<E> extends AbstractEntry<E> implements Serializable { @Nullable final E element; final int count; ImmutableEntry(@Nullable E element, int count) { this.element = element; this.count = count; checkArgument(count >= 0); } @Override @Nullable public E getElement() { return element; } @Override public int getCount() { return count; } private static final long serialVersionUID = 0; } /** * Returns a multiset view of the specified set. The multiset is backed by the * set, so changes to the set are reflected in the multiset, and vice versa. * If the set is modified while an iteration over the multiset is in progress * (except through the iterator's own {@code remove} operation) the results of * the iteration are undefined. * * <p>The multiset supports element removal, which removes the corresponding * element from the set. It does not support the {@code add} or {@code addAll} * operations, nor does it support the use of {@code setCount} to add * elements. * * <p>The returned multiset will be serializable if the specified set is * serializable. The multiset is threadsafe if the set is threadsafe. * * @param set the backing set for the returned multiset view */ static <E> Multiset<E> forSet(Set<E> set) { return new SetMultiset<E>(set); } /** @see Multisets#forSet */ private static class SetMultiset<E> extends ForwardingCollection<E> implements Multiset<E>, Serializable { final Set<E> delegate; SetMultiset(Set<E> set) { delegate = checkNotNull(set); } @Override protected Set<E> delegate() { return delegate; } @Override public int count(Object element) { return delegate.contains(element) ? 1 : 0; } @Override public int add(E element, int occurrences) { throw new UnsupportedOperationException(); } @Override public int remove(Object element, int occurrences) { if (occurrences == 0) { return count(element); } checkArgument(occurrences > 0); return delegate.remove(element) ? 1 : 0; } transient Set<E> elementSet; @Override public Set<E> elementSet() { Set<E> es = elementSet; return (es == null) ? elementSet = new ElementSet() : es; } transient Set<Entry<E>> entrySet; @Override public Set<Entry<E>> entrySet() { Set<Entry<E>> es = entrySet; if (es == null) { es = entrySet = new EntrySet<E>() { @Override Multiset<E> multiset() { return SetMultiset.this; } @Override public Iterator<Entry<E>> iterator() { return Iterators.transform(delegate.iterator(), new Function<E, Entry<E>>() { @Override public Entry<E> apply(E elem) { return immutableEntry(elem, 1); } }); } @Override public int size() { return delegate.size(); } }; } return es; } @Override public boolean add(E o) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends E> c) { throw new UnsupportedOperationException(); } @Override public int setCount(E element, int count) { checkNonnegative(count, "count"); if (count == count(element)) { return count; } else if (count == 0) { remove(element); return 1; } else { throw new UnsupportedOperationException(); } } @Override public boolean setCount(E element, int oldCount, int newCount) { return setCountImpl(this, element, oldCount, newCount); } @Override public boolean equals(@Nullable Object object) { if (object instanceof Multiset) { Multiset<?> that = (Multiset<?>) object; return this.size() == that.size() && delegate.equals(that.elementSet()); } return false; } @Override public int hashCode() { int sum = 0; for (E e : this) { sum += ((e == null) ? 0 : e.hashCode()) ^ 1; } return sum; } /** @see SetMultiset#elementSet */ class ElementSet extends ForwardingSet<E> { @Override protected Set<E> delegate() { return delegate; } @Override public boolean add(E o) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends E> c) { throw new UnsupportedOperationException(); } } private static final long serialVersionUID = 0; } /** * Returns the expected number of distinct elements given the specified * elements. The number of distinct elements is only computed if {@code * elements} is an instance of {@code Multiset}; otherwise the default value * of 11 is returned. */ static int inferDistinctElements(Iterable<?> elements) { if (elements instanceof Multiset) { return ((Multiset<?>) elements).elementSet().size(); } return 11; // initial capacity will be rounded up to 16 } /** * Returns an unmodifiable <b>view</b> of the intersection of two multisets. * An element's count in the multiset is the smaller of its counts in the two * backing multisets. The iteration order of the returned multiset matches the * element set of {@code multiset1}, with repeated occurrences of the same * element appearing consecutively. * * <p>Results are undefined if {@code multiset1} and {@code multiset2} are * based on different equivalence relations (as {@code HashMultiset} and * {@code TreeMultiset} are). * * @since 2.0 */ public static <E> Multiset<E> intersection( final Multiset<E> multiset1, final Multiset<?> multiset2) { checkNotNull(multiset1); checkNotNull(multiset2); return new AbstractMultiset<E>() { @Override public int count(Object element) { int count1 = multiset1.count(element); return (count1 == 0) ? 0 : Math.min(count1, multiset2.count(element)); } @Override Set<E> createElementSet() { return Sets.intersection( multiset1.elementSet(), multiset2.elementSet()); } @Override Iterator<Entry<E>> entryIterator() { final Iterator<Entry<E>> iterator1 = multiset1.entrySet().iterator(); return new AbstractIterator<Entry<E>>() { @Override protected Entry<E> computeNext() { while (iterator1.hasNext()) { Entry<E> entry1 = iterator1.next(); E element = entry1.getElement(); int count = Math.min(entry1.getCount(), multiset2.count(element)); if (count > 0) { return Multisets.immutableEntry(element, count); } } return endOfData(); } }; } @Override int distinctElements() { return elementSet().size(); } }; } /** * Returns {@code true} if {@code subMultiset.count(o) <= * superMultiset.count(o)} for all {@code o}. * * @since 10.0 */ @Beta public static boolean containsOccurrences( Multiset<?> superMultiset, Multiset<?> subMultiset) { checkNotNull(superMultiset); checkNotNull(subMultiset); for (Entry<?> entry : subMultiset.entrySet()) { int superCount = superMultiset.count(entry.getElement()); if (superCount < entry.getCount()) { return false; } } return true; } /** * Modifies {@code multisetToModify} so that its count for an element * {@code e} is at most {@code multisetToRetain.count(e)}. * * <p>To be precise, {@code multisetToModify.count(e)} is set to * {@code Math.min(multisetToModify.count(e), * multisetToRetain.count(e))}. This is similar to * {@link #intersection(Multiset, Multiset) intersection} * {@code (multisetToModify, multisetToRetain)}, but mutates * {@code multisetToModify} instead of returning a view. * * <p>In contrast, {@code multisetToModify.retainAll(multisetToRetain)} keeps * all occurrences of elements that appear at all in {@code * multisetToRetain}, and deletes all occurrences of all other elements. * * @return {@code true} if {@code multisetToModify} was changed as a result * of this operation * @since 10.0 */ @Beta public static boolean retainOccurrences(Multiset<?> multisetToModify, Multiset<?> multisetToRetain) { return retainOccurrencesImpl(multisetToModify, multisetToRetain); } /** * Delegate implementation which cares about the element type. */ private static <E> boolean retainOccurrencesImpl( Multiset<E> multisetToModify, Multiset<?> occurrencesToRetain) { checkNotNull(multisetToModify); checkNotNull(occurrencesToRetain); // Avoiding ConcurrentModificationExceptions is tricky. Iterator<Entry<E>> entryIterator = multisetToModify.entrySet().iterator(); boolean changed = false; while (entryIterator.hasNext()) { Entry<E> entry = entryIterator.next(); int retainCount = occurrencesToRetain.count(entry.getElement()); if (retainCount == 0) { entryIterator.remove(); changed = true; } else if (retainCount < entry.getCount()) { multisetToModify.setCount(entry.getElement(), retainCount); changed = true; } } return changed; } /** * For each occurrence of an element {@code e} in {@code occurrencesToRemove}, * removes one occurrence of {@code e} in {@code multisetToModify}. * * <p>Equivalently, this method modifies {@code multisetToModify} so that * {@code multisetToModify.count(e)} is set to * {@code Math.max(0, multisetToModify.count(e) - * occurrencesToRemove.count(e))}. * * <p>This is <i>not</i> the same as {@code multisetToModify.} * {@link Multiset#removeAll removeAll}{@code (occurrencesToRemove)}, which * removes all occurrences of elements that appear in * {@code occurrencesToRemove}. However, this operation <i>is</i> equivalent * to, albeit more efficient than, the following: <pre> {@code * * for (E e : occurrencesToRemove) { * multisetToModify.remove(e); * }}</pre> * * @return {@code true} if {@code multisetToModify} was changed as a result of * this operation * @since 10.0 */ @Beta public static boolean removeOccurrences( Multiset<?> multisetToModify, Multiset<?> occurrencesToRemove) { return removeOccurrencesImpl(multisetToModify, occurrencesToRemove); } /** * Delegate that cares about the element types in occurrencesToRemove. */ private static <E> boolean removeOccurrencesImpl( Multiset<E> multisetToModify, Multiset<?> occurrencesToRemove) { // TODO(user): generalize to removing an Iterable, perhaps checkNotNull(multisetToModify); checkNotNull(occurrencesToRemove); boolean changed = false; Iterator<Entry<E>> entryIterator = multisetToModify.entrySet().iterator(); while (entryIterator.hasNext()) { Entry<E> entry = entryIterator.next(); int removeCount = occurrencesToRemove.count(entry.getElement()); if (removeCount >= entry.getCount()) { entryIterator.remove(); changed = true; } else if (removeCount > 0) { multisetToModify.remove(entry.getElement(), removeCount); changed = true; } } return changed; } /** * Implementation of the {@code equals}, {@code hashCode}, and * {@code toString} methods of {@link Multiset.Entry}. */ abstract static class AbstractEntry<E> implements Multiset.Entry<E> { /** * Indicates whether an object equals this entry, following the behavior * specified in {@link Multiset.Entry#equals}. */ @Override public boolean equals(@Nullable Object object) { if (object instanceof Multiset.Entry) { Multiset.Entry<?> that = (Multiset.Entry<?>) object; return this.getCount() == that.getCount() && Objects.equal(this.getElement(), that.getElement()); } return false; } /** * Return this entry's hash code, following the behavior specified in * {@link Multiset.Entry#hashCode}. */ @Override public int hashCode() { E e = getElement(); return ((e == null) ? 0 : e.hashCode()) ^ getCount(); } /** * Returns a string representation of this multiset entry. The string * representation consists of the associated element if the associated count * is one, and otherwise the associated element followed by the characters * " x " (space, x and space) followed by the count. Elements and counts are * converted to strings as by {@code String.valueOf}. */ @Override public String toString() { String text = String.valueOf(getElement()); int n = getCount(); return (n == 1) ? text : (text + " x " + n); } } /** * An implementation of {@link Multiset#equals}. */ static boolean equalsImpl(Multiset<?> multiset, @Nullable Object object) { if (object == multiset) { return true; } if (object instanceof Multiset) { Multiset<?> that = (Multiset<?>) object; /* * We can't simply check whether the entry sets are equal, since that * approach fails when a TreeMultiset has a comparator that returns 0 * when passed unequal elements. */ if (multiset.size() != that.size() || multiset.entrySet().size() != that.entrySet().size()) { return false; } for (Entry<?> entry : that.entrySet()) { if (multiset.count(entry.getElement()) != entry.getCount()) { return false; } } return true; } return false; } /** * An implementation of {@link Multiset#addAll}. */ static <E> boolean addAllImpl( Multiset<E> self, Collection<? extends E> elements) { if (elements.isEmpty()) { return false; } if (elements instanceof Multiset) { Multiset<? extends E> that = cast(elements); for (Entry<? extends E> entry : that.entrySet()) { self.add(entry.getElement(), entry.getCount()); } } else { Iterators.addAll(self, elements.iterator()); } return true; } /** * An implementation of {@link Multiset#removeAll}. */ static boolean removeAllImpl( Multiset<?> self, Collection<?> elementsToRemove) { Collection<?> collection = (elementsToRemove instanceof Multiset) ? ((Multiset<?>) elementsToRemove).elementSet() : elementsToRemove; return self.elementSet().removeAll(collection); } /** * An implementation of {@link Multiset#retainAll}. */ static boolean retainAllImpl( Multiset<?> self, Collection<?> elementsToRetain) { Collection<?> collection = (elementsToRetain instanceof Multiset) ? ((Multiset<?>) elementsToRetain).elementSet() : elementsToRetain; return self.elementSet().retainAll(collection); } /** * An implementation of {@link Multiset#setCount(Object, int)}. */ static <E> int setCountImpl(Multiset<E> self, E element, int count) { checkNonnegative(count, "count"); int oldCount = self.count(element); int delta = count - oldCount; if (delta > 0) { self.add(element, delta); } else if (delta < 0) { self.remove(element, -delta); } return oldCount; } /** * An implementation of {@link Multiset#setCount(Object, int, int)}. */ static <E> boolean setCountImpl( Multiset<E> self, E element, int oldCount, int newCount) { checkNonnegative(oldCount, "oldCount"); checkNonnegative(newCount, "newCount"); if (self.count(element) == oldCount) { self.setCount(element, newCount); return true; } else { return false; } } static abstract class ElementSet<E> extends AbstractSet<E> { abstract Multiset<E> multiset(); @Override public void clear() { multiset().clear(); } @Override public boolean contains(Object o) { return multiset().contains(o); } @Override public boolean containsAll(Collection<?> c) { return multiset().containsAll(c); } @Override public boolean isEmpty() { return multiset().isEmpty(); } @Override public Iterator<E> iterator() { return Iterators.transform(multiset().entrySet().iterator(), new Function<Entry<E>, E>() { @Override public E apply(Entry<E> entry) { return entry.getElement(); } }); } @Override public boolean remove(Object o) { int count = multiset().count(o); if (count > 0) { multiset().remove(o, count); return true; } return false; } @Override public int size() { return multiset().entrySet().size(); } } static abstract class EntrySet<E> extends AbstractSet<Entry<E>>{ abstract Multiset<E> multiset(); @Override public boolean contains(@Nullable Object o) { if (o instanceof Entry) { @SuppressWarnings("cast") Entry<?> entry = (Entry<?>) o; if (entry.getCount() <= 0) { return false; } int count = multiset().count(entry.getElement()); return count == entry.getCount(); } return false; } @SuppressWarnings("cast") @Override public boolean remove(Object o) { return contains(o) && multiset().elementSet().remove(((Entry<?>) o).getElement()); } @Override public void clear() { multiset().clear(); } } /** * An implementation of {@link Multiset#iterator}. */ static <E> Iterator<E> iteratorImpl(Multiset<E> multiset) { return new MultisetIteratorImpl<E>( multiset, multiset.entrySet().iterator()); } static final class MultisetIteratorImpl<E> implements Iterator<E> { private final Multiset<E> multiset; private final Iterator<Entry<E>> entryIterator; private Entry<E> currentEntry; /** Count of subsequent elements equal to current element */ private int laterCount; /** Count of all elements equal to current element */ private int totalCount; private boolean canRemove; MultisetIteratorImpl( Multiset<E> multiset, Iterator<Entry<E>> entryIterator) { this.multiset = multiset; this.entryIterator = entryIterator; } @Override public boolean hasNext() { return laterCount > 0 || entryIterator.hasNext(); } @Override public E next() { if (!hasNext()) { throw new NoSuchElementException(); } if (laterCount == 0) { currentEntry = entryIterator.next(); totalCount = laterCount = currentEntry.getCount(); } laterCount--; canRemove = true; return currentEntry.getElement(); } @Override public void remove() { checkState( canRemove, "no calls to next() since the last call to remove()"); if (totalCount == 1) { entryIterator.remove(); } else { multiset.remove(currentEntry.getElement()); } totalCount--; canRemove = false; } } /** * An implementation of {@link Multiset#size}. */ static int sizeImpl(Multiset<?> multiset) { long size = 0; for (Entry<?> entry : multiset.entrySet()) { size += entry.getCount(); } return Ints.saturatedCast(size); } static void checkNonnegative(int count, String name) { checkArgument(count >= 0, "%s cannot be negative: %s", name, count); } /** * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */ static <T> Multiset<T> cast(Iterable<T> iterable) { return (Multiset<T>) iterable; } private static final Ordering<Entry<?>> DECREASING_COUNT_ORDERING = new Ordering<Entry<?>>() { @Override public int compare(Entry<?> entry1, Entry<?> entry2) { return Ints.compare(entry2.getCount(), entry1.getCount()); } }; /** * Returns a copy of {@code multiset} as an {@link ImmutableMultiset} whose iteration order is * highest count first, with ties broken by the iteration order of the original multiset. * * @since 11.0 */ @Beta public static <E> ImmutableMultiset<E> copyHighestCountFirst(Multiset<E> multiset) { List<Entry<E>> sortedEntries = Multisets.DECREASING_COUNT_ORDERING.sortedCopy(multiset.entrySet()); return ImmutableMultiset.copyFromEntries(sortedEntries); } }
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.Beta; import com.google.common.annotations.GwtCompatible; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; /** * Interface that extends {@code Table} and whose rows are sorted. * * <p>The {@link #rowKeySet} method returns a {@link SortedSet} and the {@link * #rowMap} method returns a {@link SortedMap}, instead of the {@link Set} and * {@link Map} specified by the {@link Table} interface. * * @author Warren Dukes * @since 8.0 */ @GwtCompatible @Beta public interface RowSortedTable<R, C, V> extends Table<R, C, V> { /** * {@inheritDoc} * * <p>This method returns a {@link SortedSet}, instead of the {@code Set} * specified in the {@link Table} interface. */ @Override SortedSet<R> rowKeySet(); /** * {@inheritDoc} * * <p>This method returns a {@link SortedMap}, instead of the {@code Map} * specified in the {@link Table} interface. */ @Override SortedMap<R, Map<C, V>> rowMap(); }
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 com.google.common.annotations.GwtIncompatible; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; /** * Multiset implementation backed by a {@link HashMap}. * * @author Kevin Bourrillion * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public final class HashMultiset<E> extends AbstractMapBasedMultiset<E> { /** * Creates a new, empty {@code HashMultiset} using the default initial * capacity. */ public static <E> HashMultiset<E> create() { return new HashMultiset<E>(); } /** * Creates a new, empty {@code HashMultiset} with the specified expected * number of distinct elements. * * @param distinctElements the expected number of distinct elements * @throws IllegalArgumentException if {@code distinctElements} is negative */ public static <E> HashMultiset<E> create(int distinctElements) { return new HashMultiset<E>(distinctElements); } /** * Creates a new {@code HashMultiset} 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 */ public static <E> HashMultiset<E> create(Iterable<? extends E> elements) { HashMultiset<E> multiset = create(Multisets.inferDistinctElements(elements)); Iterables.addAll(multiset, elements); return multiset; } private HashMultiset() { super(new HashMap<E, Count>()); } private HashMultiset(int distinctElements) { super(Maps.<E, Count>newHashMapWithExpectedSize(distinctElements)); } /** * @serialData the number of distinct elements, the first element, its count, * the second element, its count, and so on */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); Serialization.writeMultiset(this, stream); } @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); int distinctElements = Serialization.readCount(stream); setBackingMap( Maps.<E, Count>newHashMapWithExpectedSize(distinctElements)); Serialization.populateMultiset(this, stream, distinctElements); } @GwtIncompatible("Not needed in emulated source.") private static final long serialVersionUID = 0; }
Java