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.collect; 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.Collection; import java.util.Comparator; import java.util.Map.Entry; import javax.annotation.Nullable; /** * An immutable {@link ListMultimap} with reliable user-specified key and value * iteration order. Does not permit null keys or values. * * <p>Unlike {@link Multimaps#unmodifiableListMultimap(ListMultimap)}, which is * a <i>view</i> of a separate multimap which can still change, an instance of * {@code ImmutableListMultimap} contains its own data and will <i>never</i> * change. {@code ImmutableListMultimap} 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 Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public class ImmutableListMultimap<K, V> extends ImmutableMultimap<K, V> implements ListMultimap<K, V> { /** Returns the empty multimap. */ // Casting is safe because the multimap will never hold any elements. @SuppressWarnings("unchecked") public static <K, V> ImmutableListMultimap<K, V> of() { return (ImmutableListMultimap<K, V>) EmptyImmutableListMultimap.INSTANCE; } /** * Returns an immutable multimap containing a single entry. */ public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1) { ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder(); builder.put(k1, v1); return builder.build(); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1, K k2, V v2) { ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder(); builder.put(k1, v1); builder.put(k2, v2); return builder.build(); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableListMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3) { ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.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. */ public static <K, V> ImmutableListMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.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. */ public static <K, V> ImmutableListMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.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 builder. The generated builder is equivalent to the builder * created by the {@link Builder} constructor. */ public static <K, V> Builder<K, V> builder() { return new Builder<K, V>(); } /** * A builder for creating immutable {@code ListMultimap} instances, especially * {@code public static final} multimaps ("constant multimaps"). Example: * <pre> {@code * * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP = * new ImmutableListMultimap.Builder<String, Integer>() * .put("one", 1) * .putAll("several", 1, 2, 3) * .putAll("many", 1, 2, 3, 4, 5) * .build();}</pre> * * <p>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 ImmutableListMultimap#builder}. */ public Builder() {} @Override public Builder<K, V> put(K key, V value) { super.put(key, value); return this; } /** * {@inheritDoc} * * @since 11.0 */ @Override public Builder<K, V> put( Entry<? extends K, ? extends V> entry) { super.put(entry); return this; } @Override public Builder<K, V> putAll(K key, Iterable<? extends V> values) { super.putAll(key, values); return this; } @Override public Builder<K, V> putAll(K key, V... values) { super.putAll(key, values); return this; } @Override public Builder<K, V> putAll( Multimap<? extends K, ? extends V> multimap) { super.putAll(multimap); return this; } /** * {@inheritDoc} * * @since 8.0 */ @Override public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) { super.orderKeysBy(keyComparator); return this; } /** * {@inheritDoc} * * @since 8.0 */ @Override public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) { super.orderValuesBy(valueComparator); return this; } /** * Returns a newly-created immutable list multimap. */ @Override public ImmutableListMultimap<K, V> build() { return (ImmutableListMultimap<K, V>) super.build(); } } /** * Returns an immutable 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. * * <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> ImmutableListMultimap<K, V> copyOf( Multimap<? extends K, ? extends V> multimap) { if (multimap.isEmpty()) { return of(); } // TODO(user): copy ImmutableSetMultimap by using asList() on the sets if (multimap instanceof ImmutableListMultimap) { @SuppressWarnings("unchecked") // safe since multimap is not writable ImmutableListMultimap<K, V> kvMultimap = (ImmutableListMultimap<K, V>) multimap; if (!kvMultimap.isPartialView()) { return kvMultimap; } } ImmutableMap.Builder<K, ImmutableList<V>> builder = ImmutableMap.builder(); int size = 0; for (Entry<? extends K, ? extends Collection<? extends V>> entry : multimap.asMap().entrySet()) { ImmutableList<V> list = ImmutableList.copyOf(entry.getValue()); if (!list.isEmpty()) { builder.put(entry.getKey(), list); size += list.size(); } } return new ImmutableListMultimap<K, V>(builder.build(), size); } ImmutableListMultimap(ImmutableMap<K, ImmutableList<V>> map, int size) { super(map, size); } // views /** * Returns an immutable list of the values for the given key. If no mappings * in the multimap have the provided key, an empty immutable list is * returned. The values are in the same order as the parameters used to build * this multimap. */ @Override public ImmutableList<V> get(@Nullable K key) { // This cast is safe as its type is known in constructor. ImmutableList<V> list = (ImmutableList<V>) map.get(key); return (list == null) ? ImmutableList.<V>of() : list; } private transient ImmutableListMultimap<V, K> inverse; /** * {@inheritDoc} * * <p>Because an inverse of a list multimap can contain multiple pairs with * the same key and value, this method returns an {@code * ImmutableListMultimap} rather than the {@code ImmutableMultimap} specified * in the {@code ImmutableMultimap} class. * * @since 11.0 */ @Override public ImmutableListMultimap<V, K> inverse() { ImmutableListMultimap<V, K> result = inverse; return (result == null) ? (inverse = invert()) : result; } private ImmutableListMultimap<V, K> invert() { Builder<V, K> builder = builder(); for (Entry<K, V> entry : entries()) { builder.put(entry.getValue(), entry.getKey()); } ImmutableListMultimap<V, K> invertedMultimap = builder.build(); invertedMultimap.inverse = this; return invertedMultimap; } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public ImmutableList<V> removeAll(Object key) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public ImmutableList<V> replaceValues( K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } /** * @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, ImmutableList<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(); } builder.put(key, ImmutableList.copyOf(array)); tmpSize += valueCount; } ImmutableMap<Object, ImmutableList<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.io.Serializable; import javax.annotation.Nullable; /** An ordering that treats {@code null} as greater than all other values. */ @GwtCompatible(serializable = true) final class NullsLastOrdering<T> extends Ordering<T> implements Serializable { final Ordering<? super T> ordering; NullsLastOrdering(Ordering<? super T> ordering) { this.ordering = ordering; } @Override public int compare(@Nullable T left, @Nullable T right) { if (left == right) { return 0; } if (left == null) { return LEFT_IS_GREATER; } if (right == null) { return RIGHT_IS_GREATER; } return ordering.compare(left, right); } @Override public <S extends T> Ordering<S> reverse() { // ordering.reverse() might be optimized, so let it do its thing return ordering.reverse().nullsFirst(); } @Override public <S extends T> Ordering<S> nullsFirst() { return ordering.nullsFirst(); } @SuppressWarnings("unchecked") // still need the right way to explain this @Override public <S extends T> Ordering<S> nullsLast() { return (Ordering<S>) this; } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof NullsLastOrdering) { NullsLastOrdering<?> that = (NullsLastOrdering<?>) object; return this.ordering.equals(that.ordering); } return false; } @Override public int hashCode() { return ordering.hashCode() ^ -921210296; // meaningless } @Override public String toString() { return ordering + ".nullsLast()"; } 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.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.Iterator; /** An ordering that uses the reverse of the natural order of the values. */ @GwtCompatible(serializable = true) @SuppressWarnings("unchecked") // TODO(kevinb): the right way to explain this?? final class ReverseNaturalOrdering extends Ordering<Comparable> implements Serializable { static final ReverseNaturalOrdering INSTANCE = new ReverseNaturalOrdering(); @Override public int compare(Comparable left, Comparable right) { checkNotNull(left); // right null is caught later if (left == right) { return 0; } return right.compareTo(left); } @Override public <S extends Comparable> Ordering<S> reverse() { return Ordering.natural(); } // Override the min/max methods to "hoist" delegation outside loops @Override public <E extends Comparable> E min(E a, E b) { return NaturalOrdering.INSTANCE.max(a, b); } @Override public <E extends Comparable> E min(E a, E b, E c, E... rest) { return NaturalOrdering.INSTANCE.max(a, b, c, rest); } @Override public <E extends Comparable> E min(Iterator<E> iterator) { return NaturalOrdering.INSTANCE.max(iterator); } @Override public <E extends Comparable> E min(Iterable<E> iterable) { return NaturalOrdering.INSTANCE.max(iterable); } @Override public <E extends Comparable> E max(E a, E b) { return NaturalOrdering.INSTANCE.min(a, b); } @Override public <E extends Comparable> E max(E a, E b, E c, E... rest) { return NaturalOrdering.INSTANCE.min(a, b, c, rest); } @Override public <E extends Comparable> E max(Iterator<E> iterator) { return NaturalOrdering.INSTANCE.min(iterator); } @Override public <E extends Comparable> E max(Iterable<E> iterable) { return NaturalOrdering.INSTANCE.min(iterable); } // preserving singleton-ness gives equals()/hashCode() for free private Object readResolve() { return INSTANCE; } @Override public String toString() { return "Ordering.natural().reverse()"; } private ReverseNaturalOrdering() {} 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.util.Iterator; /** * An iterator that does not support {@link #remove}. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class UnmodifiableIterator<E> implements Iterator<E> { /** Constructor for use by subclasses. */ protected UnmodifiableIterator() {} /** * Guaranteed to throw an exception and leave the underlying data unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final void remove() { throw new UnsupportedOperationException(); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.Comparator; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.Queue; import java.util.RandomAccess; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import javax.annotation.Nullable; /** * Synchronized collection views. The returned synchronized collection views are * serializable if the backing collection and the mutex are serializable. * * <p>If {@code null} is passed as the {@code mutex} parameter to any of this * class's top-level methods or inner class constructors, the created object * uses itself as the synchronization mutex. * * <p>This class should be used by other collection classes only. * * @author Mike Bostock * @author Jared Levy */ @GwtCompatible(emulated = true) final class Synchronized { private Synchronized() {} static class SynchronizedObject implements Serializable { final Object delegate; final Object mutex; SynchronizedObject(Object delegate, @Nullable Object mutex) { this.delegate = checkNotNull(delegate); this.mutex = (mutex == null) ? this : mutex; } Object delegate() { return delegate; } // No equals and hashCode; see ForwardingObject for details. @Override public String toString() { synchronized (mutex) { return delegate.toString(); } } // Serialization invokes writeObject only when it's private. // The SynchronizedObject subclasses don't need a writeObject method since // they don't contain any non-transient member variables, while the // following writeObject() handles the SynchronizedObject members. @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { synchronized (mutex) { stream.defaultWriteObject(); } } @GwtIncompatible("not needed in emulated source") private static final long serialVersionUID = 0; } private static <E> Collection<E> collection( Collection<E> collection, @Nullable Object mutex) { return new SynchronizedCollection<E>(collection, mutex); } @VisibleForTesting static class SynchronizedCollection<E> extends SynchronizedObject implements Collection<E> { private SynchronizedCollection( Collection<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @SuppressWarnings("unchecked") @Override Collection<E> delegate() { return (Collection<E>) super.delegate(); } @Override public boolean add(E e) { synchronized (mutex) { return delegate().add(e); } } @Override public boolean addAll(Collection<? extends E> c) { synchronized (mutex) { return delegate().addAll(c); } } @Override public void clear() { synchronized (mutex) { delegate().clear(); } } @Override public boolean contains(Object o) { synchronized (mutex) { return delegate().contains(o); } } @Override public boolean containsAll(Collection<?> c) { synchronized (mutex) { return delegate().containsAll(c); } } @Override public boolean isEmpty() { synchronized (mutex) { return delegate().isEmpty(); } } @Override public Iterator<E> iterator() { return delegate().iterator(); // manually synchronized } @Override public boolean remove(Object o) { synchronized (mutex) { return delegate().remove(o); } } @Override public boolean removeAll(Collection<?> c) { synchronized (mutex) { return delegate().removeAll(c); } } @Override public boolean retainAll(Collection<?> c) { synchronized (mutex) { return delegate().retainAll(c); } } @Override public int size() { synchronized (mutex) { return delegate().size(); } } @Override public Object[] toArray() { synchronized (mutex) { return delegate().toArray(); } } @Override public <T> T[] toArray(T[] a) { synchronized (mutex) { return delegate().toArray(a); } } private static final long serialVersionUID = 0; } @VisibleForTesting static <E> Set<E> set(Set<E> set, @Nullable Object mutex) { return new SynchronizedSet<E>(set, mutex); } static class SynchronizedSet<E> extends SynchronizedCollection<E> implements Set<E> { SynchronizedSet(Set<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override Set<E> delegate() { return (Set<E>) super.delegate(); } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } private static <E> SortedSet<E> sortedSet( SortedSet<E> set, @Nullable Object mutex) { return new SynchronizedSortedSet<E>(set, mutex); } static class SynchronizedSortedSet<E> extends SynchronizedSet<E> implements SortedSet<E> { SynchronizedSortedSet(SortedSet<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override SortedSet<E> delegate() { return (SortedSet<E>) super.delegate(); } @Override public Comparator<? super E> comparator() { synchronized (mutex) { return delegate().comparator(); } } @Override public SortedSet<E> subSet(E fromElement, E toElement) { synchronized (mutex) { return sortedSet(delegate().subSet(fromElement, toElement), mutex); } } @Override public SortedSet<E> headSet(E toElement) { synchronized (mutex) { return sortedSet(delegate().headSet(toElement), mutex); } } @Override public SortedSet<E> tailSet(E fromElement) { synchronized (mutex) { return sortedSet(delegate().tailSet(fromElement), mutex); } } @Override public E first() { synchronized (mutex) { return delegate().first(); } } @Override public E last() { synchronized (mutex) { return delegate().last(); } } private static final long serialVersionUID = 0; } private static <E> List<E> list(List<E> list, @Nullable Object mutex) { return (list instanceof RandomAccess) ? new SynchronizedRandomAccessList<E>(list, mutex) : new SynchronizedList<E>(list, mutex); } private static class SynchronizedList<E> extends SynchronizedCollection<E> implements List<E> { SynchronizedList(List<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override List<E> delegate() { return (List<E>) super.delegate(); } @Override public void add(int index, E element) { synchronized (mutex) { delegate().add(index, element); } } @Override public boolean addAll(int index, Collection<? extends E> c) { synchronized (mutex) { return delegate().addAll(index, c); } } @Override public E get(int index) { synchronized (mutex) { return delegate().get(index); } } @Override public int indexOf(Object o) { synchronized (mutex) { return delegate().indexOf(o); } } @Override public int lastIndexOf(Object o) { synchronized (mutex) { return delegate().lastIndexOf(o); } } @Override public ListIterator<E> listIterator() { return delegate().listIterator(); // manually synchronized } @Override public ListIterator<E> listIterator(int index) { return delegate().listIterator(index); // manually synchronized } @Override public E remove(int index) { synchronized (mutex) { return delegate().remove(index); } } @Override public E set(int index, E element) { synchronized (mutex) { return delegate().set(index, element); } } @Override public List<E> subList(int fromIndex, int toIndex) { synchronized (mutex) { return list(delegate().subList(fromIndex, toIndex), mutex); } } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } private static class SynchronizedRandomAccessList<E> extends SynchronizedList<E> implements RandomAccess { SynchronizedRandomAccessList(List<E> list, @Nullable Object mutex) { super(list, mutex); } private static final long serialVersionUID = 0; } static <E> Multiset<E> multiset( Multiset<E> multiset, @Nullable Object mutex) { if (multiset instanceof SynchronizedMultiset || multiset instanceof ImmutableMultiset) { return multiset; } return new SynchronizedMultiset<E>(multiset, mutex); } private static class SynchronizedMultiset<E> extends SynchronizedCollection<E> implements Multiset<E> { transient Set<E> elementSet; transient Set<Entry<E>> entrySet; SynchronizedMultiset(Multiset<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override Multiset<E> delegate() { return (Multiset<E>) super.delegate(); } @Override public int count(Object o) { synchronized (mutex) { return delegate().count(o); } } @Override public int add(E e, int n) { synchronized (mutex) { return delegate().add(e, n); } } @Override public int remove(Object o, int n) { synchronized (mutex) { return delegate().remove(o, n); } } @Override public int setCount(E element, int count) { synchronized (mutex) { return delegate().setCount(element, count); } } @Override public boolean setCount(E element, int oldCount, int newCount) { synchronized (mutex) { return delegate().setCount(element, oldCount, newCount); } } @Override public Set<E> elementSet() { synchronized (mutex) { if (elementSet == null) { elementSet = typePreservingSet(delegate().elementSet(), mutex); } return elementSet; } } @Override public Set<Entry<E>> entrySet() { synchronized (mutex) { if (entrySet == null) { entrySet = typePreservingSet(delegate().entrySet(), mutex); } return entrySet; } } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } static <K, V> Multimap<K, V> multimap( Multimap<K, V> multimap, @Nullable Object mutex) { if (multimap instanceof SynchronizedMultimap || multimap instanceof ImmutableMultimap) { return multimap; } return new SynchronizedMultimap<K, V>(multimap, mutex); } private static class SynchronizedMultimap<K, V> extends SynchronizedObject implements Multimap<K, V> { transient Set<K> keySet; transient Collection<V> valuesCollection; transient Collection<Map.Entry<K, V>> entries; transient Map<K, Collection<V>> asMap; transient Multiset<K> keys; @SuppressWarnings("unchecked") @Override Multimap<K, V> delegate() { return (Multimap<K, V>) super.delegate(); } SynchronizedMultimap(Multimap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override public int size() { synchronized (mutex) { return delegate().size(); } } @Override public boolean isEmpty() { synchronized (mutex) { return delegate().isEmpty(); } } @Override public boolean containsKey(Object key) { synchronized (mutex) { return delegate().containsKey(key); } } @Override public boolean containsValue(Object value) { synchronized (mutex) { return delegate().containsValue(value); } } @Override public boolean containsEntry(Object key, Object value) { synchronized (mutex) { return delegate().containsEntry(key, value); } } @Override public Collection<V> get(K key) { synchronized (mutex) { return typePreservingCollection(delegate().get(key), mutex); } } @Override public boolean put(K key, V value) { synchronized (mutex) { return delegate().put(key, value); } } @Override public boolean putAll(K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().putAll(key, values); } } @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { synchronized (mutex) { return delegate().putAll(multimap); } } @Override public Collection<V> replaceValues(K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } @Override public boolean remove(Object key, Object value) { synchronized (mutex) { return delegate().remove(key, value); } } @Override public Collection<V> removeAll(Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public void clear() { synchronized (mutex) { delegate().clear(); } } @Override public Set<K> keySet() { synchronized (mutex) { if (keySet == null) { keySet = typePreservingSet(delegate().keySet(), mutex); } return keySet; } } @Override public Collection<V> values() { synchronized (mutex) { if (valuesCollection == null) { valuesCollection = collection(delegate().values(), mutex); } return valuesCollection; } } @Override public Collection<Map.Entry<K, V>> entries() { synchronized (mutex) { if (entries == null) { entries = typePreservingCollection(delegate().entries(), mutex); } return entries; } } @Override public Map<K, Collection<V>> asMap() { synchronized (mutex) { if (asMap == null) { asMap = new SynchronizedAsMap<K, V>(delegate().asMap(), mutex); } return asMap; } } @Override public Multiset<K> keys() { synchronized (mutex) { if (keys == null) { keys = multiset(delegate().keys(), mutex); } return keys; } } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } static <K, V> ListMultimap<K, V> listMultimap( ListMultimap<K, V> multimap, @Nullable Object mutex) { if (multimap instanceof SynchronizedListMultimap || multimap instanceof ImmutableListMultimap) { return multimap; } return new SynchronizedListMultimap<K, V>(multimap, mutex); } private static class SynchronizedListMultimap<K, V> extends SynchronizedMultimap<K, V> implements ListMultimap<K, V> { SynchronizedListMultimap( ListMultimap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override ListMultimap<K, V> delegate() { return (ListMultimap<K, V>) super.delegate(); } @Override public List<V> get(K key) { synchronized (mutex) { return list(delegate().get(key), mutex); } } @Override public List<V> removeAll(Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public List<V> replaceValues( K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } private static final long serialVersionUID = 0; } static <K, V> SetMultimap<K, V> setMultimap( SetMultimap<K, V> multimap, @Nullable Object mutex) { if (multimap instanceof SynchronizedSetMultimap || multimap instanceof ImmutableSetMultimap) { return multimap; } return new SynchronizedSetMultimap<K, V>(multimap, mutex); } private static class SynchronizedSetMultimap<K, V> extends SynchronizedMultimap<K, V> implements SetMultimap<K, V> { transient Set<Map.Entry<K, V>> entrySet; SynchronizedSetMultimap( SetMultimap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override SetMultimap<K, V> delegate() { return (SetMultimap<K, V>) super.delegate(); } @Override public Set<V> get(K key) { synchronized (mutex) { return set(delegate().get(key), mutex); } } @Override public Set<V> removeAll(Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public Set<V> replaceValues( K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } @Override public Set<Map.Entry<K, V>> entries() { synchronized (mutex) { if (entrySet == null) { entrySet = set(delegate().entries(), mutex); } return entrySet; } } private static final long serialVersionUID = 0; } static <K, V> SortedSetMultimap<K, V> sortedSetMultimap( SortedSetMultimap<K, V> multimap, @Nullable Object mutex) { if (multimap instanceof SynchronizedSortedSetMultimap) { return multimap; } return new SynchronizedSortedSetMultimap<K, V>(multimap, mutex); } private static class SynchronizedSortedSetMultimap<K, V> extends SynchronizedSetMultimap<K, V> implements SortedSetMultimap<K, V> { SynchronizedSortedSetMultimap( SortedSetMultimap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override SortedSetMultimap<K, V> delegate() { return (SortedSetMultimap<K, V>) super.delegate(); } @Override public SortedSet<V> get(K key) { synchronized (mutex) { return sortedSet(delegate().get(key), mutex); } } @Override public SortedSet<V> removeAll(Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public SortedSet<V> replaceValues( K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } @Override public Comparator<? super V> valueComparator() { synchronized (mutex) { return delegate().valueComparator(); } } private static final long serialVersionUID = 0; } private static <E> Collection<E> typePreservingCollection( Collection<E> collection, @Nullable Object mutex) { if (collection instanceof SortedSet) { return sortedSet((SortedSet<E>) collection, mutex); } if (collection instanceof Set) { return set((Set<E>) collection, mutex); } if (collection instanceof List) { return list((List<E>) collection, mutex); } return collection(collection, mutex); } private static <E> Set<E> typePreservingSet( Set<E> set, @Nullable Object mutex) { if (set instanceof SortedSet) { return sortedSet((SortedSet<E>) set, mutex); } else { return set(set, mutex); } } private static class SynchronizedAsMapEntries<K, V> extends SynchronizedSet<Map.Entry<K, Collection<V>>> { SynchronizedAsMapEntries( Set<Map.Entry<K, Collection<V>>> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override public Iterator<Map.Entry<K, Collection<V>>> iterator() { // Must be manually synchronized. final Iterator<Map.Entry<K, Collection<V>>> iterator = super.iterator(); return new ForwardingIterator<Map.Entry<K, Collection<V>>>() { @Override protected Iterator<Map.Entry<K, Collection<V>>> delegate() { return iterator; } @Override public Map.Entry<K, Collection<V>> next() { final Map.Entry<K, Collection<V>> entry = super.next(); return new ForwardingMapEntry<K, Collection<V>>() { @Override protected Map.Entry<K, Collection<V>> delegate() { return entry; } @Override public Collection<V> getValue() { return typePreservingCollection(entry.getValue(), mutex); } }; } }; } // See Collections.CheckedMap.CheckedEntrySet for details on attacks. @Override public Object[] toArray() { synchronized (mutex) { return ObjectArrays.toArrayImpl(delegate()); } } @Override public <T> T[] toArray(T[] array) { synchronized (mutex) { return ObjectArrays.toArrayImpl(delegate(), array); } } @Override public boolean contains(Object o) { synchronized (mutex) { return Maps.containsEntryImpl(delegate(), o); } } @Override public boolean containsAll(Collection<?> c) { synchronized (mutex) { return Collections2.containsAllImpl(delegate(), c); } } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return Sets.equalsImpl(delegate(), o); } } @Override public boolean remove(Object o) { synchronized (mutex) { return Maps.removeEntryImpl(delegate(), o); } } @Override public boolean removeAll(Collection<?> c) { synchronized (mutex) { return Iterators.removeAll(delegate().iterator(), c); } } @Override public boolean retainAll(Collection<?> c) { synchronized (mutex) { return Iterators.retainAll(delegate().iterator(), c); } } private static final long serialVersionUID = 0; } @VisibleForTesting static <K, V> Map<K, V> map(Map<K, V> map, @Nullable Object mutex) { return new SynchronizedMap<K, V>(map, mutex); } private static class SynchronizedMap<K, V> extends SynchronizedObject implements Map<K, V> { transient Set<K> keySet; transient Collection<V> values; transient Set<Map.Entry<K, V>> entrySet; SynchronizedMap(Map<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @SuppressWarnings("unchecked") @Override Map<K, V> delegate() { return (Map<K, V>) super.delegate(); } @Override public void clear() { synchronized (mutex) { delegate().clear(); } } @Override public boolean containsKey(Object key) { synchronized (mutex) { return delegate().containsKey(key); } } @Override public boolean containsValue(Object value) { synchronized (mutex) { return delegate().containsValue(value); } } @Override public Set<Map.Entry<K, V>> entrySet() { synchronized (mutex) { if (entrySet == null) { entrySet = set(delegate().entrySet(), mutex); } return entrySet; } } @Override public V get(Object key) { synchronized (mutex) { return delegate().get(key); } } @Override public boolean isEmpty() { synchronized (mutex) { return delegate().isEmpty(); } } @Override public Set<K> keySet() { synchronized (mutex) { if (keySet == null) { keySet = set(delegate().keySet(), mutex); } return keySet; } } @Override public V put(K key, V value) { synchronized (mutex) { return delegate().put(key, value); } } @Override public void putAll(Map<? extends K, ? extends V> map) { synchronized (mutex) { delegate().putAll(map); } } @Override public V remove(Object key) { synchronized (mutex) { return delegate().remove(key); } } @Override public int size() { synchronized (mutex) { return delegate().size(); } } @Override public Collection<V> values() { synchronized (mutex) { if (values == null) { values = collection(delegate().values(), mutex); } return values; } } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } static <K, V> SortedMap<K, V> sortedMap( SortedMap<K, V> sortedMap, @Nullable Object mutex) { return new SynchronizedSortedMap<K, V>(sortedMap, mutex); } static class SynchronizedSortedMap<K, V> extends SynchronizedMap<K, V> implements SortedMap<K, V> { SynchronizedSortedMap(SortedMap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override SortedMap<K, V> delegate() { return (SortedMap<K, V>) super.delegate(); } @Override public Comparator<? super K> comparator() { synchronized (mutex) { return delegate().comparator(); } } @Override public K firstKey() { synchronized (mutex) { return delegate().firstKey(); } } @Override public SortedMap<K, V> headMap(K toKey) { synchronized (mutex) { return sortedMap(delegate().headMap(toKey), mutex); } } @Override public K lastKey() { synchronized (mutex) { return delegate().lastKey(); } } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { synchronized (mutex) { return sortedMap(delegate().subMap(fromKey, toKey), mutex); } } @Override public SortedMap<K, V> tailMap(K fromKey) { synchronized (mutex) { return sortedMap(delegate().tailMap(fromKey), mutex); } } private static final long serialVersionUID = 0; } static <K, V> BiMap<K, V> biMap(BiMap<K, V> bimap, @Nullable Object mutex) { if (bimap instanceof SynchronizedBiMap || bimap instanceof ImmutableBiMap) { return bimap; } return new SynchronizedBiMap<K, V>(bimap, mutex, null); } @VisibleForTesting static class SynchronizedBiMap<K, V> extends SynchronizedMap<K, V> implements BiMap<K, V>, Serializable { private transient Set<V> valueSet; private transient BiMap<V, K> inverse; private SynchronizedBiMap(BiMap<K, V> delegate, @Nullable Object mutex, @Nullable BiMap<V, K> inverse) { super(delegate, mutex); this.inverse = inverse; } @Override BiMap<K, V> delegate() { return (BiMap<K, V>) super.delegate(); } @Override public Set<V> values() { synchronized (mutex) { if (valueSet == null) { valueSet = set(delegate().values(), mutex); } return valueSet; } } @Override public V forcePut(K key, V value) { synchronized (mutex) { return delegate().forcePut(key, value); } } @Override public BiMap<V, K> inverse() { synchronized (mutex) { if (inverse == null) { inverse = new SynchronizedBiMap<V, K>(delegate().inverse(), mutex, this); } return inverse; } } private static final long serialVersionUID = 0; } private static class SynchronizedAsMap<K, V> extends SynchronizedMap<K, Collection<V>> { transient Set<Map.Entry<K, Collection<V>>> asMapEntrySet; transient Collection<Collection<V>> asMapValues; SynchronizedAsMap(Map<K, Collection<V>> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override public Collection<V> get(Object key) { synchronized (mutex) { Collection<V> collection = super.get(key); return (collection == null) ? null : typePreservingCollection(collection, mutex); } } @Override public Set<Map.Entry<K, Collection<V>>> entrySet() { synchronized (mutex) { if (asMapEntrySet == null) { asMapEntrySet = new SynchronizedAsMapEntries<K, V>( delegate().entrySet(), mutex); } return asMapEntrySet; } } @Override public Collection<Collection<V>> values() { synchronized (mutex) { if (asMapValues == null) { asMapValues = new SynchronizedAsMapValues<V>(delegate().values(), mutex); } return asMapValues; } } @Override public boolean containsValue(Object o) { // values() and its contains() method are both synchronized. return values().contains(o); } private static final long serialVersionUID = 0; } private static class SynchronizedAsMapValues<V> extends SynchronizedCollection<Collection<V>> { SynchronizedAsMapValues( Collection<Collection<V>> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override public Iterator<Collection<V>> iterator() { // Must be manually synchronized. final Iterator<Collection<V>> iterator = super.iterator(); return new ForwardingIterator<Collection<V>>() { @Override protected Iterator<Collection<V>> delegate() { return iterator; } @Override public Collection<V> next() { return typePreservingCollection(super.next(), mutex); } }; } private static final long serialVersionUID = 0; } @GwtIncompatible("NavigableSet") @VisibleForTesting static class SynchronizedNavigableSet<E> extends SynchronizedSortedSet<E> implements NavigableSet<E> { SynchronizedNavigableSet(NavigableSet<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override NavigableSet<E> delegate() { return (NavigableSet<E>) super.delegate(); } @Override public E ceiling(E e) { synchronized (mutex) { return delegate().ceiling(e); } } @Override public Iterator<E> descendingIterator() { return delegate().descendingIterator(); // manually synchronized } transient NavigableSet<E> descendingSet; @Override public NavigableSet<E> descendingSet() { synchronized (mutex) { if (descendingSet == null) { NavigableSet<E> dS = Synchronized.navigableSet(delegate().descendingSet(), mutex); descendingSet = dS; return dS; } return descendingSet; } } @Override public E floor(E e) { synchronized (mutex) { return delegate().floor(e); } } @Override public NavigableSet<E> headSet(E toElement, boolean inclusive) { synchronized (mutex) { return Synchronized.navigableSet( delegate().headSet(toElement, inclusive), mutex); } } @Override public E higher(E e) { synchronized (mutex) { return delegate().higher(e); } } @Override public E lower(E e) { synchronized (mutex) { return delegate().lower(e); } } @Override public E pollFirst() { synchronized (mutex) { return delegate().pollFirst(); } } @Override public E pollLast() { synchronized (mutex) { return delegate().pollLast(); } } @Override public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { synchronized (mutex) { return Synchronized.navigableSet(delegate().subSet( fromElement, fromInclusive, toElement, toInclusive), mutex); } } @Override public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { synchronized (mutex) { return Synchronized.navigableSet( delegate().tailSet(fromElement, inclusive), mutex); } } @Override public SortedSet<E> headSet(E toElement) { return headSet(toElement, false); } @Override public SortedSet<E> subSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); } @Override public SortedSet<E> tailSet(E fromElement) { return tailSet(fromElement, true); } private static final long serialVersionUID = 0; } @GwtIncompatible("NavigableSet") static <E> NavigableSet<E> navigableSet( NavigableSet<E> navigableSet, @Nullable Object mutex) { return new SynchronizedNavigableSet<E>(navigableSet, mutex); } @GwtIncompatible("NavigableSet") static <E> NavigableSet<E> navigableSet(NavigableSet<E> navigableSet) { return navigableSet(navigableSet, null); } @GwtIncompatible("NavigableMap") static <K, V> NavigableMap<K, V> navigableMap( NavigableMap<K, V> navigableMap) { return navigableMap(navigableMap, null); } @GwtIncompatible("NavigableMap") static <K, V> NavigableMap<K, V> navigableMap( NavigableMap<K, V> navigableMap, @Nullable Object mutex) { return new SynchronizedNavigableMap<K, V>(navigableMap, mutex); } @GwtIncompatible("NavigableMap") @VisibleForTesting static class SynchronizedNavigableMap<K, V> extends SynchronizedSortedMap<K, V> implements NavigableMap<K, V> { SynchronizedNavigableMap( NavigableMap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override NavigableMap<K, V> delegate() { return (NavigableMap<K, V>) super.delegate(); } @Override public Entry<K, V> ceilingEntry(K key) { synchronized (mutex) { return nullableSynchronizedEntry(delegate().ceilingEntry(key), mutex); } } @Override public K ceilingKey(K key) { synchronized (mutex) { return delegate().ceilingKey(key); } } transient NavigableSet<K> descendingKeySet; @Override public NavigableSet<K> descendingKeySet() { synchronized (mutex) { if (descendingKeySet == null) { return descendingKeySet = Synchronized.navigableSet(delegate().descendingKeySet(), mutex); } return descendingKeySet; } } transient NavigableMap<K, V> descendingMap; @Override public NavigableMap<K, V> descendingMap() { synchronized (mutex) { if (descendingMap == null) { return descendingMap = navigableMap(delegate().descendingMap(), mutex); } return descendingMap; } } @Override public Entry<K, V> firstEntry() { synchronized (mutex) { return nullableSynchronizedEntry(delegate().firstEntry(), mutex); } } @Override public Entry<K, V> floorEntry(K key) { synchronized (mutex) { return nullableSynchronizedEntry(delegate().floorEntry(key), mutex); } } @Override public K floorKey(K key) { synchronized (mutex) { return delegate().floorKey(key); } } @Override public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { synchronized (mutex) { return navigableMap( delegate().headMap(toKey, inclusive), mutex); } } @Override public Entry<K, V> higherEntry(K key) { synchronized (mutex) { return nullableSynchronizedEntry(delegate().higherEntry(key), mutex); } } @Override public K higherKey(K key) { synchronized (mutex) { return delegate().higherKey(key); } } @Override public Entry<K, V> lastEntry() { synchronized (mutex) { return nullableSynchronizedEntry(delegate().lastEntry(), mutex); } } @Override public Entry<K, V> lowerEntry(K key) { synchronized (mutex) { return nullableSynchronizedEntry(delegate().lowerEntry(key), mutex); } } @Override public K lowerKey(K key) { synchronized (mutex) { return delegate().lowerKey(key); } } @Override public Set<K> keySet() { return navigableKeySet(); } transient NavigableSet<K> navigableKeySet; @Override public NavigableSet<K> navigableKeySet() { synchronized (mutex) { if (navigableKeySet == null) { return navigableKeySet = Synchronized.navigableSet(delegate().navigableKeySet(), mutex); } return navigableKeySet; } } @Override public Entry<K, V> pollFirstEntry() { synchronized (mutex) { return nullableSynchronizedEntry(delegate().pollFirstEntry(), mutex); } } @Override public Entry<K, V> pollLastEntry() { synchronized (mutex) { return nullableSynchronizedEntry(delegate().pollLastEntry(), mutex); } } @Override public NavigableMap<K, V> subMap( K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { synchronized (mutex) { return navigableMap( delegate().subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); } } @Override public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { synchronized (mutex) { return navigableMap( delegate().tailMap(fromKey, inclusive), mutex); } } @Override public SortedMap<K, V> headMap(K toKey) { return headMap(toKey, false); } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } @Override public SortedMap<K, V> tailMap(K fromKey) { return tailMap(fromKey, true); } private static final long serialVersionUID = 0; } @GwtIncompatible("works but is needed only for NavigableMap") private static <K, V> Entry<K, V> nullableSynchronizedEntry( @Nullable Entry<K, V> entry, @Nullable Object mutex) { if (entry == null) { return null; } return new SynchronizedEntry<K, V>(entry, mutex); } @GwtIncompatible("works but is needed only for NavigableMap") private static class SynchronizedEntry<K, V> extends SynchronizedObject implements Entry<K, V> { SynchronizedEntry(Entry<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @SuppressWarnings("unchecked") // guaranteed by the constructor @Override Entry<K, V> delegate() { return (Entry<K, V>) super.delegate(); } @Override public boolean equals(Object obj) { synchronized (mutex) { return delegate().equals(obj); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } @Override public K getKey() { synchronized (mutex) { return delegate().getKey(); } } @Override public V getValue() { synchronized (mutex) { return delegate().getValue(); } } @Override public V setValue(V value) { synchronized (mutex) { return delegate().setValue(value); } } private static final long serialVersionUID = 0; } static <E> Queue<E> queue(Queue<E> queue, @Nullable Object mutex) { return (queue instanceof SynchronizedQueue) ? queue : new SynchronizedQueue<E>(queue, mutex); } private static class SynchronizedQueue<E> extends SynchronizedCollection<E> implements Queue<E> { SynchronizedQueue(Queue<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override Queue<E> delegate() { return (Queue<E>) super.delegate(); } @Override public E element() { synchronized (mutex) { return delegate().element(); } } @Override public boolean offer(E e) { synchronized (mutex) { return delegate().offer(e); } } @Override public E peek() { synchronized (mutex) { return delegate().peek(); } } @Override public E poll() { synchronized (mutex) { return delegate().poll(); } } @Override public E remove() { synchronized (mutex) { return delegate().remove(); } } private static final long serialVersionUID = 0; } @GwtIncompatible("Deque") static <E> Deque<E> deque(Deque<E> deque, @Nullable Object mutex) { return new SynchronizedDeque<E>(deque, mutex); } @GwtIncompatible("Deque") private static final class SynchronizedDeque<E> extends SynchronizedQueue<E> implements Deque<E> { SynchronizedDeque(Deque<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override Deque<E> delegate() { return (Deque<E>) super.delegate(); } @Override public void addFirst(E e) { synchronized (mutex) { delegate().addFirst(e); } } @Override public void addLast(E e) { synchronized (mutex) { delegate().addLast(e); } } @Override public boolean offerFirst(E e) { synchronized (mutex) { return delegate().offerFirst(e); } } @Override public boolean offerLast(E e) { synchronized (mutex) { return delegate().offerLast(e); } } @Override public E removeFirst() { synchronized (mutex) { return delegate().removeFirst(); } } @Override public E removeLast() { synchronized (mutex) { return delegate().removeLast(); } } @Override public E pollFirst() { synchronized (mutex) { return delegate().pollFirst(); } } @Override public E pollLast() { synchronized (mutex) { return delegate().pollLast(); } } @Override public E getFirst() { synchronized (mutex) { return delegate().getFirst(); } } @Override public E getLast() { synchronized (mutex) { return delegate().getLast(); } } @Override public E peekFirst() { synchronized (mutex) { return delegate().peekFirst(); } } @Override public E peekLast() { synchronized (mutex) { return delegate().peekLast(); } } @Override public boolean removeFirstOccurrence(Object o) { synchronized (mutex) { return delegate().removeFirstOccurrence(o); } } @Override public boolean removeLastOccurrence(Object o) { synchronized (mutex) { return delegate().removeLastOccurrence(o); } } @Override public void push(E e) { synchronized (mutex) { delegate().push(e); } } @Override public E pop() { synchronized (mutex) { return delegate().pop(); } } @Override public Iterator<E> descendingIterator() { synchronized (mutex) { return delegate().descendingIterator(); } } 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 javax.annotation.Nullable; /** * Bimap with no mappings. * * @author Jared Levy */ @GwtCompatible(emulated = true) @SuppressWarnings("serial") // uses writeReplace(), not default serialization final class EmptyImmutableBiMap extends ImmutableBiMap<Object, Object> { static final EmptyImmutableBiMap INSTANCE = new EmptyImmutableBiMap(); private EmptyImmutableBiMap() {} @Override public ImmutableBiMap<Object, Object> inverse() { return this; } @Override public int size() { return 0; } @Override public boolean isEmpty() { return true; } @Override public Object get(@Nullable Object key) { return null; } @Override public ImmutableSet<Entry<Object, Object>> entrySet() { return ImmutableSet.of(); } @Override ImmutableSet<Entry<Object, Object>> createEntrySet() { throw new AssertionError("should never be called"); } @Override public ImmutableSetMultimap<Object, Object> asMultimap() { return ImmutableSetMultimap.of(); } @Override public ImmutableSet<Object> keySet() { return ImmutableSet.of(); } @Override boolean isPartialView() { return false; } Object readResolve() { return INSTANCE; // preserve singleton property } }
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 java.util.Map; import javax.annotation.Nullable; /** * Implementation of {@link ImmutableMultiset} with zero or more elements. * * @author Jared Levy * @author Louis Wasserman */ @GwtCompatible(serializable = true) @SuppressWarnings("serial") // uses writeReplace(), not default serialization class RegularImmutableMultiset<E> extends ImmutableMultiset<E> { private final transient ImmutableMap<E, Integer> map; private final transient int size; RegularImmutableMultiset(ImmutableMap<E, Integer> map, int size) { this.map = map; this.size = size; } @Override boolean isPartialView() { return map.isPartialView(); } @Override public int count(@Nullable Object element) { Integer value = map.get(element); return (value == null) ? 0 : value; } @Override public int size() { return size; } @Override public boolean contains(@Nullable Object element) { return map.containsKey(element); } @Override public ImmutableSet<E> elementSet() { return map.keySet(); } @Override Entry<E> getEntry(int index) { Map.Entry<E, Integer> mapEntry = map.entrySet().asList().get(index); return Multisets.immutableEntry(mapEntry.getKey(), mapEntry.getValue()); } @Override public int hashCode() { return map.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.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.Comparator; import javax.annotation.Nullable; /** An ordering for a pre-existing comparator. */ @GwtCompatible(serializable = true) final class ComparatorOrdering<T> extends Ordering<T> implements Serializable { final Comparator<T> comparator; ComparatorOrdering(Comparator<T> comparator) { this.comparator = checkNotNull(comparator); } @Override public int compare(T a, T b) { return comparator.compare(a, b); } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof ComparatorOrdering) { ComparatorOrdering<?> that = (ComparatorOrdering<?>) object; return this.comparator.equals(that.comparator); } return false; } @Override public int hashCode() { return comparator.hashCode(); } @Override public String toString() { return comparator.toString(); } 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 com.google.common.annotations.GwtCompatible; import java.util.Map.Entry; import java.util.Set; import javax.annotation.Nullable; /** * A set multimap which forwards all its method calls to another set multimap. * Subclasses should override one or more methods to modify the behavior of * the backing multimap as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * @author Kurt Alfred Kluever * @since 3.0 */ @GwtCompatible public abstract class ForwardingSetMultimap<K, V> extends ForwardingMultimap<K, V> implements SetMultimap<K, V> { @Override protected abstract SetMultimap<K, V> delegate(); @Override public Set<Entry<K, V>> entries() { return delegate().entries(); } @Override public Set<V> get(@Nullable K key) { return delegate().get(key); } @Override public Set<V> removeAll(@Nullable Object key) { return delegate().removeAll(key); } @Override public Set<V> replaceValues(K key, Iterable<? extends V> values) { return delegate().replaceValues(key, values); } }
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.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndex; import static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.math.IntMath; import java.util.AbstractQueue; import java.util.ArrayDeque; import java.util.ArrayList; 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.NoSuchElementException; import java.util.PriorityQueue; import java.util.Queue; /** * A double-ended priority queue, which provides constant-time access to both * its least element and its greatest element, as determined by the queue's * specified comparator. If no comparator is given at construction time, the * natural order of elements is used. * * <p>As a {@link Queue} it functions exactly as a {@link PriorityQueue}: its * head element -- the implicit target of the methods {@link #peek()}, {@link * #poll()} and {@link #remove()} -- is defined as the <i>least</i> element in * the queue according to the queue's comparator. But unlike a regular priority * queue, the methods {@link #peekLast}, {@link #pollLast} and * {@link #removeLast} are also provided, to act on the <i>greatest</i> element * in the queue instead. * * <p>A min-max priority queue can be configured with a maximum size. If so, * each time the size of the queue exceeds that value, the queue automatically * removes its greatest element according to its comparator (which might be the * element that was just added). This is different from conventional bounded * queues, which either block or reject new elements when full. * * <p>This implementation is based on the * <a href="http://portal.acm.org/citation.cfm?id=6621">min-max heap</a> * developed by Atkinson, et al. Unlike many other double-ended priority queues, * it stores elements in a single array, as compact as the traditional heap data * structure used in {@link PriorityQueue}. * * <p>This class is not thread-safe, and does not accept null elements. * * <p><i>Performance notes:</i> * * <ul> * <li>The retrieval operations {@link #peek}, {@link #peekFirst}, {@link * #peekLast}, {@link #element}, and {@link #size} are constant-time * <li>The enqueing and dequeing operations ({@link #offer}, {@link #add}, and * all the forms of {@link #poll} and {@link #remove()}) run in {@code * O(log n) time} * <li>The {@link #remove(Object)} and {@link #contains} operations require * linear ({@code O(n)}) time * <li>If you only access one end of the queue, and don't use a maximum size, * this class is functionally equivalent to {@link PriorityQueue}, but * significantly slower. * </ul> * * @author Sverre Sundsdal * @author Torbjorn Gannholm * @since 8.0 */ // TODO(kevinb): GWT compatibility @Beta public final class MinMaxPriorityQueue<E> extends AbstractQueue<E> { /** * Creates a new min-max priority queue with default settings: natural order, * no maximum size, no initial contents, and an initial expected size of 11. */ public static <E extends Comparable<E>> MinMaxPriorityQueue<E> create() { return new Builder<Comparable>(Ordering.natural()).create(); } /** * Creates a new min-max priority queue using natural order, no maximum size, * and initially containing the given elements. */ public static <E extends Comparable<E>> MinMaxPriorityQueue<E> create( Iterable<? extends E> initialContents) { return new Builder<E>(Ordering.<E>natural()).create(initialContents); } /** * Creates and returns a new builder, configured to build {@code * MinMaxPriorityQueue} instances that use {@code comparator} to determine the * least and greatest elements. */ public static <B> Builder<B> orderedBy(Comparator<B> comparator) { return new Builder<B>(comparator); } /** * Creates and returns a new builder, configured to build {@code * MinMaxPriorityQueue} instances sized appropriately to hold {@code * expectedSize} elements. */ public static Builder<Comparable> expectedSize(int expectedSize) { return new Builder<Comparable>(Ordering.natural()) .expectedSize(expectedSize); } /** * Creates and returns a new builder, configured to build {@code * MinMaxPriorityQueue} instances that are limited to {@code maximumSize} * elements. Each time a queue grows beyond this bound, it immediately * removes its greatest element (according to its comparator), which might be * the element that was just added. */ public static Builder<Comparable> maximumSize(int maximumSize) { return new Builder<Comparable>(Ordering.natural()) .maximumSize(maximumSize); } /** * The builder class used in creation of min-max priority queues. Instead of * constructing one directly, use {@link * MinMaxPriorityQueue#orderedBy(Comparator)}, {@link * MinMaxPriorityQueue#expectedSize(int)} or {@link * MinMaxPriorityQueue#maximumSize(int)}. * * @param <B> the upper bound on the eventual type that can be produced by * this builder (for example, a {@code Builder<Number>} can produce a * {@code Queue<Number>} or {@code Queue<Integer>} but not a {@code * Queue<Object>}). * @since 8.0 */ @Beta public static final class Builder<B> { /* * TODO(kevinb): when the dust settles, see if we still need this or can * just default to DEFAULT_CAPACITY. */ private static final int UNSET_EXPECTED_SIZE = -1; private final Comparator<B> comparator; private int expectedSize = UNSET_EXPECTED_SIZE; private int maximumSize = Integer.MAX_VALUE; private Builder(Comparator<B> comparator) { this.comparator = checkNotNull(comparator); } /** * Configures this builder to build min-max priority queues with an initial * expected size of {@code expectedSize}. */ public Builder<B> expectedSize(int expectedSize) { checkArgument(expectedSize >= 0); this.expectedSize = expectedSize; return this; } /** * Configures this builder to build {@code MinMaxPriorityQueue} instances * that are limited to {@code maximumSize} elements. Each time a queue grows * beyond this bound, it immediately removes its greatest element (according * to its comparator), which might be the element that was just added. */ public Builder<B> maximumSize(int maximumSize) { checkArgument(maximumSize > 0); this.maximumSize = maximumSize; return this; } /** * Builds a new min-max priority queue using the previously specified * options, and having no initial contents. */ public <T extends B> MinMaxPriorityQueue<T> create() { return create(Collections.<T>emptySet()); } /** * Builds a new min-max priority queue using the previously specified * options, and having the given initial elements. */ public <T extends B> MinMaxPriorityQueue<T> create( Iterable<? extends T> initialContents) { MinMaxPriorityQueue<T> queue = new MinMaxPriorityQueue<T>( this, initialQueueSize(expectedSize, maximumSize, initialContents)); for (T element : initialContents) { queue.offer(element); } return queue; } @SuppressWarnings("unchecked") // safe "contravariant cast" private <T extends B> Ordering<T> ordering() { return Ordering.from((Comparator<T>) comparator); } } private final Heap minHeap; private final Heap maxHeap; @VisibleForTesting final int maximumSize; private Object[] queue; private int size; private int modCount; private MinMaxPriorityQueue(Builder<? super E> builder, int queueSize) { Ordering<E> ordering = builder.ordering(); this.minHeap = new Heap(ordering); this.maxHeap = new Heap(ordering.reverse()); minHeap.otherHeap = maxHeap; maxHeap.otherHeap = minHeap; this.maximumSize = builder.maximumSize; // TODO(kevinb): pad? this.queue = new Object[queueSize]; } @Override public int size() { return size; } /** * Adds the given element to this queue. If this queue has a maximum size, * after adding {@code element} the queue will automatically evict its * greatest element (according to its comparator), which may be {@code * element} itself. * * @return {@code true} always */ @Override public boolean add(E element) { offer(element); return true; } @Override public boolean addAll(Collection<? extends E> newElements) { boolean modified = false; for (E element : newElements) { offer(element); modified = true; } return modified; } /** * Adds the given element to this queue. If this queue has a maximum size, * after adding {@code element} the queue will automatically evict its * greatest element (according to its comparator), which may be {@code * element} itself. */ @Override public boolean offer(E element) { checkNotNull(element); modCount++; int insertIndex = size++; growIfNeeded(); // Adds the element to the end of the heap and bubbles it up to the correct // position. heapForIndex(insertIndex).bubbleUp(insertIndex, element); return size <= maximumSize || pollLast() != element; } @Override public E poll() { return isEmpty() ? null : removeAndGet(0); } @SuppressWarnings("unchecked") // we must carefully only allow Es to get in E elementData(int index) { return (E) queue[index]; } @Override public E peek() { return isEmpty() ? null : elementData(0); } /** * Returns the index of the max element. */ private int getMaxElementIndex() { switch (size) { case 1: return 0; // The lone element in the queue is the maximum. case 2: return 1; // The lone element in the maxHeap is the maximum. default: // The max element must sit on the first level of the maxHeap. It is // actually the *lesser* of the two from the maxHeap's perspective. return (maxHeap.compareElements(1, 2) <= 0) ? 1 : 2; } } /** * Removes and returns the least element of this queue, or returns {@code * null} if the queue is empty. */ public E pollFirst() { return poll(); } /** * Removes and returns the least element of this queue. * * @throws NoSuchElementException if the queue is empty */ public E removeFirst() { return remove(); } /** * Retrieves, but does not remove, the least element of this queue, or returns * {@code null} if the queue is empty. */ public E peekFirst() { return peek(); } /** * Removes and returns the greatest element of this queue, or returns {@code * null} if the queue is empty. */ public E pollLast() { return isEmpty() ? null : removeAndGet(getMaxElementIndex()); } /** * Removes and returns the greatest element of this queue. * * @throws NoSuchElementException if the queue is empty */ public E removeLast() { if (isEmpty()) { throw new NoSuchElementException(); } return removeAndGet(getMaxElementIndex()); } /** * Retrieves, but does not remove, the greatest element of this queue, or * returns {@code null} if the queue is empty. */ public E peekLast() { return isEmpty() ? null : elementData(getMaxElementIndex()); } /** * Removes the element at position {@code index}. * * <p>Normally this method leaves the elements at up to {@code index - 1}, * inclusive, untouched. Under these circumstances, it returns {@code null}. * * <p>Occasionally, in order to maintain the heap invariant, it must swap a * later element of the list with one before {@code index}. Under these * circumstances it returns a pair of elements as a {@link MoveDesc}. The * first one is the element that was previously at the end of the heap and is * now at some position before {@code index}. The second element is the one * that was swapped down to replace the element at {@code index}. This fact is * used by iterator.remove so as to visit elements during a traversal once and * only once. */ @VisibleForTesting MoveDesc<E> removeAt(int index) { checkPositionIndex(index, size); modCount++; size--; if (size == index) { queue[size] = null; return null; } E actualLastElement = elementData(size); int lastElementAt = heapForIndex(size) .getCorrectLastElement(actualLastElement); E toTrickle = elementData(size); queue[size] = null; MoveDesc<E> changes = fillHole(index, toTrickle); if (lastElementAt < index) { // Last element is moved to before index, swapped with trickled element. if (changes == null) { // The trickled element is still after index. return new MoveDesc<E>(actualLastElement, toTrickle); } else { // The trickled element is back before index, but the replaced element // has now been moved after index. return new MoveDesc<E>(actualLastElement, changes.replaced); } } // Trickled element was after index to begin with, no adjustment needed. return changes; } private MoveDesc<E> fillHole(int index, E toTrickle) { Heap heap = heapForIndex(index); // We consider elementData(index) a "hole", and we want to fill it // with the last element of the heap, toTrickle. // Since the last element of the heap is from the bottom level, we // optimistically fill index position with elements from lower levels, // moving the hole down. In most cases this reduces the number of // comparisons with toTrickle, but in some cases we will need to bubble it // all the way up again. int vacated = heap.fillHoleAt(index); // Try to see if toTrickle can be bubbled up min levels. int bubbledTo = heap.bubbleUpAlternatingLevels(vacated, toTrickle); if (bubbledTo == vacated) { // Could not bubble toTrickle up min levels, try moving // it from min level to max level (or max to min level) and bubble up // there. return heap.tryCrossOverAndBubbleUp(index, vacated, toTrickle); } else { return (bubbledTo < index) ? new MoveDesc<E>(toTrickle, elementData(index)) : null; } } // Returned from removeAt() to iterator.remove() static class MoveDesc<E> { final E toTrickle; final E replaced; MoveDesc(E toTrickle, E replaced) { this.toTrickle = toTrickle; this.replaced = replaced; } } /** * Removes and returns the value at {@code index}. */ private E removeAndGet(int index) { E value = elementData(index); removeAt(index); return value; } private Heap heapForIndex(int i) { return isEvenLevel(i) ? minHeap : maxHeap; } private static final int EVEN_POWERS_OF_TWO = 0x55555555; private static final int ODD_POWERS_OF_TWO = 0xaaaaaaaa; @VisibleForTesting static boolean isEvenLevel(int index) { int oneBased = index + 1; checkState(oneBased > 0, "negative index"); return (oneBased & EVEN_POWERS_OF_TWO) > (oneBased & ODD_POWERS_OF_TWO); } /** * Returns {@code true} if the MinMax heap structure holds. This is only used * in testing. * * TODO(kevinb): move to the test class? */ @VisibleForTesting boolean isIntact() { for (int i = 1; i < size; i++) { if (!heapForIndex(i).verifyIndex(i)) { return false; } } return true; } /** * Each instance of MinMaxPriortyQueue encapsulates two instances of Heap: * a min-heap and a max-heap. Conceptually, these might each have their own * array for storage, but for efficiency's sake they are stored interleaved on * alternate heap levels in the same array (MMPQ.queue). */ private class Heap { final Ordering<E> ordering; Heap otherHeap; Heap(Ordering<E> ordering) { this.ordering = ordering; } int compareElements(int a, int b) { return ordering.compare(elementData(a), elementData(b)); } /** * Tries to move {@code toTrickle} from a min to a max level and * bubble up there. If it moved before {@code removeIndex} this method * returns a pair as described in {@link #removeAt}. */ MoveDesc<E> tryCrossOverAndBubbleUp( int removeIndex, int vacated, E toTrickle) { int crossOver = crossOver(vacated, toTrickle); if (crossOver == vacated) { return null; } // Successfully crossed over from min to max. // Bubble up max levels. E parent; // If toTrickle is moved up to a parent of removeIndex, the parent is // placed in removeIndex position. We must return that to the iterator so // that it knows to skip it. if (crossOver < removeIndex) { // We crossed over to the parent level in crossOver, so the parent // has already been moved. parent = elementData(removeIndex); } else { parent = elementData(getParentIndex(removeIndex)); } // bubble it up the opposite heap if (otherHeap.bubbleUpAlternatingLevels(crossOver, toTrickle) < removeIndex) { return new MoveDesc<E>(toTrickle, parent); } else { return null; } } /** * Bubbles a value from {@code index} up the appropriate heap if required. */ void bubbleUp(int index, E x) { int crossOver = crossOverUp(index, x); Heap heap; if (crossOver == index) { heap = this; } else { index = crossOver; heap = otherHeap; } heap.bubbleUpAlternatingLevels(index, x); } /** * Bubbles a value from {@code index} up the levels of this heap, and * returns the index the element ended up at. */ int bubbleUpAlternatingLevels(int index, E x) { while (index > 2) { int grandParentIndex = getGrandparentIndex(index); E e = elementData(grandParentIndex); if (ordering.compare(e, x) <= 0) { break; } queue[index] = e; index = grandParentIndex; } queue[index] = x; return index; } /** * Returns the index of minimum value between {@code index} and * {@code index + len}, or {@code -1} if {@code index} is greater than * {@code size}. */ int findMin(int index, int len) { if (index >= size) { return -1; } checkState(index > 0); int limit = Math.min(index, size - len) + len; int minIndex = index; for (int i = index + 1; i < limit; i++) { if (compareElements(i, minIndex) < 0) { minIndex = i; } } return minIndex; } /** * Returns the minimum child or {@code -1} if no child exists. */ int findMinChild(int index) { return findMin(getLeftChildIndex(index), 2); } /** * Returns the minimum grand child or -1 if no grand child exists. */ int findMinGrandChild(int index) { int leftChildIndex = getLeftChildIndex(index); if (leftChildIndex < 0) { return -1; } return findMin(getLeftChildIndex(leftChildIndex), 4); } /** * Moves an element one level up from a min level to a max level * (or vice versa). * Returns the new position of the element. */ int crossOverUp(int index, E x) { if (index == 0) { queue[0] = x; return 0; } int parentIndex = getParentIndex(index); E parentElement = elementData(parentIndex); if (parentIndex != 0) { // This is a guard for the case of the childless uncle. // Since the end of the array is actually the middle of the heap, // a smaller childless uncle can become a child of x when we // bubble up alternate levels, violating the invariant. int grandparentIndex = getParentIndex(parentIndex); int uncleIndex = getRightChildIndex(grandparentIndex); if (uncleIndex != parentIndex && getLeftChildIndex(uncleIndex) >= size) { E uncleElement = elementData(uncleIndex); if (ordering.compare(uncleElement, parentElement) < 0) { parentIndex = uncleIndex; parentElement = uncleElement; } } } if (ordering.compare(parentElement, x) < 0) { queue[index] = parentElement; queue[parentIndex] = x; return parentIndex; } queue[index] = x; return index; } /** * Returns the conceptually correct last element of the heap. * * <p>Since the last element of the array is actually in the * middle of the sorted structure, a childless uncle node could be * smaller, which would corrupt the invariant if this element * becomes the new parent of the uncle. In that case, we first * switch the last element with its uncle, before returning. */ int getCorrectLastElement(E actualLastElement) { int parentIndex = getParentIndex(size); if (parentIndex != 0) { int grandparentIndex = getParentIndex(parentIndex); int uncleIndex = getRightChildIndex(grandparentIndex); if (uncleIndex != parentIndex && getLeftChildIndex(uncleIndex) >= size) { E uncleElement = elementData(uncleIndex); if (ordering.compare(uncleElement, actualLastElement) < 0) { queue[uncleIndex] = actualLastElement; queue[size] = uncleElement; return uncleIndex; } } } return size; } /** * Crosses an element over to the opposite heap by moving it one level down * (or up if there are no elements below it). * * Returns the new position of the element. */ int crossOver(int index, E x) { int minChildIndex = findMinChild(index); // TODO(kevinb): split the && into two if's and move crossOverUp so it's // only called when there's no child. if ((minChildIndex > 0) && (ordering.compare(elementData(minChildIndex), x) < 0)) { queue[index] = elementData(minChildIndex); queue[minChildIndex] = x; return minChildIndex; } return crossOverUp(index, x); } /** * Fills the hole at {@code index} by moving in the least of its * grandchildren to this position, then recursively filling the new hole * created. * * @return the position of the new hole (where the lowest grandchild moved * from, that had no grandchild to replace it) */ int fillHoleAt(int index) { int minGrandchildIndex; while ((minGrandchildIndex = findMinGrandChild(index)) > 0) { queue[index] = elementData(minGrandchildIndex); index = minGrandchildIndex; } return index; } private boolean verifyIndex(int i) { if ((getLeftChildIndex(i) < size) && (compareElements(i, getLeftChildIndex(i)) > 0)) { return false; } if ((getRightChildIndex(i) < size) && (compareElements(i, getRightChildIndex(i)) > 0)) { return false; } if ((i > 0) && (compareElements(i, getParentIndex(i)) > 0)) { return false; } if ((i > 2) && (compareElements(getGrandparentIndex(i), i) > 0)) { return false; } return true; } // These would be static if inner classes could have static members. private int getLeftChildIndex(int i) { return i * 2 + 1; } private int getRightChildIndex(int i) { return i * 2 + 2; } private int getParentIndex(int i) { return (i - 1) / 2; } private int getGrandparentIndex(int i) { return getParentIndex(getParentIndex(i)); // (i - 3) / 4 } } /** * Iterates the elements of the queue in no particular order. * * If the underlying queue is modified during iteration an exception will be * thrown. */ private class QueueIterator implements Iterator<E> { private int cursor = -1; private int expectedModCount = modCount; private Queue<E> forgetMeNot; private List<E> skipMe; private E lastFromForgetMeNot; private boolean canRemove; @Override public boolean hasNext() { checkModCount(); return (nextNotInSkipMe(cursor + 1) < size()) || ((forgetMeNot != null) && !forgetMeNot.isEmpty()); } @Override public E next() { checkModCount(); int tempCursor = nextNotInSkipMe(cursor + 1); if (tempCursor < size()) { cursor = tempCursor; canRemove = true; return elementData(cursor); } else if (forgetMeNot != null) { cursor = size(); lastFromForgetMeNot = forgetMeNot.poll(); if (lastFromForgetMeNot != null) { canRemove = true; return lastFromForgetMeNot; } } throw new NoSuchElementException( "iterator moved past last element in queue."); } @Override public void remove() { checkState(canRemove, "no calls to remove() since the last call to next()"); checkModCount(); canRemove = false; expectedModCount++; if (cursor < size()) { MoveDesc<E> moved = removeAt(cursor); if (moved != null) { if (forgetMeNot == null) { forgetMeNot = new ArrayDeque<E>(); skipMe = new ArrayList<E>(3); } forgetMeNot.add(moved.toTrickle); skipMe.add(moved.replaced); } cursor--; } else { // we must have set lastFromForgetMeNot in next() checkState(removeExact(lastFromForgetMeNot)); lastFromForgetMeNot = null; } } // Finds only this exact instance, not others that are equals() private boolean containsExact(Iterable<E> elements, E target) { for (E element : elements) { if (element == target) { return true; } } return false; } // Removes only this exact instance, not others that are equals() boolean removeExact(Object target) { for (int i = 0; i < size; i++) { if (queue[i] == target) { removeAt(i); return true; } } return false; } void checkModCount() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } /** * Returns the index of the first element after {@code c} that is not in * {@code skipMe} and returns {@code size()} if there is no such element. */ private int nextNotInSkipMe(int c) { if (skipMe != null) { while (c < size() && containsExact(skipMe, elementData(c))) { c++; } } return c; } } /** * Returns an iterator over the elements contained in this collection, * <i>in no particular order</i>. * * <p>The iterator is <i>fail-fast</i>: If the MinMaxPriorityQueue is modified * at any time after the iterator is created, in any way except through the * iterator's own remove method, the iterator will generally throw a * {@link ConcurrentModificationException}. Thus, in the face of concurrent * modification, the iterator fails quickly and cleanly, rather than risking * arbitrary, non-deterministic behavior at an undetermined time in the * future. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw {@code ConcurrentModificationException} on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * * @return an iterator over the elements contained in this collection */ @Override public Iterator<E> iterator() { return new QueueIterator(); } @Override public void clear() { for (int i = 0; i < size; i++) { queue[i] = null; } size = 0; } @Override public Object[] toArray() { Object[] copyTo = new Object[size]; System.arraycopy(queue, 0, copyTo, 0, size); return copyTo; } /** * Returns the comparator used to order the elements in this queue. Obeys the * general contract of {@link PriorityQueue#comparator}, but returns {@link * Ordering#natural} instead of {@code null} to indicate natural ordering. */ public Comparator<? super E> comparator() { return minHeap.ordering; } @VisibleForTesting int capacity() { return queue.length; } // Size/capacity-related methods private static final int DEFAULT_CAPACITY = 11; @VisibleForTesting static int initialQueueSize(int configuredExpectedSize, int maximumSize, Iterable<?> initialContents) { // Start with what they said, if they said it, otherwise DEFAULT_CAPACITY int result = (configuredExpectedSize == Builder.UNSET_EXPECTED_SIZE) ? DEFAULT_CAPACITY : configuredExpectedSize; // Enlarge to contain initial contents if (initialContents instanceof Collection) { int initialSize = ((Collection<?>) initialContents).size(); result = Math.max(result, initialSize); } // Now cap it at maxSize + 1 return capAtMaximumSize(result, maximumSize); } private void growIfNeeded() { if (size > queue.length) { int newCapacity = calculateNewCapacity(); Object[] newQueue = new Object[newCapacity]; System.arraycopy(queue, 0, newQueue, 0, queue.length); queue = newQueue; } } /** Returns ~2x the old capacity if small; ~1.5x otherwise. */ private int calculateNewCapacity() { int oldCapacity = queue.length; int newCapacity = (oldCapacity < 64) ? (oldCapacity + 1) * 2 : IntMath.checkedMultiply(oldCapacity / 2, 3); return capAtMaximumSize(newCapacity, maximumSize); } /** There's no reason for the queueSize to ever be more than maxSize + 1 */ private static int capAtMaximumSize(int queueSize, int maximumSize) { return Math.min(queueSize - 1, maximumSize) + 1; // don't overflow } }
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.SortedSet; import javax.annotation.Nullable; /** * A sorted set which forwards all its method calls to another sorted set. * Subclasses should override one or more methods to modify the behavior of the * backing sorted 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 ForwardingSortedSet} 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, where appropriate, 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 Mike Bostock * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingSortedSet<E> extends ForwardingSet<E> implements SortedSet<E> { /** Constructor for use by subclasses. */ protected ForwardingSortedSet() {} @Override protected abstract SortedSet<E> delegate(); @Override public Comparator<? super E> comparator() { return delegate().comparator(); } @Override public E first() { return delegate().first(); } @Override public SortedSet<E> headSet(E toElement) { return delegate().headSet(toElement); } @Override public E last() { return delegate().last(); } @Override public SortedSet<E> subSet(E fromElement, E toElement) { return delegate().subSet(fromElement, toElement); } @Override public SortedSet<E> tailSet(E fromElement) { return delegate().tailSet(fromElement); } // unsafe, but worst case is a CCE is thrown, which callers will be expecting @SuppressWarnings("unchecked") private int unsafeCompare(Object o1, Object o2) { Comparator<? super E> comparator = comparator(); return (comparator == null) ? ((Comparable<Object>) o1).compareTo(o2) : ((Comparator<Object>) comparator).compare(o1, o2); } /** * A sensible definition of {@link #contains} in terms of the {@code first()} * method of {@link #tailSet}. If you override {@link #tailSet}, you may wish * to override {@link #contains} to forward to this implementation. * * @since 7.0 */ @Override @Beta protected boolean standardContains(@Nullable Object object) { try { // any ClassCastExceptions are caught @SuppressWarnings("unchecked") SortedSet<Object> self = (SortedSet<Object>) this; Object ceiling = self.tailSet(object).first(); return unsafeCompare(ceiling, object) == 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()} * method of {@link #tailSet}. If you override {@link #tailSet}, you may wish * to override {@link #remove} to forward to this implementation. * * @since 7.0 */ @Override @Beta protected boolean standardRemove(@Nullable Object object) { try { // any ClassCastExceptions are caught @SuppressWarnings("unchecked") SortedSet<Object> self = (SortedSet<Object>) this; Iterator<Object> iterator = self.tailSet(object).iterator(); if (iterator.hasNext()) { Object ceiling = iterator.next(); if (unsafeCompare(ceiling, object) == 0) { iterator.remove(); return true; } } } catch (ClassCastException e) { return false; } catch (NullPointerException e) { return false; } return false; } /** * A sensible default implementation of {@link #subSet(Object, Object)} in * terms of {@link #headSet(Object)} and {@link #tailSet(Object)}. In some * situations, you may wish to override {@link #subSet(Object, Object)} to * forward to this implementation. * * @since 7.0 */ @Beta protected SortedSet<E> standardSubSet(E fromElement, E toElement) { return tailSet(fromElement).headSet(toElement); } }
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.Iterator; import java.util.NoSuchElementException; /** * An iterator that supports a one-element lookahead while iterating. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/CollectionHelpersExplained#PeekingIterator"> * {@code PeekingIterator}</a>. * * @author Mick Killianey * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public interface PeekingIterator<E> extends Iterator<E> { /** * Returns the next element in the iteration, without advancing the iteration. * * <p>Calls to {@code peek()} should not change the state of the iteration, * except that it <i>may</i> prevent removal of the most recent element via * {@link #remove()}. * * @throws NoSuchElementException if the iteration has no more elements * according to {@link #hasNext()} */ E peek(); /** * {@inheritDoc} * * <p>The objects returned by consecutive calls to {@link #peek()} then {@link * #next()} are guaranteed to be equal to each other. */ @Override E next(); /** * {@inheritDoc} * * <p>Implementations may or may not support removal when a call to {@link * #peek()} has occurred since the most recent call to {@link #next()}. * * @throws IllegalStateException if there has been a call to {@link #peek()} * since the most recent call to {@link #next()} and this implementation * does not support this sequence of calls (optional) */ @Override void remove(); }
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; /** * "Overrides" the {@link ImmutableMultiset} static methods that lack * {@link ImmutableSortedMultiset} equivalents with deprecated, exception-throwing versions. This * prevents accidents like the following: * * <pre> {@code * * List<Object> objects = ...; * // Sort them: * Set<Object> sorted = ImmutableSortedMultiset.copyOf(objects); * // BAD CODE! The returned multiset is actually an unsorted ImmutableMultiset!}</pre> * * <p>While we could put the overrides in {@link ImmutableSortedMultiset} itself, it seems clearer * to separate these "do not call" methods from those intended for normal use. * * @author Louis Wasserman */ abstract class ImmutableSortedMultisetFauxverideShim<E> extends ImmutableMultiset<E> { /** * Not supported. Use {@link ImmutableSortedMultiset#naturalOrder}, which offers better * type-safety, instead. This method exists only to hide {@link ImmutableMultiset#builder} from * consumers of {@code ImmutableSortedMultiset}. * * @throws UnsupportedOperationException always * @deprecated Use {@link ImmutableSortedMultiset#naturalOrder}, which offers better type-safety. */ @Deprecated public static <E> ImmutableSortedMultiset.Builder<E> builder() { throw new UnsupportedOperationException(); } /** * Not supported. <b>You are attempting to create a multiset that may contain a non-{@code * Comparable} element.</b> Proper calls will resolve to the version in {@code * ImmutableSortedMultiset}, not this dummy version. * * @throws UnsupportedOperationException always * @deprecated <b>Pass a parameter of type {@code Comparable} to use * {@link ImmutableSortedMultiset#of(Comparable)}.</b> */ @Deprecated public static <E> ImmutableSortedMultiset<E> of(E element) { throw new UnsupportedOperationException(); } /** * Not supported. <b>You are attempting to create a multiset that may contain a non-{@code * Comparable} element.</b> Proper calls will resolve to the version in {@code * ImmutableSortedMultiset}, not this dummy version. * * @throws UnsupportedOperationException always * @deprecated <b>Pass the parameters of type {@code Comparable} to use * {@link ImmutableSortedMultiset#of(Comparable, Comparable)}.</b> */ @Deprecated public static <E> ImmutableSortedMultiset<E> of(E e1, E e2) { throw new UnsupportedOperationException(); } /** * Not supported. <b>You are attempting to create a multiset that may contain a non-{@code * Comparable} element.</b> Proper calls will resolve to the version in {@code * ImmutableSortedMultiset}, not this dummy version. * * @throws UnsupportedOperationException always * @deprecated <b>Pass the parameters of type {@code Comparable} to use * {@link ImmutableSortedMultiset#of(Comparable, Comparable, Comparable)}.</b> */ @Deprecated public static <E> ImmutableSortedMultiset<E> of(E e1, E e2, E e3) { throw new UnsupportedOperationException(); } /** * Not supported. <b>You are attempting to create a multiset that may contain a non-{@code * Comparable} element.</b> Proper calls will resolve to the version in {@code * ImmutableSortedMultiset}, not this dummy version. * * @throws UnsupportedOperationException always * @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link * ImmutableSortedMultiset#of(Comparable, Comparable, Comparable, Comparable)}. </b> */ @Deprecated public static <E> ImmutableSortedMultiset<E> of(E e1, E e2, E e3, E e4) { throw new UnsupportedOperationException(); } /** * Not supported. <b>You are attempting to create a multiset that may contain a non-{@code * Comparable} element.</b> Proper calls will resolve to the version in {@code * ImmutableSortedMultiset}, not this dummy version. * * @throws UnsupportedOperationException always * @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link * ImmutableSortedMultiset#of(Comparable, Comparable, Comparable, Comparable, * Comparable)} . </b> */ @Deprecated public static <E> ImmutableSortedMultiset<E> of(E e1, E e2, E e3, E e4, E e5) { throw new UnsupportedOperationException(); } /** * Not supported. <b>You are attempting to create a multiset that may contain a non-{@code * Comparable} element.</b> Proper calls will resolve to the version in {@code * ImmutableSortedMultiset}, not this dummy version. * * @throws UnsupportedOperationException always * @deprecated <b>Pass the parameters of type {@code Comparable} to use {@link * ImmutableSortedMultiset#of(Comparable, Comparable, Comparable, Comparable, * Comparable, Comparable, Comparable...)} . </b> */ @Deprecated public static <E> ImmutableSortedMultiset<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 multiset that may contain non-{@code * Comparable} elements.</b> Proper calls will resolve to the version in {@code * ImmutableSortedMultiset}, not this dummy version. * * @throws UnsupportedOperationException always * @deprecated <b>Pass parameters of type {@code Comparable} to use * {@link ImmutableSortedMultiset#copyOf(Comparable[])}.</b> */ @Deprecated public static <E> ImmutableSortedMultiset<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 ImmutableSortedMultiset (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 ImmutableSortedMultiset matches that in * ImmutableMultiset. * * The result is that ImmutableSortedMultiset.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 ImmutableSortedMultiset wouldn't "inherit" * too-permissive factory methods from ImmutableMultiset. */ }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.primitives.Booleans; import java.io.Serializable; import java.util.NoSuchElementException; import javax.annotation.Nullable; /** * Implementation detail for the internal structure of {@link Range} instances. Represents * a unique way of "cutting" a "number line" (actually of instances of type {@code C}, not * necessarily "numbers") into two sections; this can be done below a certain value, above * a certain value, below all values or above all values. With this object defined in this * way, an interval can always be represented by a pair of {@code Cut} instances. * * @author Kevin Bourrillion */ @GwtCompatible abstract class Cut<C extends Comparable> implements Comparable<Cut<C>>, Serializable { final C endpoint; Cut(@Nullable C endpoint) { this.endpoint = endpoint; } abstract boolean isLessThan(C value); abstract BoundType typeAsLowerBound(); abstract BoundType typeAsUpperBound(); abstract Cut<C> withLowerBoundType(BoundType boundType, DiscreteDomain<C> domain); abstract Cut<C> withUpperBoundType(BoundType boundType, DiscreteDomain<C> domain); abstract void describeAsLowerBound(StringBuilder sb); abstract void describeAsUpperBound(StringBuilder sb); abstract C leastValueAbove(DiscreteDomain<C> domain); abstract C greatestValueBelow(DiscreteDomain<C> domain); /* * The canonical form is a BelowValue cut whenever possible, otherwise ABOVE_ALL, or * (only in the case of types that are unbounded below) BELOW_ALL. */ Cut<C> canonical(DiscreteDomain<C> domain) { return this; } // note: overriden by {BELOW,ABOVE}_ALL @Override public int compareTo(Cut<C> that) { if (that == belowAll()) { return 1; } if (that == aboveAll()) { return -1; } int result = Range.compareOrThrow(endpoint, that.endpoint); if (result != 0) { return result; } // same value. below comes before above return Booleans.compare( this instanceof AboveValue, that instanceof AboveValue); } C endpoint() { return endpoint; } @SuppressWarnings("unchecked") // catching CCE @Override public boolean equals(Object obj) { if (obj instanceof Cut) { // It might not really be a Cut<C>, but we'll catch a CCE if it's not Cut<C> that = (Cut<C>) obj; try { int compareResult = compareTo(that); return compareResult == 0; } catch (ClassCastException ignored) { } } return false; } /* * The implementation neither produces nor consumes any non-null instance of type C, so * casting the type parameter is safe. */ @SuppressWarnings("unchecked") static <C extends Comparable> Cut<C> belowAll() { return (Cut<C>) BelowAll.INSTANCE; } private static final long serialVersionUID = 0; private static final class BelowAll extends Cut<Comparable<?>> { private static final BelowAll INSTANCE = new BelowAll(); private BelowAll() { super(null); } @Override Comparable<?> endpoint() { throw new IllegalStateException("range unbounded on this side"); } @Override boolean isLessThan(Comparable<?> value) { return true; } @Override BoundType typeAsLowerBound() { throw new IllegalStateException(); } @Override BoundType typeAsUpperBound() { throw new AssertionError("this statement should be unreachable"); } @Override Cut<Comparable<?>> withLowerBoundType(BoundType boundType, DiscreteDomain<Comparable<?>> domain) { throw new IllegalStateException(); } @Override Cut<Comparable<?>> withUpperBoundType(BoundType boundType, DiscreteDomain<Comparable<?>> domain) { throw new AssertionError("this statement should be unreachable"); } @Override void describeAsLowerBound(StringBuilder sb) { sb.append("(-\u221e"); } @Override void describeAsUpperBound(StringBuilder sb) { throw new AssertionError(); } @Override Comparable<?> leastValueAbove( DiscreteDomain<Comparable<?>> domain) { return domain.minValue(); } @Override Comparable<?> greatestValueBelow( DiscreteDomain<Comparable<?>> domain) { throw new AssertionError(); } @Override Cut<Comparable<?>> canonical( DiscreteDomain<Comparable<?>> domain) { try { return Cut.<Comparable<?>>belowValue(domain.minValue()); } catch (NoSuchElementException e) { return this; } } @Override public int compareTo(Cut<Comparable<?>> o) { return (o == this) ? 0 : -1; } @Override public String toString() { return "-\u221e"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 0; } /* * The implementation neither produces nor consumes any non-null instance of * type C, so casting the type parameter is safe. */ @SuppressWarnings("unchecked") static <C extends Comparable> Cut<C> aboveAll() { return (Cut<C>) AboveAll.INSTANCE; } private static final class AboveAll extends Cut<Comparable<?>> { private static final AboveAll INSTANCE = new AboveAll(); private AboveAll() { super(null); } @Override Comparable<?> endpoint() { throw new IllegalStateException("range unbounded on this side"); } @Override boolean isLessThan(Comparable<?> value) { return false; } @Override BoundType typeAsLowerBound() { throw new AssertionError("this statement should be unreachable"); } @Override BoundType typeAsUpperBound() { throw new IllegalStateException(); } @Override Cut<Comparable<?>> withLowerBoundType(BoundType boundType, DiscreteDomain<Comparable<?>> domain) { throw new AssertionError("this statement should be unreachable"); } @Override Cut<Comparable<?>> withUpperBoundType(BoundType boundType, DiscreteDomain<Comparable<?>> domain) { throw new IllegalStateException(); } @Override void describeAsLowerBound(StringBuilder sb) { throw new AssertionError(); } @Override void describeAsUpperBound(StringBuilder sb) { sb.append("+\u221e)"); } @Override Comparable<?> leastValueAbove( DiscreteDomain<Comparable<?>> domain) { throw new AssertionError(); } @Override Comparable<?> greatestValueBelow( DiscreteDomain<Comparable<?>> domain) { return domain.maxValue(); } @Override public int compareTo(Cut<Comparable<?>> o) { return (o == this) ? 0 : 1; } @Override public String toString() { return "+\u221e"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 0; } static <C extends Comparable> Cut<C> belowValue(C endpoint) { return new BelowValue<C>(endpoint); } private static final class BelowValue<C extends Comparable> extends Cut<C> { BelowValue(C endpoint) { super(checkNotNull(endpoint)); } @Override boolean isLessThan(C value) { return Range.compareOrThrow(endpoint, value) <= 0; } @Override BoundType typeAsLowerBound() { return BoundType.CLOSED; } @Override BoundType typeAsUpperBound() { return BoundType.OPEN; } @Override Cut<C> withLowerBoundType(BoundType boundType, DiscreteDomain<C> domain) { switch (boundType) { case CLOSED: return this; case OPEN: @Nullable C previous = domain.previous(endpoint); return (previous == null) ? Cut.<C>belowAll() : new AboveValue<C>(previous); default: throw new AssertionError(); } } @Override Cut<C> withUpperBoundType(BoundType boundType, DiscreteDomain<C> domain) { switch (boundType) { case CLOSED: @Nullable C previous = domain.previous(endpoint); return (previous == null) ? Cut.<C>aboveAll() : new AboveValue<C>(previous); case OPEN: return this; default: throw new AssertionError(); } } @Override void describeAsLowerBound(StringBuilder sb) { sb.append('[').append(endpoint); } @Override void describeAsUpperBound(StringBuilder sb) { sb.append(endpoint).append(')'); } @Override C leastValueAbove(DiscreteDomain<C> domain) { return endpoint; } @Override C greatestValueBelow(DiscreteDomain<C> domain) { return domain.previous(endpoint); } @Override public int hashCode() { return endpoint.hashCode(); } @Override public String toString() { return "\\" + endpoint + "/"; } private static final long serialVersionUID = 0; } static <C extends Comparable> Cut<C> aboveValue(C endpoint) { return new AboveValue<C>(endpoint); } private static final class AboveValue<C extends Comparable> extends Cut<C> { AboveValue(C endpoint) { super(checkNotNull(endpoint)); } @Override boolean isLessThan(C value) { return Range.compareOrThrow(endpoint, value) < 0; } @Override BoundType typeAsLowerBound() { return BoundType.OPEN; } @Override BoundType typeAsUpperBound() { return BoundType.CLOSED; } @Override Cut<C> withLowerBoundType(BoundType boundType, DiscreteDomain<C> domain) { switch (boundType) { case OPEN: return this; case CLOSED: @Nullable C next = domain.next(endpoint); return (next == null) ? Cut.<C>belowAll() : belowValue(next); default: throw new AssertionError(); } } @Override Cut<C> withUpperBoundType(BoundType boundType, DiscreteDomain<C> domain) { switch (boundType) { case OPEN: @Nullable C next = domain.next(endpoint); return (next == null) ? Cut.<C>aboveAll() : belowValue(next); case CLOSED: return this; default: throw new AssertionError(); } } @Override void describeAsLowerBound(StringBuilder sb) { sb.append('(').append(endpoint); } @Override void describeAsUpperBound(StringBuilder sb) { sb.append(endpoint).append(']'); } @Override C leastValueAbove(DiscreteDomain<C> domain) { return domain.next(endpoint); } @Override C greatestValueBelow(DiscreteDomain<C> domain) { return endpoint; } @Override Cut<C> canonical(DiscreteDomain<C> domain) { C next = leastValueAbove(domain); return (next != null) ? belowValue(next) : Cut.<C>aboveAll(); } @Override public int hashCode() { return ~endpoint.hashCode(); } @Override public String toString() { return "/" + endpoint + "\\"; } 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.List; import java.util.Map; import javax.annotation.Nullable; /** * A {@code Multimap} that can hold duplicate key-value pairs and that maintains * the insertion ordering of values for a given key. See the {@link Multimap} * documentation for information common to all multimaps. * * <p>The {@link #get}, {@link #removeAll}, and {@link #replaceValues} methods * each return a {@link List} of values. Though the method signature doesn't say * so explicitly, the map returned by {@link #asMap} has {@code List} 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 ListMultimap<K, V> extends Multimap<K, V> { /** * {@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 java.util.Collection} specified in the {@link Multimap} interface. */ @Override List<V> get(@Nullable K 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 java.util.Collection} specified in the {@link Multimap} interface. */ @Override List<V> removeAll(@Nullable Object 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 java.util.Collection} specified in the {@link Multimap} interface. */ @Override List<V> replaceValues(K key, Iterable<? extends V> values); /** * {@inheritDoc} * * <p><b>Note:</b> The returned map's values are guaranteed to be of type * {@link List}. To obtain this map with the more specific generic type * {@code Map<K, List<V>>}, call {@link Multimaps#asMap(ListMultimap)} * instead. */ @Override Map<K, Collection<V>> 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. * * <p>An empty {@code ListMultimap} is equal to any other empty {@code * Multimap}, including an empty {@code SetMultimap}. */ @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.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.EnumMap; import java.util.HashMap; import java.util.Map; import javax.annotation.Nullable; /** * A {@code BiMap} backed by an {@code EnumMap} instance for keys-to-values, and * a {@code HashMap} instance for values-to-keys. Null keys are not permitted, * but null values are. An {@code EnumHashBiMap} and its inverse are both * serializable. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap"> * {@code BiMap}</a>. * * @author Mike Bostock * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class EnumHashBiMap<K extends Enum<K>, V> extends AbstractBiMap<K, V> { private transient Class<K> keyType; /** * Returns a new, empty {@code EnumHashBiMap} using the specified key type. * * @param keyType the key type */ public static <K extends Enum<K>, V> EnumHashBiMap<K, V> create(Class<K> keyType) { return new EnumHashBiMap<K, V>(keyType); } /** * Constructs a new bimap with the same mappings as the specified map. If the * specified map is an {@code EnumHashBiMap} or an {@link EnumBiMap}, the new * bimap has the same key type as the input bimap. Otherwise, the specified * map must contain at least one mapping, in order to determine the key type. * * @param map the map whose mappings are to be placed in this map * @throws IllegalArgumentException if map is not an {@code EnumBiMap} or an * {@code EnumHashBiMap} instance and contains no mappings */ public static <K extends Enum<K>, V> EnumHashBiMap<K, V> create(Map<K, ? extends V> map) { EnumHashBiMap<K, V> bimap = create(EnumBiMap.inferKeyType(map)); bimap.putAll(map); return bimap; } private EnumHashBiMap(Class<K> keyType) { super(WellBehavedMap.wrap( new EnumMap<K, V>(keyType)), Maps.<V, K>newHashMapWithExpectedSize( keyType.getEnumConstants().length)); this.keyType = keyType; } // Overriding these 3 methods to show that values may be null (but not keys) @Override K checkKey(K key) { return checkNotNull(key); } @Override public V put(K key, @Nullable V value) { return super.put(key, value); } @Override public V forcePut(K key, @Nullable V value) { return super.forcePut(key, value); } /** Returns the associated key type. */ public Class<K> keyType() { return keyType; } /** * @serialData the key class, number of entries, first key, first value, * second key, second value, and so on. */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(keyType); Serialization.writeMap(this, stream); } @SuppressWarnings("unchecked") // reading field populated by writeObject @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); keyType = (Class<K>) stream.readObject(); setDelegates(WellBehavedMap.wrap(new EnumMap<K, V>(keyType)), new HashMap<V, K>(keyType.getEnumConstants().length * 3 / 2)); Serialization.populateMap(this, stream); } @GwtIncompatible("only 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 com.google.common.annotations.GwtCompatible; import com.google.common.base.Supplier; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import javax.annotation.Nullable; /** * Implementation of {@link Table} using hash tables. * * <p>The views returned by {@link #column}, {@link #columnKeySet()}, and {@link * #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>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table"> * {@code Table}</a>. * * @author Jared Levy * @since 7.0 */ @GwtCompatible(serializable = true) public class HashBasedTable<R, C, V> extends StandardTable<R, C, V> { private static class Factory<C, V> implements Supplier<Map<C, V>>, Serializable { final int expectedSize; Factory(int expectedSize) { this.expectedSize = expectedSize; } @Override public Map<C, V> get() { return Maps.newHashMapWithExpectedSize(expectedSize); } private static final long serialVersionUID = 0; } /** * Creates an empty {@code HashBasedTable}. */ public static <R, C, V> HashBasedTable<R, C, V> create() { return new HashBasedTable<R, C, V>( new HashMap<R, Map<C, V>>(), new Factory<C, V>(0)); } /** * Creates an empty {@code HashBasedTable} with the specified map sizes. * * @param expectedRows the expected number of distinct row keys * @param expectedCellsPerRow the expected number of column key / value * mappings in each row * @throws IllegalArgumentException if {@code expectedRows} or {@code * expectedCellsPerRow} is negative */ public static <R, C, V> HashBasedTable<R, C, V> create( int expectedRows, int expectedCellsPerRow) { checkArgument(expectedCellsPerRow >= 0); Map<R, Map<C, V>> backingMap = Maps.newHashMapWithExpectedSize(expectedRows); return new HashBasedTable<R, C, V>( backingMap, new Factory<C, V>(expectedCellsPerRow)); } /** * Creates a {@code HashBasedTable} with the same mappings as the specified * table. * * @param table the table to copy * @throws NullPointerException if any of the row keys, column keys, or values * in {@code table} is null */ public static <R, C, V> HashBasedTable<R, C, V> create( Table<? extends R, ? extends C, ? extends V> table) { HashBasedTable<R, C, V> result = create(); result.putAll(table); return result; } HashBasedTable(Map<R, Map<C, V>> backingMap, Factory<C, V> factory) { super(backingMap, factory); } // Overriding so NullPointerTester test passes. @Override public boolean contains( @Nullable Object rowKey, @Nullable Object columnKey) { return super.contains(rowKey, columnKey); } @Override public boolean containsColumn(@Nullable Object columnKey) { return super.containsColumn(columnKey); } @Override public boolean containsRow(@Nullable Object rowKey) { return super.containsRow(rowKey); } @Override public boolean containsValue(@Nullable Object value) { return super.containsValue(value); } @Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) { return super.get(rowKey, columnKey); } @Override public boolean equals(@Nullable Object obj) { return super.equals(obj); } @Override public V remove( @Nullable Object rowKey, @Nullable Object columnKey) { return super.remove(rowKey, columnKey); } 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.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.BoundType.CLOSED; import static com.google.common.collect.BoundType.OPEN; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import java.io.Serializable; import java.util.Comparator; import javax.annotation.Nullable; /** * A generalized interval on any ordering, for internal use. Supports {@code null}. Unlike * {@link Range}, this allows the use of an arbitrary comparator. This is designed for use in the * implementation of subcollections of sorted collection types. * * <p>Whenever possible, use {@code Range} instead, which is better supported. * * @author Louis Wasserman */ @GwtCompatible(serializable = true) final class GeneralRange<T> implements Serializable { /** * Converts a Range to a GeneralRange. */ static <T extends Comparable> GeneralRange<T> from(Range<T> range) { @Nullable T lowerEndpoint = range.hasLowerBound() ? range.lowerEndpoint() : null; BoundType lowerBoundType = range.hasLowerBound() ? range.lowerBoundType() : OPEN; @Nullable T upperEndpoint = range.hasUpperBound() ? range.upperEndpoint() : null; BoundType upperBoundType = range.hasUpperBound() ? range.upperBoundType() : OPEN; return new GeneralRange<T>(Ordering.natural(), range.hasLowerBound(), lowerEndpoint, lowerBoundType, range.hasUpperBound(), upperEndpoint, upperBoundType); } /** * Returns the whole range relative to the specified comparator. */ static <T> GeneralRange<T> all(Comparator<? super T> comparator) { return new GeneralRange<T>(comparator, false, null, OPEN, false, null, OPEN); } /** * Returns everything above the endpoint relative to the specified comparator, with the specified * endpoint behavior. */ static <T> GeneralRange<T> downTo(Comparator<? super T> comparator, @Nullable T endpoint, BoundType boundType) { return new GeneralRange<T>(comparator, true, endpoint, boundType, false, null, OPEN); } /** * Returns everything below the endpoint relative to the specified comparator, with the specified * endpoint behavior. */ static <T> GeneralRange<T> upTo(Comparator<? super T> comparator, @Nullable T endpoint, BoundType boundType) { return new GeneralRange<T>(comparator, false, null, OPEN, true, endpoint, boundType); } /** * Returns everything between the endpoints relative to the specified comparator, with the * specified endpoint behavior. */ static <T> GeneralRange<T> range(Comparator<? super T> comparator, @Nullable T lower, BoundType lowerType, @Nullable T upper, BoundType upperType) { return new GeneralRange<T>(comparator, true, lower, lowerType, true, upper, upperType); } private final Comparator<? super T> comparator; private final boolean hasLowerBound; @Nullable private final T lowerEndpoint; private final BoundType lowerBoundType; private final boolean hasUpperBound; @Nullable private final T upperEndpoint; private final BoundType upperBoundType; private GeneralRange(Comparator<? super T> comparator, boolean hasLowerBound, @Nullable T lowerEndpoint, BoundType lowerBoundType, boolean hasUpperBound, @Nullable T upperEndpoint, BoundType upperBoundType) { this.comparator = checkNotNull(comparator); this.hasLowerBound = hasLowerBound; this.hasUpperBound = hasUpperBound; this.lowerEndpoint = lowerEndpoint; this.lowerBoundType = checkNotNull(lowerBoundType); this.upperEndpoint = upperEndpoint; this.upperBoundType = checkNotNull(upperBoundType); if (hasLowerBound) { comparator.compare(lowerEndpoint, lowerEndpoint); } if (hasUpperBound) { comparator.compare(upperEndpoint, upperEndpoint); } if (hasLowerBound && hasUpperBound) { int cmp = comparator.compare(lowerEndpoint, upperEndpoint); // be consistent with Range checkArgument(cmp <= 0, "lowerEndpoint (%s) > upperEndpoint (%s)", lowerEndpoint, upperEndpoint); if (cmp == 0) { checkArgument(lowerBoundType != OPEN | upperBoundType != OPEN); } } } Comparator<? super T> comparator() { return comparator; } boolean hasLowerBound() { return hasLowerBound; } boolean hasUpperBound() { return hasUpperBound; } boolean isEmpty() { return (hasUpperBound() && tooLow(getUpperEndpoint())) || (hasLowerBound() && tooHigh(getLowerEndpoint())); } boolean tooLow(@Nullable T t) { if (!hasLowerBound()) { return false; } T lbound = getLowerEndpoint(); int cmp = comparator.compare(t, lbound); return cmp < 0 | (cmp == 0 & getLowerBoundType() == OPEN); } boolean tooHigh(@Nullable T t) { if (!hasUpperBound()) { return false; } T ubound = getUpperEndpoint(); int cmp = comparator.compare(t, ubound); return cmp > 0 | (cmp == 0 & getUpperBoundType() == OPEN); } boolean contains(@Nullable T t) { return !tooLow(t) && !tooHigh(t); } /** * Returns the intersection of the two ranges, or an empty range if their intersection is empty. */ GeneralRange<T> intersect(GeneralRange<T> other) { checkNotNull(other); checkArgument(comparator.equals(other.comparator)); boolean hasLowBound = this.hasLowerBound; @Nullable T lowEnd = getLowerEndpoint(); BoundType lowType = getLowerBoundType(); if (!hasLowerBound()) { hasLowBound = other.hasLowerBound; lowEnd = other.getLowerEndpoint(); lowType = other.getLowerBoundType(); } else if (other.hasLowerBound()) { int cmp = comparator.compare(getLowerEndpoint(), other.getLowerEndpoint()); if (cmp < 0 || (cmp == 0 && other.getLowerBoundType() == OPEN)) { lowEnd = other.getLowerEndpoint(); lowType = other.getLowerBoundType(); } } boolean hasUpBound = this.hasUpperBound; @Nullable T upEnd = getUpperEndpoint(); BoundType upType = getUpperBoundType(); if (!hasUpperBound()) { hasUpBound = other.hasUpperBound; upEnd = other.getUpperEndpoint(); upType = other.getUpperBoundType(); } else if (other.hasUpperBound()) { int cmp = comparator.compare(getUpperEndpoint(), other.getUpperEndpoint()); if (cmp > 0 || (cmp == 0 && other.getUpperBoundType() == OPEN)) { upEnd = other.getUpperEndpoint(); upType = other.getUpperBoundType(); } } if (hasLowBound && hasUpBound) { int cmp = comparator.compare(lowEnd, upEnd); if (cmp > 0 || (cmp == 0 && lowType == OPEN && upType == OPEN)) { // force allowed empty range lowEnd = upEnd; lowType = OPEN; upType = CLOSED; } } return new GeneralRange<T>(comparator, hasLowBound, lowEnd, lowType, hasUpBound, upEnd, upType); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof GeneralRange) { GeneralRange<?> r = (GeneralRange<?>) obj; return comparator.equals(r.comparator) && hasLowerBound == r.hasLowerBound && hasUpperBound == r.hasUpperBound && getLowerBoundType().equals(r.getLowerBoundType()) && getUpperBoundType().equals(r.getUpperBoundType()) && Objects.equal(getLowerEndpoint(), r.getLowerEndpoint()) && Objects.equal(getUpperEndpoint(), r.getUpperEndpoint()); } return false; } @Override public int hashCode() { return Objects.hashCode(comparator, getLowerEndpoint(), getLowerBoundType(), getUpperEndpoint(), getUpperBoundType()); } private transient GeneralRange<T> reverse; /** * Returns the same range relative to the reversed comparator. */ GeneralRange<T> reverse() { GeneralRange<T> result = reverse; if (result == null) { result = new GeneralRange<T>( Ordering.from(comparator).reverse(), hasUpperBound, getUpperEndpoint(), getUpperBoundType(), hasLowerBound, getLowerEndpoint(), getLowerBoundType()); result.reverse = this; return this.reverse = result; } return result; } @Override public String toString() { return new StringBuilder() .append(comparator) .append(":") .append(lowerBoundType == CLOSED ? '[' : '(') .append(hasLowerBound ? lowerEndpoint : "-\u221e") .append(',') .append(hasUpperBound ? upperEndpoint : "\u221e") .append(upperBoundType == CLOSED ? ']' : ')') .toString(); } T getLowerEndpoint() { return lowerEndpoint; } BoundType getLowerBoundType() { return lowerBoundType; } T getUpperEndpoint() { return upperEndpoint; } BoundType getUpperBoundType() { return upperBoundType; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.Multiset.Entry; import com.google.common.primitives.Ints; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import javax.annotation.Nullable; /** * An immutable hash-based multiset. Does not permit null elements. * * <p>Its iterator orders elements according to the first appearance of the * element among the items passed to the factory method or builder. When the * multiset contains multiple instances of an element, those instances are * consecutive in the iteration order. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained"> * immutable collections</a>. * * @author Jared Levy * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // we're overriding default serialization // TODO(user): write an efficient asList() implementation public abstract class ImmutableMultiset<E> extends ImmutableCollection<E> implements Multiset<E> { private static final ImmutableMultiset<Object> EMPTY = new RegularImmutableMultiset<Object>(ImmutableMap.<Object, Integer>of(), 0); /** * Returns the empty immutable multiset. */ @SuppressWarnings("unchecked") // all supported methods are covariant public static <E> ImmutableMultiset<E> of() { return (ImmutableMultiset<E>) EMPTY; } /** * Returns an immutable multiset containing a single element. * * @throws NullPointerException if {@code element} is null * @since 6.0 (source-compatible since 2.0) */ @SuppressWarnings("unchecked") // generic array created but never written public static <E> ImmutableMultiset<E> of(E element) { return copyOfInternal(element); } /** * Returns an immutable multiset containing the given elements, in order. * * @throws NullPointerException if any element is null * @since 6.0 (source-compatible since 2.0) */ @SuppressWarnings("unchecked") // public static <E> ImmutableMultiset<E> of(E e1, E e2) { return copyOfInternal(e1, e2); } /** * Returns an immutable multiset containing the given elements, in order. * * @throws NullPointerException if any element is null * @since 6.0 (source-compatible since 2.0) */ @SuppressWarnings("unchecked") // public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3) { return copyOfInternal(e1, e2, e3); } /** * Returns an immutable multiset containing the given elements, in order. * * @throws NullPointerException if any element is null * @since 6.0 (source-compatible since 2.0) */ @SuppressWarnings("unchecked") // public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4) { return copyOfInternal(e1, e2, e3, e4); } /** * Returns an immutable multiset containing the given elements, in order. * * @throws NullPointerException if any element is null * @since 6.0 (source-compatible since 2.0) */ @SuppressWarnings("unchecked") // public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4, E e5) { return copyOfInternal(e1, e2, e3, e4, e5); } /** * Returns an immutable multiset containing the given elements, in order. * * @throws NullPointerException if any element is null * @since 6.0 (source-compatible since 2.0) */ @SuppressWarnings("unchecked") // public static <E> ImmutableMultiset<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E... others) { return new Builder<E>() .add(e1) .add(e2) .add(e3) .add(e4) .add(e5) .add(e6) .add(others) .build(); } /** * Returns an immutable multiset containing the given elements. * * <p>The multiset is ordered by the first occurrence of each element. For * example, {@code ImmutableMultiset.copyOf([2, 3, 1, 3])} yields a multiset * with elements in the order {@code 2, 3, 3, 1}. * * @throws NullPointerException if any of {@code elements} is null * @since 6.0 */ public static <E> ImmutableMultiset<E> copyOf(E[] elements) { return copyOf(Arrays.asList(elements)); } /** * Returns an immutable multiset containing the given elements. * * <p>The multiset is ordered by the first occurrence of each element. For * example, {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3))} yields * a multiset with elements in the order {@code 2, 3, 3, 1}. * * <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><b>Note:</b> Despite what the method name suggests, if {@code elements} * is an {@code ImmutableMultiset}, no copy will actually be performed, and * the given multiset itself will be returned. * * @throws NullPointerException if any of {@code elements} is null */ public static <E> ImmutableMultiset<E> copyOf( Iterable<? extends E> elements) { if (elements instanceof ImmutableMultiset) { @SuppressWarnings("unchecked") // all supported methods are covariant ImmutableMultiset<E> result = (ImmutableMultiset<E>) elements; if (!result.isPartialView()) { return result; } } Multiset<? extends E> multiset = (elements instanceof Multiset) ? Multisets.cast(elements) : LinkedHashMultiset.create(elements); return copyOfInternal(multiset); } private static <E> ImmutableMultiset<E> copyOfInternal(E... elements) { return copyOf(Arrays.asList(elements)); } private static <E> ImmutableMultiset<E> copyOfInternal( Multiset<? extends E> multiset) { return copyFromEntries(multiset.entrySet()); } static <E> ImmutableMultiset<E> copyFromEntries( Collection<? extends Entry<? extends E>> entries) { long size = 0; ImmutableMap.Builder<E, Integer> builder = ImmutableMap.builder(); for (Entry<? extends E> entry : entries) { int count = entry.getCount(); if (count > 0) { // Since ImmutableMap.Builder throws an NPE if an element is null, no // other null checks are needed. builder.put(entry.getElement(), count); size += count; } } if (size == 0) { return of(); } return new RegularImmutableMultiset<E>( builder.build(), Ints.saturatedCast(size)); } /** * Returns an immutable multiset containing the given elements. * * <p>The multiset is ordered by the first occurrence of each element. For * example, * {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3).iterator())} * yields a multiset with elements in the order {@code 2, 3, 3, 1}. * * @throws NullPointerException if any of {@code elements} is null */ public static <E> ImmutableMultiset<E> copyOf( Iterator<? extends E> elements) { Multiset<E> multiset = LinkedHashMultiset.create(); Iterators.addAll(multiset, elements); return copyOfInternal(multiset); } ImmutableMultiset() {} @Override public UnmodifiableIterator<E> iterator() { final Iterator<Entry<E>> entryIterator = entrySet().iterator(); return new UnmodifiableIterator<E>() { int remaining; E element; @Override public boolean hasNext() { return (remaining > 0) || entryIterator.hasNext(); } @Override public E next() { if (remaining <= 0) { Entry<E> entry = entryIterator.next(); element = entry.getElement(); remaining = entry.getCount(); } remaining--; return element; } }; } @Override public boolean contains(@Nullable Object object) { return count(object) > 0; } @Override public boolean containsAll(Collection<?> targets) { return elementSet().containsAll(targets); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final int add(E element, int occurrences) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final int remove(Object element, int occurrences) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final int setCount(E element, int count) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final boolean setCount(E element, int oldCount, int newCount) { throw new UnsupportedOperationException(); } @GwtIncompatible("not present in emulated superclass") @Override int copyIntoArray(Object[] dst, int offset) { for (Multiset.Entry<E> entry : entrySet()) { Arrays.fill(dst, offset, offset + entry.getCount(), entry.getElement()); offset += entry.getCount(); } return offset; } @Override public boolean equals(@Nullable Object object) { return Multisets.equalsImpl(this, object); } @Override public int hashCode() { return Sets.hashCodeImpl(entrySet()); } @Override public String toString() { return entrySet().toString(); } private transient ImmutableSet<Entry<E>> entrySet; @Override public ImmutableSet<Entry<E>> entrySet() { ImmutableSet<Entry<E>> es = entrySet; return (es == null) ? (entrySet = createEntrySet()) : es; } private final ImmutableSet<Entry<E>> createEntrySet() { return isEmpty() ? ImmutableSet.<Entry<E>>of() : new EntrySet(); } abstract Entry<E> getEntry(int index); private final class EntrySet extends ImmutableSet<Entry<E>> { @Override boolean isPartialView() { return ImmutableMultiset.this.isPartialView(); } @Override public UnmodifiableIterator<Entry<E>> iterator() { return asList().iterator(); } @Override ImmutableList<Entry<E>> createAsList() { return new ImmutableAsList<Entry<E>>() { @Override public Entry<E> get(int index) { return getEntry(index); } @Override ImmutableCollection<Entry<E>> delegateCollection() { return EntrySet.this; } }; } @Override public int size() { return elementSet().size(); } @Override public boolean contains(Object o) { if (o instanceof Entry) { Entry<?> entry = (Entry<?>) o; if (entry.getCount() <= 0) { return false; } int count = count(entry.getElement()); return count == entry.getCount(); } return false; } @Override public int hashCode() { return ImmutableMultiset.this.hashCode(); } // We can't label this with @Override, because it doesn't override anything // in the GWT emulated version. // TODO(cpovirk): try making all copies of this method @GwtIncompatible instead Object writeReplace() { return new EntrySetSerializedForm<E>(ImmutableMultiset.this); } private static final long serialVersionUID = 0; } static class EntrySetSerializedForm<E> implements Serializable { final ImmutableMultiset<E> multiset; EntrySetSerializedForm(ImmutableMultiset<E> multiset) { this.multiset = multiset; } Object readResolve() { return multiset.entrySet(); } } private static class SerializedForm implements Serializable { final Object[] elements; final int[] counts; SerializedForm(Multiset<?> multiset) { int distinct = multiset.entrySet().size(); elements = new Object[distinct]; counts = new int[distinct]; int i = 0; for (Entry<?> entry : multiset.entrySet()) { elements[i] = entry.getElement(); counts[i] = entry.getCount(); i++; } } Object readResolve() { LinkedHashMultiset<Object> multiset = LinkedHashMultiset.create(elements.length); for (int i = 0; i < elements.length; i++) { multiset.add(elements[i], counts[i]); } return ImmutableMultiset.copyOf(multiset); } private static final long serialVersionUID = 0; } // We can't label this with @Override, because it doesn't override anything // in the GWT emulated version. Object writeReplace() { return new SerializedForm(this); } /** * 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 multiset instances, especially {@code * public static final} multisets ("constant multisets"). Example: * <pre> {@code * * public static final ImmutableMultiset<Bean> BEANS = * new ImmutableMultiset.Builder<Bean>() * .addCopies(Bean.COCOA, 4) * .addCopies(Bean.GARDEN, 6) * .addCopies(Bean.RED, 8) * .addCopies(Bean.BLACK_EYED, 10) * .build();}</pre> * * <p>Builder instances can be reused; it is safe to call {@link #build} multiple * times to build multiple multisets in series. * * @since 2.0 (imported from Google Collections Library) */ public static class Builder<E> extends ImmutableCollection.Builder<E> { final Multiset<E> contents; /** * Creates a new builder. The returned builder is equivalent to the builder * generated by {@link ImmutableMultiset#builder}. */ public Builder() { this(LinkedHashMultiset.<E>create()); } Builder(Multiset<E> contents) { this.contents = contents; } /** * Adds {@code element} to the {@code ImmutableMultiset}. * * @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 a number of occurrences of an element to this {@code * ImmutableMultiset}. * * @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 */ public Builder<E> addCopies(E element, int occurrences) { contents.add(checkNotNull(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 */ public Builder<E> setCount(E element, int count) { contents.setCount(checkNotNull(element), count); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableMultiset}. * * @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 ImmutableMultiset}. * * @param elements the {@code Iterable} to add to the {@code * ImmutableMultiset} * @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 Multiset) { Multiset<? extends E> multiset = Multisets.cast(elements); for (Entry<? extends E> entry : multiset.entrySet()) { addCopies(entry.getElement(), entry.getCount()); } } else { super.addAll(elements); } return this; } /** * Adds each element of {@code elements} to the {@code ImmutableMultiset}. * * @param elements the elements to add to the {@code ImmutableMultiset} * @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 ImmutableMultiset} based on the contents * of the {@code Builder}. */ @Override public ImmutableMultiset<E> build() { return copyOf(contents); } } }
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.GwtCompatible; import com.google.common.base.Preconditions; import java.util.Collection; import java.util.List; import java.util.ListIterator; import java.util.RandomAccess; import java.util.Set; import java.util.SortedSet; /** * Factories and utilities pertaining to the {@link Constraint} interface. * * @see MapConstraints * @author Mike Bostock * @author Jared Levy * @since 3.0 * @deprecated Use {@link Preconditions} for basic checks. In place of * constrained collections, we encourage you to check your preconditions * explicitly instead of leaving that work to the collection implementation. * For the specific case of rejecting null, consider the immutable * collections. * This class is scheduled for removal in Guava 16.0. */ @Beta @Deprecated @GwtCompatible public final class Constraints { private Constraints() {} // enum singleton pattern private enum NotNullConstraint implements Constraint<Object> { INSTANCE; @Override public Object checkElement(Object element) { return checkNotNull(element); } @Override public String toString() { return "Not null"; } } /** * Returns a constraint that verifies that the element is not null. If the * element is null, a {@link NullPointerException} is thrown. */ // safe to narrow the type since checkElement returns its argument directly @SuppressWarnings("unchecked") public static <E> Constraint<E> notNull() { return (Constraint<E>) NotNullConstraint.INSTANCE; } /** * Returns a constrained view of the specified collection, using the specified * constraint. Any operations that add new elements to the collection will * call the provided constraint. However, this method does not verify that * existing elements satisfy the constraint. * * <p>The returned collection is not serializable. * * @param collection the collection to constrain * @param constraint the constraint that validates added elements * @return a constrained view of the collection */ public static <E> Collection<E> constrainedCollection( Collection<E> collection, Constraint<? super E> constraint) { return new ConstrainedCollection<E>(collection, constraint); } /** @see Constraints#constrainedCollection */ static class ConstrainedCollection<E> extends ForwardingCollection<E> { private final Collection<E> delegate; private final Constraint<? super E> constraint; public ConstrainedCollection( Collection<E> delegate, Constraint<? super E> constraint) { this.delegate = checkNotNull(delegate); this.constraint = checkNotNull(constraint); } @Override protected Collection<E> delegate() { return delegate; } @Override public boolean add(E element) { constraint.checkElement(element); return delegate.add(element); } @Override public boolean addAll(Collection<? extends E> elements) { return delegate.addAll(checkElements(elements, constraint)); } } /** * Returns a constrained view of the specified set, using the specified * constraint. Any operations that add new elements to the set will call the * provided constraint. However, this method does not verify that existing * elements satisfy the constraint. * * <p>The returned set is not serializable. * * @param set the set to constrain * @param constraint the constraint that validates added elements * @return a constrained view of the set */ public static <E> Set<E> constrainedSet( Set<E> set, Constraint<? super E> constraint) { return new ConstrainedSet<E>(set, constraint); } /** @see Constraints#constrainedSet */ static class ConstrainedSet<E> extends ForwardingSet<E> { private final Set<E> delegate; private final Constraint<? super E> constraint; public ConstrainedSet(Set<E> delegate, Constraint<? super E> constraint) { this.delegate = checkNotNull(delegate); this.constraint = checkNotNull(constraint); } @Override protected Set<E> delegate() { return delegate; } @Override public boolean add(E element) { constraint.checkElement(element); return delegate.add(element); } @Override public boolean addAll(Collection<? extends E> elements) { return delegate.addAll(checkElements(elements, constraint)); } } /** * Returns a constrained view of the specified sorted set, using the specified * constraint. Any operations that add new elements to the sorted set will * call the provided constraint. However, this method does not verify that * existing elements satisfy the constraint. * * <p>The returned set is not serializable. * * @param sortedSet the sorted set to constrain * @param constraint the constraint that validates added elements * @return a constrained view of the sorted set */ public static <E> SortedSet<E> constrainedSortedSet( SortedSet<E> sortedSet, Constraint<? super E> constraint) { return new ConstrainedSortedSet<E>(sortedSet, constraint); } /** @see Constraints#constrainedSortedSet */ private static class ConstrainedSortedSet<E> extends ForwardingSortedSet<E> { final SortedSet<E> delegate; final Constraint<? super E> constraint; ConstrainedSortedSet( SortedSet<E> delegate, Constraint<? super E> constraint) { this.delegate = checkNotNull(delegate); this.constraint = checkNotNull(constraint); } @Override protected SortedSet<E> delegate() { return delegate; } @Override public SortedSet<E> headSet(E toElement) { return constrainedSortedSet(delegate.headSet(toElement), constraint); } @Override public SortedSet<E> subSet(E fromElement, E toElement) { return constrainedSortedSet( delegate.subSet(fromElement, toElement), constraint); } @Override public SortedSet<E> tailSet(E fromElement) { return constrainedSortedSet(delegate.tailSet(fromElement), constraint); } @Override public boolean add(E element) { constraint.checkElement(element); return delegate.add(element); } @Override public boolean addAll(Collection<? extends E> elements) { return delegate.addAll(checkElements(elements, constraint)); } } /** * Returns a constrained view of the specified list, using the specified * constraint. Any operations that add new elements to the list will call the * provided constraint. However, this method does not verify that existing * elements satisfy the constraint. * * <p>If {@code list} implements {@link RandomAccess}, so will the returned * list. The returned list is not serializable. * * @param list the list to constrain * @param constraint the constraint that validates added elements * @return a constrained view of the list */ public static <E> List<E> constrainedList( List<E> list, Constraint<? super E> constraint) { return (list instanceof RandomAccess) ? new ConstrainedRandomAccessList<E>(list, constraint) : new ConstrainedList<E>(list, constraint); } /** @see Constraints#constrainedList */ @GwtCompatible private static class ConstrainedList<E> extends ForwardingList<E> { final List<E> delegate; final Constraint<? super E> constraint; ConstrainedList(List<E> delegate, Constraint<? super E> constraint) { this.delegate = checkNotNull(delegate); this.constraint = checkNotNull(constraint); } @Override protected List<E> delegate() { return delegate; } @Override public boolean add(E element) { constraint.checkElement(element); return delegate.add(element); } @Override public void add(int index, E element) { constraint.checkElement(element); delegate.add(index, element); } @Override public boolean addAll(Collection<? extends E> elements) { return delegate.addAll(checkElements(elements, constraint)); } @Override public boolean addAll(int index, Collection<? extends E> elements) { return delegate.addAll(index, checkElements(elements, constraint)); } @Override public ListIterator<E> listIterator() { return constrainedListIterator(delegate.listIterator(), constraint); } @Override public ListIterator<E> listIterator(int index) { return constrainedListIterator(delegate.listIterator(index), constraint); } @Override public E set(int index, E element) { constraint.checkElement(element); return delegate.set(index, element); } @Override public List<E> subList(int fromIndex, int toIndex) { return constrainedList( delegate.subList(fromIndex, toIndex), constraint); } } /** @see Constraints#constrainedList */ static class ConstrainedRandomAccessList<E> extends ConstrainedList<E> implements RandomAccess { ConstrainedRandomAccessList( List<E> delegate, Constraint<? super E> constraint) { super(delegate, constraint); } } /** * Returns a constrained view of the specified list iterator, using the * specified constraint. Any operations that would add new elements to the * underlying list will be verified by the constraint. * * @param listIterator the iterator for which to return a constrained view * @param constraint the constraint for elements in the list * @return a constrained view of the specified iterator */ private static <E> ListIterator<E> constrainedListIterator( ListIterator<E> listIterator, Constraint<? super E> constraint) { return new ConstrainedListIterator<E>(listIterator, constraint); } /** @see Constraints#constrainedListIterator */ static class ConstrainedListIterator<E> extends ForwardingListIterator<E> { private final ListIterator<E> delegate; private final Constraint<? super E> constraint; public ConstrainedListIterator( ListIterator<E> delegate, Constraint<? super E> constraint) { this.delegate = delegate; this.constraint = constraint; } @Override protected ListIterator<E> delegate() { return delegate; } @Override public void add(E element) { constraint.checkElement(element); delegate.add(element); } @Override public void set(E element) { constraint.checkElement(element); delegate.set(element); } } static <E> Collection<E> constrainedTypePreservingCollection( Collection<E> collection, Constraint<E> constraint) { if (collection instanceof SortedSet) { return constrainedSortedSet((SortedSet<E>) collection, constraint); } else if (collection instanceof Set) { return constrainedSet((Set<E>) collection, constraint); } else if (collection instanceof List) { return constrainedList((List<E>) collection, constraint); } else { return constrainedCollection(collection, constraint); } } /** * Returns a constrained view of the specified multiset, using the specified * constraint. Any operations that add new elements to the multiset will call * the provided constraint. However, this method does not verify that * existing elements satisfy the constraint. * * <p>The returned multiset is not serializable. * * @param multiset the multiset to constrain * @param constraint the constraint that validates added elements * @return a constrained view of the multiset */ public static <E> Multiset<E> constrainedMultiset( Multiset<E> multiset, Constraint<? super E> constraint) { return new ConstrainedMultiset<E>(multiset, constraint); } /** @see Constraints#constrainedMultiset */ static class ConstrainedMultiset<E> extends ForwardingMultiset<E> { private Multiset<E> delegate; private final Constraint<? super E> constraint; public ConstrainedMultiset( Multiset<E> delegate, Constraint<? super E> constraint) { this.delegate = checkNotNull(delegate); this.constraint = checkNotNull(constraint); } @Override protected Multiset<E> delegate() { return delegate; } @Override public boolean add(E element) { return standardAdd(element); } @Override public boolean addAll(Collection<? extends E> elements) { return delegate.addAll(checkElements(elements, constraint)); } @Override public int add(E element, int occurrences) { constraint.checkElement(element); return delegate.add(element, occurrences); } @Override public int setCount(E element, int count) { constraint.checkElement(element); return delegate.setCount(element, count); } @Override public boolean setCount(E element, int oldCount, int newCount) { constraint.checkElement(element); return delegate.setCount(element, oldCount, newCount); } } /* * TODO(kevinb): For better performance, avoid making a copy of the elements * by having addAll() call add() repeatedly instead. */ private static <E> Collection<E> checkElements( Collection<E> elements, Constraint<? super E> constraint) { Collection<E> copy = Lists.newArrayList(elements); for (E element : copy) { constraint.checkElement(element); } return copy; } }
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 javax.annotation.Nullable; /** * A descending wrapper around an {@code ImmutableSortedMultiset} * * @author Louis Wasserman */ @SuppressWarnings("serial") // uses writeReplace, not default serialization final class DescendingImmutableSortedMultiset<E> extends ImmutableSortedMultiset<E> { private final transient ImmutableSortedMultiset<E> forward; DescendingImmutableSortedMultiset(ImmutableSortedMultiset<E> forward) { this.forward = forward; } @Override public int count(@Nullable Object element) { return forward.count(element); } @Override public Entry<E> firstEntry() { return forward.lastEntry(); } @Override public Entry<E> lastEntry() { return forward.firstEntry(); } @Override public int size() { return forward.size(); } @Override public ImmutableSortedSet<E> elementSet() { return forward.elementSet().descendingSet(); } @Override Entry<E> getEntry(int index) { return forward.entrySet().asList().reverse().get(index); } @Override public ImmutableSortedMultiset<E> descendingMultiset() { return forward; } @Override public ImmutableSortedMultiset<E> headMultiset(E upperBound, BoundType boundType) { return forward.tailMultiset(upperBound, boundType).descendingMultiset(); } @Override public ImmutableSortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) { return forward.headMultiset(lowerBound, boundType).descendingMultiset(); } @Override boolean isPartialView() { return forward.isPartialView(); } }
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.Set; import javax.annotation.Nullable; /** * A multiset which forwards all its method calls to another multiset. * Subclasses should override one or more methods to modify the behavior of the * backing multiset as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><b>Warning:</b> The methods of {@code ForwardingMultiset} forward * <b>indiscriminately</b> to the methods of the delegate. For example, * overriding {@link #add(Object, int)} alone <b>will not</b> change the * behavior of {@link #add(Object)}, which can lead to unexpected behavior. In * this case, you should override {@code add(Object)} as well, either providing * your own implementation, or delegating to the provided {@code standardAdd} * method. * * <p>The {@code standard} methods and any collection views they return are not * guaranteed to be thread-safe, even when all of the methods that they depend * on are thread-safe. * * @author Kevin Bourrillion * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingMultiset<E> extends ForwardingCollection<E> implements Multiset<E> { /** Constructor for use by subclasses. */ protected ForwardingMultiset() {} @Override protected abstract Multiset<E> delegate(); @Override public int count(Object element) { return delegate().count(element); } @Override public int add(E element, int occurrences) { return delegate().add(element, occurrences); } @Override public int remove(Object element, int occurrences) { return delegate().remove(element, occurrences); } @Override public Set<E> elementSet() { return delegate().elementSet(); } @Override public Set<Entry<E>> entrySet() { return delegate().entrySet(); } @Override public boolean equals(@Nullable Object object) { return object == this || delegate().equals(object); } @Override public int hashCode() { return delegate().hashCode(); } @Override public int setCount(E element, int count) { return delegate().setCount(element, count); } @Override public boolean setCount(E element, int oldCount, int newCount) { return delegate().setCount(element, oldCount, newCount); } /** * A sensible definition of {@link #contains} in terms of {@link #count}. If * you override {@link #count}, you may wish to override {@link #contains} to * forward to this implementation. * * @since 7.0 */ @Override protected boolean standardContains(@Nullable Object object) { return count(object) > 0; } /** * A sensible definition of {@link #clear} in terms of the {@code iterator} * method of {@link #entrySet}. If you override {@link #entrySet}, you may * wish to override {@link #clear} to forward to this implementation. * * @since 7.0 */ @Override protected void standardClear() { Iterators.clear(entrySet().iterator()); } /** * A sensible, albeit inefficient, definition of {@link #count} in terms of * {@link #entrySet}. If you override {@link #entrySet}, you may wish to * override {@link #count} to forward to this implementation. * * @since 7.0 */ @Beta protected int standardCount(@Nullable Object object) { for (Entry<?> entry : this.entrySet()) { if (Objects.equal(entry.getElement(), object)) { return entry.getCount(); } } return 0; } /** * A sensible definition of {@link #add(Object)} in terms of {@link * #add(Object, int)}. If you override {@link #add(Object, int)}, you may * wish to override {@link #add(Object)} to forward to this implementation. * * @since 7.0 */ protected boolean standardAdd(E element) { add(element, 1); return true; } /** * A sensible definition of {@link #addAll(Collection)} in terms of {@link * #add(Object)} and {@link #add(Object, int)}. If you override either of * these methods, you may wish to override {@link #addAll(Collection)} to * forward to this implementation. * * @since 7.0 */ @Beta @Override protected boolean standardAddAll( Collection<? extends E> elementsToAdd) { return Multisets.addAllImpl(this, elementsToAdd); } /** * A sensible definition of {@link #remove(Object)} in terms of {@link * #remove(Object, int)}. If you override {@link #remove(Object, int)}, you * may wish to override {@link #remove(Object)} to forward to this * implementation. * * @since 7.0 */ @Override protected boolean standardRemove(Object element) { return remove(element, 1) > 0; } /** * A sensible definition of {@link #removeAll} in terms of the {@code * removeAll} method of {@link #elementSet}. If you override {@link * #elementSet}, you may wish to override {@link #removeAll} to forward to * this implementation. * * @since 7.0 */ @Override protected boolean standardRemoveAll( Collection<?> elementsToRemove) { return Multisets.removeAllImpl(this, elementsToRemove); } /** * A sensible definition of {@link #retainAll} in terms of the {@code * retainAll} method of {@link #elementSet}. If you override {@link * #elementSet}, you may wish to override {@link #retainAll} to forward to * this implementation. * * @since 7.0 */ @Override protected boolean standardRetainAll( Collection<?> elementsToRetain) { return Multisets.retainAllImpl(this, elementsToRetain); } /** * A sensible definition of {@link #setCount(Object, int)} in terms of {@link * #count(Object)}, {@link #add(Object, int)}, and {@link #remove(Object, * int)}. {@link #entrySet()}. If you override any of these methods, you may * wish to override {@link #setCount(Object, int)} to forward to this * implementation. * * @since 7.0 */ protected int standardSetCount(E element, int count) { return Multisets.setCountImpl(this, element, count); } /** * A sensible definition of {@link #setCount(Object, int, int)} in terms of * {@link #count(Object)} and {@link #setCount(Object, int)}. If you override * either of these methods, you may wish to override {@link #setCount(Object, * int, int)} to forward to this implementation. * * @since 7.0 */ protected boolean standardSetCount(E element, int oldCount, int newCount) { return Multisets.setCountImpl(this, element, oldCount, newCount); } /** * A sensible implementation of {@link Multiset#elementSet} in terms of the * following methods: {@link ForwardingMultiset#clear}, {@link * ForwardingMultiset#contains}, {@link ForwardingMultiset#containsAll}, * {@link ForwardingMultiset#count}, {@link ForwardingMultiset#isEmpty}, the * {@link Set#size} and {@link Set#iterator} methods of {@link * ForwardingMultiset#entrySet}, and {@link ForwardingMultiset#remove(Object, * int)}. In many situations, you may wish to override {@link * ForwardingMultiset#elementSet} to forward to this implementation or a * subclass thereof. * * @since 10.0 */ @Beta protected class StandardElementSet extends Multisets.ElementSet<E> { /** Constructor for use by subclasses. */ public StandardElementSet() {} @Override Multiset<E> multiset() { return ForwardingMultiset.this; } } /** * A sensible definition of {@link #iterator} in terms of {@link #entrySet} * and {@link #remove(Object)}. If you override either of these methods, you * may wish to override {@link #iterator} to forward to this implementation. * * @since 7.0 */ protected Iterator<E> standardIterator() { return Multisets.iteratorImpl(this); } /** * A sensible, albeit inefficient, definition of {@link #size} in terms of * {@link #entrySet}. If you override {@link #entrySet}, you may wish to * override {@link #size} to forward to this implementation. * * @since 7.0 */ protected int standardSize() { return Multisets.sizeImpl(this); } /** * A sensible, albeit inefficient, definition of {@link #size} in terms of * {@code entrySet().size()} and {@link #count}. If you override either of * these methods, you may wish to override {@link #size} to forward to this * implementation. * * @since 7.0 */ protected boolean standardEquals(@Nullable Object object) { return Multisets.equalsImpl(this, object); } /** * A sensible definition of {@link #hashCode} as {@code entrySet().hashCode()} * . If you override {@link #entrySet}, you may wish to override {@link * #hashCode} to forward to this implementation. * * @since 7.0 */ protected int standardHashCode() { return entrySet().hashCode(); } /** * A sensible definition of {@link #toString} as {@code entrySet().toString()} * . If you override {@link #entrySet}, you may wish to override {@link * #toString} to forward to this implementation. * * @since 7.0 */ @Override protected String standardToString() { 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 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.annotations.GwtIncompatible; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Supplier; import com.google.common.collect.Maps.EntryTransformer; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.AbstractCollection; 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.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedSet; import javax.annotation.Nullable; /** * Provides static methods acting on or generating a {@code Multimap}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Multimaps"> * {@code Multimaps}</a>. * * @author Jared Levy * @author Robert Konigsberg * @author Mike Bostock * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class Multimaps { private Multimaps() {} /** * Creates a new {@code Multimap} backed by {@code map}, whose internal value * collections are generated by {@code factory}. * * <b>Warning: do not use</b> this method when the collections returned by * {@code factory} implement either {@link List} or {@code Set}! Use the more * specific method {@link #newListMultimap}, {@link #newSetMultimap} or {@link * #newSortedSetMultimap} instead, to avoid very surprising behavior from * {@link Multimap#equals}. * * <p>The {@code factory}-generated and {@code map} classes determine the * multimap iteration order. They also specify the behavior of the * {@code equals}, {@code hashCode}, and {@code toString} methods for the * multimap and its returned views. However, the multimap's {@code get} * method returns instances of a different class than {@code factory.get()} * does. * * <p>The multimap is serializable if {@code map}, {@code factory}, the * collections generated by {@code factory}, and the multimap contents are all * serializable. * * <p>The multimap is not threadsafe when any concurrent operations update the * multimap, even if {@code map} and the instances generated by * {@code factory} are. Concurrent read operations will work correctly. To * allow concurrent update operations, wrap the multimap with a call to * {@link #synchronizedMultimap}. * * <p>Call this method only when the simpler methods * {@link ArrayListMultimap#create()}, {@link HashMultimap#create()}, * {@link LinkedHashMultimap#create()}, {@link LinkedListMultimap#create()}, * {@link TreeMultimap#create()}, and * {@link TreeMultimap#create(Comparator, Comparator)} won't suffice. * * <p>Note: the multimap assumes complete ownership over of {@code map} and * the collections returned by {@code factory}. Those objects should not be * manually updated and they should not use soft, weak, or phantom references. * * @param map place to store the mapping from each key to its corresponding * values * @param factory supplier of new, empty collections that will each hold all * values for a given key * @throws IllegalArgumentException if {@code map} is not empty */ public static <K, V> Multimap<K, V> newMultimap(Map<K, Collection<V>> map, final Supplier<? extends Collection<V>> factory) { return new CustomMultimap<K, V>(map, factory); } private static class CustomMultimap<K, V> extends AbstractMapBasedMultimap<K, V> { transient Supplier<? extends Collection<V>> factory; CustomMultimap(Map<K, Collection<V>> map, Supplier<? extends Collection<V>> factory) { super(map); this.factory = checkNotNull(factory); } @Override protected Collection<V> createCollection() { return factory.get(); } // can't use Serialization writeMultimap and populateMultimap methods since // there's no way to generate the empty backing map. /** @serialData the factory and the backing map */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(factory); stream.writeObject(backingMap()); } @GwtIncompatible("java.io.ObjectInputStream") @SuppressWarnings("unchecked") // reading data stored by writeObject private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); factory = (Supplier<? extends Collection<V>>) stream.readObject(); Map<K, Collection<V>> map = (Map<K, Collection<V>>) stream.readObject(); setMap(map); } @GwtIncompatible("java serialization not supported") private static final long serialVersionUID = 0; } /** * Creates a new {@code ListMultimap} that uses the provided map and factory. * It can generate a multimap based on arbitrary {@link Map} and {@link List} * classes. * * <p>The {@code factory}-generated and {@code map} classes determine the * multimap iteration order. They also specify the behavior of the * {@code equals}, {@code hashCode}, and {@code toString} methods for the * multimap and its returned views. The multimap's {@code get}, {@code * removeAll}, and {@code replaceValues} methods return {@code RandomAccess} * lists if the factory does. However, the multimap's {@code get} method * returns instances of a different class than does {@code factory.get()}. * * <p>The multimap is serializable if {@code map}, {@code factory}, the * lists generated by {@code factory}, and the multimap contents are all * serializable. * * <p>The multimap is not threadsafe when any concurrent operations update the * multimap, even if {@code map} and the instances generated by * {@code factory} are. Concurrent read operations will work correctly. To * allow concurrent update operations, wrap the multimap with a call to * {@link #synchronizedListMultimap}. * * <p>Call this method only when the simpler methods * {@link ArrayListMultimap#create()} and {@link LinkedListMultimap#create()} * won't suffice. * * <p>Note: the multimap assumes complete ownership over of {@code map} and * the lists returned by {@code factory}. Those objects should not be manually * updated, they should be empty when provided, and they should not use soft, * weak, or phantom references. * * @param map place to store the mapping from each key to its corresponding * values * @param factory supplier of new, empty lists that will each hold all values * for a given key * @throws IllegalArgumentException if {@code map} is not empty */ public static <K, V> ListMultimap<K, V> newListMultimap( Map<K, Collection<V>> map, final Supplier<? extends List<V>> factory) { return new CustomListMultimap<K, V>(map, factory); } private static class CustomListMultimap<K, V> extends AbstractListMultimap<K, V> { transient Supplier<? extends List<V>> factory; CustomListMultimap(Map<K, Collection<V>> map, Supplier<? extends List<V>> factory) { super(map); this.factory = checkNotNull(factory); } @Override protected List<V> createCollection() { return factory.get(); } /** @serialData the factory and the backing map */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(factory); stream.writeObject(backingMap()); } @GwtIncompatible("java.io.ObjectInputStream") @SuppressWarnings("unchecked") // reading data stored by writeObject private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); factory = (Supplier<? extends List<V>>) stream.readObject(); Map<K, Collection<V>> map = (Map<K, Collection<V>>) stream.readObject(); setMap(map); } @GwtIncompatible("java serialization not supported") private static final long serialVersionUID = 0; } /** * Creates a new {@code SetMultimap} that uses the provided map and factory. * It can generate a multimap based on arbitrary {@link Map} and {@link Set} * classes. * * <p>The {@code factory}-generated and {@code map} classes determine the * multimap iteration order. They also specify the behavior of the * {@code equals}, {@code hashCode}, and {@code toString} methods for the * multimap and its returned views. However, the multimap's {@code get} * method returns instances of a different class than {@code factory.get()} * does. * * <p>The multimap is serializable if {@code map}, {@code factory}, the * sets generated by {@code factory}, and the multimap contents are all * serializable. * * <p>The multimap is not threadsafe when any concurrent operations update the * multimap, even if {@code map} and the instances generated by * {@code factory} are. Concurrent read operations will work correctly. To * allow concurrent update operations, wrap the multimap with a call to * {@link #synchronizedSetMultimap}. * * <p>Call this method only when the simpler methods * {@link HashMultimap#create()}, {@link LinkedHashMultimap#create()}, * {@link TreeMultimap#create()}, and * {@link TreeMultimap#create(Comparator, Comparator)} won't suffice. * * <p>Note: the multimap assumes complete ownership over of {@code map} and * the sets returned by {@code factory}. Those objects should not be manually * updated and they should not use soft, weak, or phantom references. * * @param map place to store the mapping from each key to its corresponding * values * @param factory supplier of new, empty sets that will each hold all values * for a given key * @throws IllegalArgumentException if {@code map} is not empty */ public static <K, V> SetMultimap<K, V> newSetMultimap( Map<K, Collection<V>> map, final Supplier<? extends Set<V>> factory) { return new CustomSetMultimap<K, V>(map, factory); } private static class CustomSetMultimap<K, V> extends AbstractSetMultimap<K, V> { transient Supplier<? extends Set<V>> factory; CustomSetMultimap(Map<K, Collection<V>> map, Supplier<? extends Set<V>> factory) { super(map); this.factory = checkNotNull(factory); } @Override protected Set<V> createCollection() { return factory.get(); } /** @serialData the factory and the backing map */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(factory); stream.writeObject(backingMap()); } @GwtIncompatible("java.io.ObjectInputStream") @SuppressWarnings("unchecked") // reading data stored by writeObject private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); factory = (Supplier<? extends Set<V>>) stream.readObject(); Map<K, Collection<V>> map = (Map<K, Collection<V>>) stream.readObject(); setMap(map); } @GwtIncompatible("not needed in emulated source") private static final long serialVersionUID = 0; } /** * Creates a new {@code SortedSetMultimap} that uses the provided map and * factory. It can generate a multimap based on arbitrary {@link Map} and * {@link SortedSet} classes. * * <p>The {@code factory}-generated and {@code map} classes determine the * multimap iteration order. They also specify the behavior of the * {@code equals}, {@code hashCode}, and {@code toString} methods for the * multimap and its returned views. However, the multimap's {@code get} * method returns instances of a different class than {@code factory.get()} * does. * * <p>The multimap is serializable if {@code map}, {@code factory}, the * sets generated by {@code factory}, and the multimap contents are all * serializable. * * <p>The multimap is not threadsafe when any concurrent operations update the * multimap, even if {@code map} and the instances generated by * {@code factory} are. Concurrent read operations will work correctly. To * allow concurrent update operations, wrap the multimap with a call to * {@link #synchronizedSortedSetMultimap}. * * <p>Call this method only when the simpler methods * {@link TreeMultimap#create()} and * {@link TreeMultimap#create(Comparator, Comparator)} won't suffice. * * <p>Note: the multimap assumes complete ownership over of {@code map} and * the sets returned by {@code factory}. Those objects should not be manually * updated and they should not use soft, weak, or phantom references. * * @param map place to store the mapping from each key to its corresponding * values * @param factory supplier of new, empty sorted sets that will each hold * all values for a given key * @throws IllegalArgumentException if {@code map} is not empty */ public static <K, V> SortedSetMultimap<K, V> newSortedSetMultimap( Map<K, Collection<V>> map, final Supplier<? extends SortedSet<V>> factory) { return new CustomSortedSetMultimap<K, V>(map, factory); } private static class CustomSortedSetMultimap<K, V> extends AbstractSortedSetMultimap<K, V> { transient Supplier<? extends SortedSet<V>> factory; transient Comparator<? super V> valueComparator; CustomSortedSetMultimap(Map<K, Collection<V>> map, Supplier<? extends SortedSet<V>> factory) { super(map); this.factory = checkNotNull(factory); valueComparator = factory.get().comparator(); } @Override protected SortedSet<V> createCollection() { return factory.get(); } @Override public Comparator<? super V> valueComparator() { return valueComparator; } /** @serialData the factory and the backing map */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(factory); stream.writeObject(backingMap()); } @GwtIncompatible("java.io.ObjectInputStream") @SuppressWarnings("unchecked") // reading data stored by writeObject private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); factory = (Supplier<? extends SortedSet<V>>) stream.readObject(); valueComparator = factory.get().comparator(); Map<K, Collection<V>> map = (Map<K, Collection<V>>) stream.readObject(); setMap(map); } @GwtIncompatible("not needed in emulated source") private static final long serialVersionUID = 0; } /** * Copies each key-value mapping in {@code source} into {@code dest}, with * its key and value reversed. * * <p>If {@code source} is an {@link ImmutableMultimap}, consider using * {@link ImmutableMultimap#inverse} instead. * * @param source any multimap * @param dest the multimap to copy into; usually empty * @return {@code dest} */ public static <K, V, M extends Multimap<K, V>> M invertFrom( Multimap<? extends V, ? extends K> source, M dest) { checkNotNull(dest); for (Map.Entry<? extends V, ? extends K> entry : source.entries()) { dest.put(entry.getValue(), entry.getKey()); } return dest; } /** * Returns a synchronized (thread-safe) multimap backed by the specified * multimap. In order to guarantee serial access, it is critical that * <b>all</b> access to the backing multimap is accomplished through the * returned multimap. * * <p>It is imperative that the user manually synchronize on the returned * multimap when accessing any of its collection views: <pre> {@code * * Multimap<K, V> multimap = Multimaps.synchronizedMultimap( * HashMultimap.<K, V>create()); * ... * Collection<V> values = multimap.get(key); // Needn't be in synchronized block * ... * synchronized (multimap) { // Synchronizing on multimap, not values! * Iterator<V> i = values.iterator(); // Must be in synchronized block * while (i.hasNext()) { * foo(i.next()); * } * }}</pre> * * <p>Failure to follow this advice may result in non-deterministic behavior. * * <p>Note that the generated multimap's {@link Multimap#removeAll} and * {@link Multimap#replaceValues} methods return collections that aren't * synchronized. * * <p>The returned multimap will be serializable if the specified multimap is * serializable. * * @param multimap the multimap to be wrapped in a synchronized view * @return a synchronized view of the specified multimap */ public static <K, V> Multimap<K, V> synchronizedMultimap( Multimap<K, V> multimap) { return Synchronized.multimap(multimap, null); } /** * Returns an unmodifiable view of the specified multimap. Query operations on * the returned multimap "read through" to the specified multimap, and * attempts to modify the returned multimap, either directly or through the * multimap's views, result in an {@code UnsupportedOperationException}. * * <p>Note that the generated multimap's {@link Multimap#removeAll} and * {@link Multimap#replaceValues} methods return collections that are * modifiable. * * <p>The returned multimap will be serializable if the specified multimap is * serializable. * * @param delegate the multimap for which an unmodifiable view is to be * returned * @return an unmodifiable view of the specified multimap */ public static <K, V> Multimap<K, V> unmodifiableMultimap( Multimap<K, V> delegate) { if (delegate instanceof UnmodifiableMultimap || delegate instanceof ImmutableMultimap) { return delegate; } return new UnmodifiableMultimap<K, V>(delegate); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <K, V> Multimap<K, V> unmodifiableMultimap( ImmutableMultimap<K, V> delegate) { return checkNotNull(delegate); } private static class UnmodifiableMultimap<K, V> extends ForwardingMultimap<K, V> implements Serializable { final Multimap<K, V> delegate; transient Collection<Entry<K, V>> entries; transient Multiset<K> keys; transient Set<K> keySet; transient Collection<V> values; transient Map<K, Collection<V>> map; UnmodifiableMultimap(final Multimap<K, V> delegate) { this.delegate = checkNotNull(delegate); } @Override protected Multimap<K, V> delegate() { return delegate; } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Map<K, Collection<V>> asMap() { Map<K, Collection<V>> result = map; if (result == null) { result = map = Collections.unmodifiableMap( Maps.transformValues(delegate.asMap(), new Function<Collection<V>, Collection<V>>() { @Override public Collection<V> apply(Collection<V> collection) { return unmodifiableValueCollection(collection); } })); } return result; } @Override public Collection<Entry<K, V>> entries() { Collection<Entry<K, V>> result = entries; if (result == null) { entries = result = unmodifiableEntries(delegate.entries()); } return result; } @Override public Collection<V> get(K key) { return unmodifiableValueCollection(delegate.get(key)); } @Override public Multiset<K> keys() { Multiset<K> result = keys; if (result == null) { keys = result = Multisets.unmodifiableMultiset(delegate.keys()); } return result; } @Override public Set<K> keySet() { Set<K> result = keySet; if (result == null) { keySet = result = Collections.unmodifiableSet(delegate.keySet()); } return result; } @Override public boolean put(K key, V value) { throw new UnsupportedOperationException(); } @Override public boolean putAll(K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object key, Object value) { throw new UnsupportedOperationException(); } @Override public Collection<V> removeAll(Object key) { throw new UnsupportedOperationException(); } @Override public Collection<V> replaceValues( K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } @Override public Collection<V> values() { Collection<V> result = values; if (result == null) { values = result = Collections.unmodifiableCollection(delegate.values()); } return result; } private static final long serialVersionUID = 0; } private static class UnmodifiableListMultimap<K, V> extends UnmodifiableMultimap<K, V> implements ListMultimap<K, V> { UnmodifiableListMultimap(ListMultimap<K, V> delegate) { super(delegate); } @Override public ListMultimap<K, V> delegate() { return (ListMultimap<K, V>) super.delegate(); } @Override public List<V> get(K key) { return Collections.unmodifiableList(delegate().get(key)); } @Override public List<V> removeAll(Object key) { throw new UnsupportedOperationException(); } @Override public List<V> replaceValues( K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } private static final long serialVersionUID = 0; } private static class UnmodifiableSetMultimap<K, V> extends UnmodifiableMultimap<K, V> implements SetMultimap<K, V> { UnmodifiableSetMultimap(SetMultimap<K, V> delegate) { super(delegate); } @Override public SetMultimap<K, V> delegate() { return (SetMultimap<K, V>) super.delegate(); } @Override public Set<V> get(K key) { /* * Note that this doesn't return a SortedSet when delegate is a * SortedSetMultiset, unlike (SortedSet<V>) super.get(). */ return Collections.unmodifiableSet(delegate().get(key)); } @Override public Set<Map.Entry<K, V>> entries() { return Maps.unmodifiableEntrySet(delegate().entries()); } @Override public Set<V> removeAll(Object key) { throw new UnsupportedOperationException(); } @Override public Set<V> replaceValues( K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } private static final long serialVersionUID = 0; } private static class UnmodifiableSortedSetMultimap<K, V> extends UnmodifiableSetMultimap<K, V> implements SortedSetMultimap<K, V> { UnmodifiableSortedSetMultimap(SortedSetMultimap<K, V> delegate) { super(delegate); } @Override public SortedSetMultimap<K, V> delegate() { return (SortedSetMultimap<K, V>) super.delegate(); } @Override public SortedSet<V> get(K key) { return Collections.unmodifiableSortedSet(delegate().get(key)); } @Override public SortedSet<V> removeAll(Object key) { throw new UnsupportedOperationException(); } @Override public SortedSet<V> replaceValues( K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } @Override public Comparator<? super V> valueComparator() { return delegate().valueComparator(); } private static final long serialVersionUID = 0; } /** * Returns a synchronized (thread-safe) {@code SetMultimap} backed by the * specified multimap. * * <p>You must follow the warnings described in {@link #synchronizedMultimap}. * * <p>The returned multimap will be serializable if the specified multimap is * serializable. * * @param multimap the multimap to be wrapped * @return a synchronized view of the specified multimap */ public static <K, V> SetMultimap<K, V> synchronizedSetMultimap( SetMultimap<K, V> multimap) { return Synchronized.setMultimap(multimap, null); } /** * Returns an unmodifiable view of the specified {@code SetMultimap}. Query * operations on the returned multimap "read through" to the specified * multimap, and attempts to modify the returned multimap, either directly or * through the multimap's views, result in an * {@code UnsupportedOperationException}. * * <p>Note that the generated multimap's {@link Multimap#removeAll} and * {@link Multimap#replaceValues} methods return collections that are * modifiable. * * <p>The returned multimap will be serializable if the specified multimap is * serializable. * * @param delegate the multimap for which an unmodifiable view is to be * returned * @return an unmodifiable view of the specified multimap */ public static <K, V> SetMultimap<K, V> unmodifiableSetMultimap( SetMultimap<K, V> delegate) { if (delegate instanceof UnmodifiableSetMultimap || delegate instanceof ImmutableSetMultimap) { return delegate; } return new UnmodifiableSetMultimap<K, V>(delegate); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <K, V> SetMultimap<K, V> unmodifiableSetMultimap( ImmutableSetMultimap<K, V> delegate) { return checkNotNull(delegate); } /** * Returns a synchronized (thread-safe) {@code SortedSetMultimap} backed by * the specified multimap. * * <p>You must follow the warnings described in {@link #synchronizedMultimap}. * * <p>The returned multimap will be serializable if the specified multimap is * serializable. * * @param multimap the multimap to be wrapped * @return a synchronized view of the specified multimap */ public static <K, V> SortedSetMultimap<K, V> synchronizedSortedSetMultimap(SortedSetMultimap<K, V> multimap) { return Synchronized.sortedSetMultimap(multimap, null); } /** * Returns an unmodifiable view of the specified {@code SortedSetMultimap}. * Query operations on the returned multimap "read through" to the specified * multimap, and attempts to modify the returned multimap, either directly or * through the multimap's views, result in an * {@code UnsupportedOperationException}. * * <p>Note that the generated multimap's {@link Multimap#removeAll} and * {@link Multimap#replaceValues} methods return collections that are * modifiable. * * <p>The returned multimap will be serializable if the specified multimap is * serializable. * * @param delegate the multimap for which an unmodifiable view is to be * returned * @return an unmodifiable view of the specified multimap */ public static <K, V> SortedSetMultimap<K, V> unmodifiableSortedSetMultimap( SortedSetMultimap<K, V> delegate) { if (delegate instanceof UnmodifiableSortedSetMultimap) { return delegate; } return new UnmodifiableSortedSetMultimap<K, V>(delegate); } /** * Returns a synchronized (thread-safe) {@code ListMultimap} backed by the * specified multimap. * * <p>You must follow the warnings described in {@link #synchronizedMultimap}. * * @param multimap the multimap to be wrapped * @return a synchronized view of the specified multimap */ public static <K, V> ListMultimap<K, V> synchronizedListMultimap( ListMultimap<K, V> multimap) { return Synchronized.listMultimap(multimap, null); } /** * Returns an unmodifiable view of the specified {@code ListMultimap}. Query * operations on the returned multimap "read through" to the specified * multimap, and attempts to modify the returned multimap, either directly or * through the multimap's views, result in an * {@code UnsupportedOperationException}. * * <p>Note that the generated multimap's {@link Multimap#removeAll} and * {@link Multimap#replaceValues} methods return collections that are * modifiable. * * <p>The returned multimap will be serializable if the specified multimap is * serializable. * * @param delegate the multimap for which an unmodifiable view is to be * returned * @return an unmodifiable view of the specified multimap */ public static <K, V> ListMultimap<K, V> unmodifiableListMultimap( ListMultimap<K, V> delegate) { if (delegate instanceof UnmodifiableListMultimap || delegate instanceof ImmutableListMultimap) { return delegate; } return new UnmodifiableListMultimap<K, V>(delegate); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <K, V> ListMultimap<K, V> unmodifiableListMultimap( ImmutableListMultimap<K, V> delegate) { return checkNotNull(delegate); } /** * Returns an unmodifiable view of the specified collection, preserving the * interface for instances of {@code SortedSet}, {@code Set}, {@code List} and * {@code Collection}, in that order of preference. * * @param collection the collection for which to return an unmodifiable view * @return an unmodifiable view of the collection */ private static <V> Collection<V> unmodifiableValueCollection( 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); } return Collections.unmodifiableCollection(collection); } /** * Returns an unmodifiable view of the specified collection of entries. The * {@link Entry#setValue} operation throws an {@link * UnsupportedOperationException}. If the specified collection is a {@code * Set}, the returned collection is also a {@code Set}. * * @param entries the entries for which to return an unmodifiable view * @return an unmodifiable view of the entries */ private static <K, V> Collection<Entry<K, V>> unmodifiableEntries( Collection<Entry<K, V>> entries) { if (entries instanceof Set) { return Maps.unmodifiableEntrySet((Set<Entry<K, V>>) entries); } return new Maps.UnmodifiableEntries<K, V>( Collections.unmodifiableCollection(entries)); } /** * Returns {@link ListMultimap#asMap multimap.asMap()}, with its type * corrected from {@code Map<K, Collection<V>>} to {@code Map<K, List<V>>}. * * @since 15.0 */ @Beta @SuppressWarnings("unchecked") // safe by specification of ListMultimap.asMap() public static <K, V> Map<K, List<V>> asMap(ListMultimap<K, V> multimap) { return (Map<K, List<V>>) (Map<K, ?>) multimap.asMap(); } /** * Returns {@link SetMultimap#asMap multimap.asMap()}, with its type corrected * from {@code Map<K, Collection<V>>} to {@code Map<K, Set<V>>}. * * @since 15.0 */ @Beta @SuppressWarnings("unchecked") // safe by specification of SetMultimap.asMap() public static <K, V> Map<K, Set<V>> asMap(SetMultimap<K, V> multimap) { return (Map<K, Set<V>>) (Map<K, ?>) multimap.asMap(); } /** * Returns {@link SortedSetMultimap#asMap multimap.asMap()}, with its type * corrected from {@code Map<K, Collection<V>>} to * {@code Map<K, SortedSet<V>>}. * * @since 15.0 */ @Beta @SuppressWarnings("unchecked") // safe by specification of SortedSetMultimap.asMap() public static <K, V> Map<K, SortedSet<V>> asMap( SortedSetMultimap<K, V> multimap) { return (Map<K, SortedSet<V>>) (Map<K, ?>) multimap.asMap(); } /** * Returns {@link Multimap#asMap multimap.asMap()}. This is provided for * parity with the other more strongly-typed {@code asMap()} implementations. * * @since 15.0 */ @Beta public static <K, V> Map<K, Collection<V>> asMap(Multimap<K, V> multimap) { return multimap.asMap(); } /** * Returns a multimap view of the specified map. The multimap is backed by the * map, so changes to the map are reflected in the multimap, and vice versa. * If the map is modified while an iteration over one of the multimap's * collection views is in progress (except through the iterator's own {@code * remove} operation, or through the {@code setValue} operation on a map entry * returned by the iterator), the results of the iteration are undefined. * * <p>The multimap supports mapping removal, which removes the corresponding * mapping from the map. It does not support any operations which might add * mappings, such as {@code put}, {@code putAll} or {@code replaceValues}. * * <p>The returned multimap will be serializable if the specified map is * serializable. * * @param map the backing map for the returned multimap view */ public static <K, V> SetMultimap<K, V> forMap(Map<K, V> map) { return new MapMultimap<K, V>(map); } /** @see Multimaps#forMap */ private static class MapMultimap<K, V> extends AbstractMultimap<K, V> implements SetMultimap<K, V>, Serializable { final Map<K, V> map; MapMultimap(Map<K, V> map) { this.map = checkNotNull(map); } @Override public int size() { return map.size(); } @Override public boolean containsKey(Object key) { return map.containsKey(key); } @Override public boolean containsValue(Object value) { return map.containsValue(value); } @Override public boolean containsEntry(Object key, Object value) { return map.entrySet().contains(Maps.immutableEntry(key, value)); } @Override public Set<V> get(final K key) { return new Sets.ImprovedAbstractSet<V>() { @Override public Iterator<V> iterator() { return new Iterator<V>() { int i; @Override public boolean hasNext() { return (i == 0) && map.containsKey(key); } @Override public V next() { if (!hasNext()) { throw new NoSuchElementException(); } i++; return map.get(key); } @Override public void remove() { checkState(i == 1); i = -1; map.remove(key); } }; } @Override public int size() { return map.containsKey(key) ? 1 : 0; } }; } @Override public boolean put(K key, V value) { throw new UnsupportedOperationException(); } @Override public boolean putAll(K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { throw new UnsupportedOperationException(); } @Override public Set<V> replaceValues(K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object key, Object value) { return map.entrySet().remove(Maps.immutableEntry(key, value)); } @Override public Set<V> removeAll(Object key) { Set<V> values = new HashSet<V>(2); if (!map.containsKey(key)) { return values; } values.add(map.remove(key)); return values; } @Override public void clear() { map.clear(); } @Override public Set<K> keySet() { return map.keySet(); } @Override public Collection<V> values() { return map.values(); } @Override public Set<Entry<K, V>> entries() { return map.entrySet(); } @Override Iterator<Entry<K, V>> entryIterator() { return map.entrySet().iterator(); } @Override Map<K, Collection<V>> createAsMap() { return new AsMap<K, V>(this); } @Override public int hashCode() { return map.hashCode(); } private static final long serialVersionUID = 7845222491160860175L; } /** * Returns a view of a multimap where each value is transformed by a function. * All other properties of the multimap, such as iteration order, are left * intact. For example, the code: <pre> {@code * * Multimap<String, Integer> multimap = * ImmutableSetMultimap.of("a", 2, "b", -3, "b", -3, "a", 4, "c", 6); * Function<Integer, String> square = new Function<Integer, String>() { * public String apply(Integer in) { * return Integer.toString(in * in); * } * }; * Multimap<String, String> transformed = * Multimaps.transformValues(multimap, square); * System.out.println(transformed);}</pre> * * ... prints {@code {a=[4, 16], b=[9, 9], c=[36]}}. * * <p>Changes in the underlying multimap are reflected in this view. * Conversely, this view supports removal operations, and these are reflected * in the underlying multimap. * * <p>It's acceptable for the underlying multimap to contain null keys, and * even null values provided that the function is capable of accepting null * input. The transformed multimap might contain null values, if the function * sometimes gives a null result. * * <p>The returned multimap is not thread-safe or serializable, even if the * underlying multimap is. The {@code equals} and {@code hashCode} methods * of the returned multimap are meaningless, since there is not a definition * of {@code equals} or {@code hashCode} for general collections, and * {@code get()} will return a general {@code Collection} as opposed to a * {@code List} or a {@code Set}. * * <p>The function is applied lazily, invoked when needed. This is necessary * for the returned multimap to be a view, but it means that the function will * be applied many times for bulk operations like * {@link Multimap#containsValue} and {@code Multimap.toString()}. For this to * perform well, {@code function} should be fast. To avoid lazy evaluation * when the returned multimap doesn't need to be a view, copy the returned * multimap into a new multimap of your choosing. * * @since 7.0 */ public static <K, V1, V2> Multimap<K, V2> transformValues( Multimap<K, V1> fromMultimap, final Function<? super V1, V2> function) { checkNotNull(function); EntryTransformer<K, V1, V2> transformer = Maps.asEntryTransformer(function); return transformEntries(fromMultimap, transformer); } /** * Returns a view of a multimap whose values are derived from the original * multimap'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 multimap, such as iteration * order, are left intact. For example, the code: <pre> {@code * * SetMultimap<String, Integer> multimap = * ImmutableSetMultimap.of("a", 1, "a", 4, "b", -6); * EntryTransformer<String, Integer, String> transformer = * new EntryTransformer<String, Integer, String>() { * public String transformEntry(String key, Integer value) { * return (value >= 0) ? key : "no" + key; * } * }; * Multimap<String, String> transformed = * Multimaps.transformEntries(multimap, transformer); * System.out.println(transformed);}</pre> * * ... prints {@code {a=[a, a], b=[nob]}}. * * <p>Changes in the underlying multimap are reflected in this view. * Conversely, this view supports removal operations, and these are reflected * in the underlying multimap. * * <p>It's acceptable for the underlying multimap to contain null keys and * null values provided that the transformer is capable of accepting null * inputs. The transformed multimap might contain null values if the * transformer sometimes gives a null result. * * <p>The returned multimap is not thread-safe or serializable, even if the * underlying multimap is. The {@code equals} and {@code hashCode} methods * of the returned multimap are meaningless, since there is not a definition * of {@code equals} or {@code hashCode} for general collections, and * {@code get()} will return a general {@code Collection} as opposed to a * {@code List} or a {@code Set}. * * <p>The transformer is applied lazily, invoked when needed. This is * necessary for the returned multimap to be a view, but it means that the * transformer will be applied many times for bulk operations like {@link * Multimap#containsValue} and {@link Object#toString}. For this to perform * well, {@code transformer} should be fast. To avoid lazy evaluation when the * returned multimap doesn't need to be a view, copy the returned multimap * into a new multimap 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 multimap. * * @since 7.0 */ public static <K, V1, V2> Multimap<K, V2> transformEntries( Multimap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { return new TransformedEntriesMultimap<K, V1, V2>(fromMap, transformer); } private static class TransformedEntriesMultimap<K, V1, V2> extends AbstractMultimap<K, V2> { final Multimap<K, V1> fromMultimap; final EntryTransformer<? super K, ? super V1, V2> transformer; TransformedEntriesMultimap(Multimap<K, V1> fromMultimap, final EntryTransformer<? super K, ? super V1, V2> transformer) { this.fromMultimap = checkNotNull(fromMultimap); this.transformer = checkNotNull(transformer); } Collection<V2> transform(K key, Collection<V1> values) { Function<? super V1, V2> function = Maps.asValueToValueFunction(transformer, key); if (values instanceof List) { return Lists.transform((List<V1>) values, function); } else { return Collections2.transform(values, function); } } @Override Map<K, Collection<V2>> createAsMap() { return Maps.transformEntries(fromMultimap.asMap(), new EntryTransformer<K, Collection<V1>, Collection<V2>>() { @Override public Collection<V2> transformEntry( K key, Collection<V1> value) { return transform(key, value); } }); } @Override public void clear() { fromMultimap.clear(); } @Override public boolean containsKey(Object key) { return fromMultimap.containsKey(key); } @Override Iterator<Entry<K, V2>> entryIterator() { return Iterators.transform(fromMultimap.entries().iterator(), Maps.<K, V1, V2>asEntryToEntryFunction(transformer)); } @Override public Collection<V2> get(final K key) { return transform(key, fromMultimap.get(key)); } @Override public boolean isEmpty() { return fromMultimap.isEmpty(); } @Override public Set<K> keySet() { return fromMultimap.keySet(); } @Override public Multiset<K> keys() { return fromMultimap.keys(); } @Override public boolean put(K key, V2 value) { throw new UnsupportedOperationException(); } @Override public boolean putAll(K key, Iterable<? extends V2> values) { throw new UnsupportedOperationException(); } @Override public boolean putAll( Multimap<? extends K, ? extends V2> multimap) { throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") @Override public boolean remove(Object key, Object value) { return get((K) key).remove(value); } @SuppressWarnings("unchecked") @Override public Collection<V2> removeAll(Object key) { return transform((K) key, fromMultimap.removeAll(key)); } @Override public Collection<V2> replaceValues( K key, Iterable<? extends V2> values) { throw new UnsupportedOperationException(); } @Override public int size() { return fromMultimap.size(); } @Override Collection<V2> createValues() { return Collections2.transform( fromMultimap.entries(), Maps.<K, V1, V2>asEntryToValueFunction(transformer)); } } /** * Returns a view of a {@code ListMultimap} where each value is transformed by * a function. All other properties of the multimap, such as iteration order, * are left intact. For example, the code: <pre> {@code * * ListMultimap<String, Integer> multimap * = ImmutableListMultimap.of("a", 4, "a", 16, "b", 9); * Function<Integer, Double> sqrt = * new Function<Integer, Double>() { * public Double apply(Integer in) { * return Math.sqrt((int) in); * } * }; * ListMultimap<String, Double> transformed = Multimaps.transformValues(map, * sqrt); * System.out.println(transformed);}</pre> * * ... prints {@code {a=[2.0, 4.0], b=[3.0]}}. * * <p>Changes in the underlying multimap are reflected in this view. * Conversely, this view supports removal operations, and these are reflected * in the underlying multimap. * * <p>It's acceptable for the underlying multimap to contain null keys, and * even null values provided that the function is capable of accepting null * input. The transformed multimap might contain null values, if the function * sometimes gives a null result. * * <p>The returned multimap is not thread-safe or serializable, even if the * underlying multimap is. * * <p>The function is applied lazily, invoked when needed. This is necessary * for the returned multimap to be a view, but it means that the function will * be applied many times for bulk operations like * {@link Multimap#containsValue} and {@code Multimap.toString()}. For this to * perform well, {@code function} should be fast. To avoid lazy evaluation * when the returned multimap doesn't need to be a view, copy the returned * multimap into a new multimap of your choosing. * * @since 7.0 */ public static <K, V1, V2> ListMultimap<K, V2> transformValues( ListMultimap<K, V1> fromMultimap, final Function<? super V1, V2> function) { checkNotNull(function); EntryTransformer<K, V1, V2> transformer = Maps.asEntryTransformer(function); return transformEntries(fromMultimap, transformer); } /** * Returns a view of a {@code ListMultimap} whose values are derived from the * original multimap's entries. In contrast to * {@link #transformValues(ListMultimap, Function)}, this method's * entry-transformation logic may depend on the key as well as the value. * * <p>All other properties of the transformed multimap, such as iteration * order, are left intact. For example, the code: <pre> {@code * * Multimap<String, Integer> multimap = * ImmutableMultimap.of("a", 1, "a", 4, "b", 6); * EntryTransformer<String, Integer, String> transformer = * new EntryTransformer<String, Integer, String>() { * public String transformEntry(String key, Integer value) { * return key + value; * } * }; * Multimap<String, String> transformed = * Multimaps.transformEntries(multimap, transformer); * System.out.println(transformed);}</pre> * * ... prints {@code {"a"=["a1", "a4"], "b"=["b6"]}}. * * <p>Changes in the underlying multimap are reflected in this view. * Conversely, this view supports removal operations, and these are reflected * in the underlying multimap. * * <p>It's acceptable for the underlying multimap to contain null keys and * null values provided that the transformer is capable of accepting null * inputs. The transformed multimap might contain null values if the * transformer sometimes gives a null result. * * <p>The returned multimap is not thread-safe or serializable, even if the * underlying multimap is. * * <p>The transformer is applied lazily, invoked when needed. This is * necessary for the returned multimap to be a view, but it means that the * transformer will be applied many times for bulk operations like {@link * Multimap#containsValue} and {@link Object#toString}. For this to perform * well, {@code transformer} should be fast. To avoid lazy evaluation when the * returned multimap doesn't need to be a view, copy the returned multimap * into a new multimap 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 multimap. * * @since 7.0 */ public static <K, V1, V2> ListMultimap<K, V2> transformEntries( ListMultimap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { return new TransformedEntriesListMultimap<K, V1, V2>(fromMap, transformer); } private static final class TransformedEntriesListMultimap<K, V1, V2> extends TransformedEntriesMultimap<K, V1, V2> implements ListMultimap<K, V2> { TransformedEntriesListMultimap(ListMultimap<K, V1> fromMultimap, EntryTransformer<? super K, ? super V1, V2> transformer) { super(fromMultimap, transformer); } @Override List<V2> transform(K key, Collection<V1> values) { return Lists.transform((List<V1>) values, Maps.asValueToValueFunction(transformer, key)); } @Override public List<V2> get(K key) { return transform(key, fromMultimap.get(key)); } @SuppressWarnings("unchecked") @Override public List<V2> removeAll(Object key) { return transform((K) key, fromMultimap.removeAll(key)); } @Override public List<V2> replaceValues( K key, Iterable<? extends V2> values) { throw new UnsupportedOperationException(); } } /** * Creates an index {@code ImmutableListMultimap} that contains the results of * applying a specified function to each item in an {@code Iterable} of * values. Each value will be stored as a value in the resulting multimap, * yielding a multimap with the same size as the input iterable. The key used * to store that value in the multimap will be the result of calling the * function on that value. The resulting multimap is created as an immutable * snapshot. In the returned multimap, keys appear in the order they are first * encountered, and the values corresponding to each key appear in the same * order as they are encountered. * * <p>For example, <pre> {@code * * List<String> badGuys = * Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde"); * Function<String, Integer> stringLengthFunction = ...; * Multimap<Integer, String> index = * Multimaps.index(badGuys, stringLengthFunction); * System.out.println(index);}</pre> * * <p>prints <pre> {@code * * {4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]}}</pre> * * <p>The returned multimap is serializable if its keys and values are all * serializable. * * @param values the values to use when constructing the {@code * ImmutableListMultimap} * @param keyFunction the function used to produce the key for each value * @return {@code ImmutableListMultimap} mapping the result of evaluating the * function {@code keyFunction} on each value in the input collection to * that value * @throws NullPointerException if any of the following cases is true: * <ul> * <li>{@code values} is null * <li>{@code keyFunction} is null * <li>An element in {@code values} is null * <li>{@code keyFunction} returns {@code null} for any element of {@code * values} * </ul> */ public static <K, V> ImmutableListMultimap<K, V> index( Iterable<V> values, Function<? super V, K> keyFunction) { return index(values.iterator(), keyFunction); } /** * Creates an index {@code ImmutableListMultimap} that contains the results of * applying a specified function to each item in an {@code Iterator} of * values. Each value will be stored as a value in the resulting multimap, * yielding a multimap with the same size as the input iterator. The key used * to store that value in the multimap will be the result of calling the * function on that value. The resulting multimap is created as an immutable * snapshot. In the returned multimap, keys appear in the order they are first * encountered, and the values corresponding to each key appear in the same * order as they are encountered. * * <p>For example, <pre> {@code * * List<String> badGuys = * Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde"); * Function<String, Integer> stringLengthFunction = ...; * Multimap<Integer, String> index = * Multimaps.index(badGuys.iterator(), stringLengthFunction); * System.out.println(index);}</pre> * * <p>prints <pre> {@code * * {4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]}}</pre> * * <p>The returned multimap is serializable if its keys and values are all * serializable. * * @param values the values to use when constructing the {@code * ImmutableListMultimap} * @param keyFunction the function used to produce the key for each value * @return {@code ImmutableListMultimap} mapping the result of evaluating the * function {@code keyFunction} on each value in the input collection to * that value * @throws NullPointerException if any of the following cases is true: * <ul> * <li>{@code values} is null * <li>{@code keyFunction} is null * <li>An element in {@code values} is null * <li>{@code keyFunction} returns {@code null} for any element of {@code * values} * </ul> * @since 10.0 */ public static <K, V> ImmutableListMultimap<K, V> index( Iterator<V> values, Function<? super V, K> keyFunction) { checkNotNull(keyFunction); ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder(); while (values.hasNext()) { V value = values.next(); checkNotNull(value, values); builder.put(keyFunction.apply(value), value); } return builder.build(); } static class Keys<K, V> extends AbstractMultiset<K> { final Multimap<K, V> multimap; Keys(Multimap<K, V> multimap) { this.multimap = multimap; } @Override Iterator<Multiset.Entry<K>> entryIterator() { return new TransformedIterator<Map.Entry<K, Collection<V>>, Multiset.Entry<K>>( multimap.asMap().entrySet().iterator()) { @Override Multiset.Entry<K> transform( final Map.Entry<K, Collection<V>> backingEntry) { return new Multisets.AbstractEntry<K>() { @Override public K getElement() { return backingEntry.getKey(); } @Override public int getCount() { return backingEntry.getValue().size(); } }; } }; } @Override int distinctElements() { return multimap.asMap().size(); } @Override Set<Multiset.Entry<K>> createEntrySet() { return new KeysEntrySet(); } class KeysEntrySet extends Multisets.EntrySet<K> { @Override Multiset<K> multiset() { return Keys.this; } @Override public Iterator<Multiset.Entry<K>> iterator() { return entryIterator(); } @Override public int size() { return distinctElements(); } @Override public boolean isEmpty() { return multimap.isEmpty(); } @Override public boolean contains(@Nullable Object o) { if (o instanceof Multiset.Entry) { Multiset.Entry<?> entry = (Multiset.Entry<?>) o; Collection<V> collection = multimap.asMap().get(entry.getElement()); return collection != null && collection.size() == entry.getCount(); } return false; } @Override public boolean remove(@Nullable Object o) { if (o instanceof Multiset.Entry) { Multiset.Entry<?> entry = (Multiset.Entry<?>) o; Collection<V> collection = multimap.asMap().get(entry.getElement()); if (collection != null && collection.size() == entry.getCount()) { collection.clear(); return true; } } return false; } } @Override public boolean contains(@Nullable Object element) { return multimap.containsKey(element); } @Override public Iterator<K> iterator() { return Maps.keyIterator(multimap.entries().iterator()); } @Override public int count(@Nullable Object element) { Collection<V> values = Maps.safeGet(multimap.asMap(), element); return (values == null) ? 0 : values.size(); } @Override public int remove(@Nullable Object element, int occurrences) { checkArgument(occurrences >= 0); if (occurrences == 0) { return count(element); } Collection<V> values = Maps.safeGet(multimap.asMap(), element); if (values == null) { return 0; } int oldCount = values.size(); if (occurrences >= oldCount) { values.clear(); } else { Iterator<V> iterator = values.iterator(); for (int i = 0; i < occurrences; i++) { iterator.next(); iterator.remove(); } } return oldCount; } @Override public void clear() { multimap.clear(); } @Override public Set<K> elementSet() { return multimap.keySet(); } } /** * A skeleton implementation of {@link Multimap#entries()}. */ abstract static class Entries<K, V> extends AbstractCollection<Map.Entry<K, V>> { abstract Multimap<K, V> multimap(); @Override public int size() { return multimap().size(); } @Override public boolean contains(@Nullable Object o) { if (o instanceof Map.Entry) { Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; return multimap().containsEntry(entry.getKey(), entry.getValue()); } return false; } @Override public boolean remove(@Nullable Object o) { if (o instanceof Map.Entry) { Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; return multimap().remove(entry.getKey(), entry.getValue()); } return false; } @Override public void clear() { multimap().clear(); } } /** * A skeleton implementation of {@link Multimap#asMap()}. */ static final class AsMap<K, V> extends Maps.ImprovedAbstractMap<K, Collection<V>> { private final Multimap<K, V> multimap; AsMap(Multimap<K, V> multimap) { this.multimap = checkNotNull(multimap); } @Override public int size() { return multimap.keySet().size(); } @Override protected Set<Entry<K, Collection<V>>> createEntrySet() { return new EntrySet(); } void removeValuesForKey(Object key) { multimap.keySet().remove(key); } class EntrySet extends Maps.EntrySet<K, Collection<V>> { @Override Map<K, Collection<V>> map() { return AsMap.this; } @Override public Iterator<Entry<K, Collection<V>>> iterator() { return Maps.asMapEntryIterator(multimap.keySet(), new Function<K, Collection<V>>() { @Override public Collection<V> apply(K key) { return multimap.get(key); } }); } @Override public boolean remove(Object o) { if (!contains(o)) { return false; } Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; removeValuesForKey(entry.getKey()); return true; } } @SuppressWarnings("unchecked") @Override public Collection<V> get(Object key) { return containsKey(key) ? multimap.get((K) key) : null; } @Override public Collection<V> remove(Object key) { return containsKey(key) ? multimap.removeAll(key) : null; } @Override public Set<K> keySet() { return multimap.keySet(); } @Override public boolean isEmpty() { return multimap.isEmpty(); } @Override public boolean containsKey(Object key) { return multimap.containsKey(key); } @Override public void clear() { multimap.clear(); } } /** * Returns a multimap containing the mappings in {@code unfiltered} whose keys * satisfy a predicate. The returned multimap is a live view of * {@code unfiltered}; changes to one affect the other. * * <p>The resulting multimap's views have iterators that don't support * {@code remove()}, but all other methods are supported by the multimap and * its views. When adding a key that doesn't satisfy the predicate, the * multimap's {@code put()}, {@code putAll()}, and {@code replaceValues()} * methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on * the filtered multimap or its views, only mappings whose keys satisfy the * filter will be removed from the underlying multimap. * * <p>The returned multimap isn't threadsafe or serializable, even if * {@code unfiltered} is. * * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate * across every key/value mapping in the underlying multimap and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered multimap 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. * * @since 11.0 */ public static <K, V> Multimap<K, V> filterKeys( Multimap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { if (unfiltered instanceof SetMultimap) { return filterKeys((SetMultimap<K, V>) unfiltered, keyPredicate); } else if (unfiltered instanceof ListMultimap) { return filterKeys((ListMultimap<K, V>) unfiltered, keyPredicate); } else if (unfiltered instanceof FilteredKeyMultimap) { FilteredKeyMultimap<K, V> prev = (FilteredKeyMultimap<K, V>) unfiltered; return new FilteredKeyMultimap<K, V>(prev.unfiltered, Predicates.and(prev.keyPredicate, keyPredicate)); } else if (unfiltered instanceof FilteredMultimap) { FilteredMultimap<K, V> prev = (FilteredMultimap<K, V>) unfiltered; return filterFiltered(prev, Maps.<K>keyPredicateOnEntries(keyPredicate)); } else { return new FilteredKeyMultimap<K, V>(unfiltered, keyPredicate); } } /** * Returns a multimap containing the mappings in {@code unfiltered} whose keys * satisfy a predicate. The returned multimap is a live view of * {@code unfiltered}; changes to one affect the other. * * <p>The resulting multimap's views have iterators that don't support * {@code remove()}, but all other methods are supported by the multimap and * its views. When adding a key that doesn't satisfy the predicate, the * multimap's {@code put()}, {@code putAll()}, and {@code replaceValues()} * methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on * the filtered multimap or its views, only mappings whose keys satisfy the * filter will be removed from the underlying multimap. * * <p>The returned multimap isn't threadsafe or serializable, even if * {@code unfiltered} is. * * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate * across every key/value mapping in the underlying multimap and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered multimap 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. * * @since 14.0 */ public static <K, V> SetMultimap<K, V> filterKeys( SetMultimap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { if (unfiltered instanceof FilteredKeySetMultimap) { FilteredKeySetMultimap<K, V> prev = (FilteredKeySetMultimap<K, V>) unfiltered; return new FilteredKeySetMultimap<K, V>(prev.unfiltered(), Predicates.and(prev.keyPredicate, keyPredicate)); } else if (unfiltered instanceof FilteredSetMultimap) { FilteredSetMultimap<K, V> prev = (FilteredSetMultimap<K, V>) unfiltered; return filterFiltered(prev, Maps.<K>keyPredicateOnEntries(keyPredicate)); } else { return new FilteredKeySetMultimap<K, V>(unfiltered, keyPredicate); } } /** * Returns a multimap containing the mappings in {@code unfiltered} whose keys * satisfy a predicate. The returned multimap is a live view of * {@code unfiltered}; changes to one affect the other. * * <p>The resulting multimap's views have iterators that don't support * {@code remove()}, but all other methods are supported by the multimap and * its views. When adding a key that doesn't satisfy the predicate, the * multimap's {@code put()}, {@code putAll()}, and {@code replaceValues()} * methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on * the filtered multimap or its views, only mappings whose keys satisfy the * filter will be removed from the underlying multimap. * * <p>The returned multimap isn't threadsafe or serializable, even if * {@code unfiltered} is. * * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate * across every key/value mapping in the underlying multimap and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered multimap 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. * * @since 14.0 */ public static <K, V> ListMultimap<K, V> filterKeys( ListMultimap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { if (unfiltered instanceof FilteredKeyListMultimap) { FilteredKeyListMultimap<K, V> prev = (FilteredKeyListMultimap<K, V>) unfiltered; return new FilteredKeyListMultimap<K, V>(prev.unfiltered(), Predicates.and(prev.keyPredicate, keyPredicate)); } else { return new FilteredKeyListMultimap<K, V>(unfiltered, keyPredicate); } } /** * Returns a multimap containing the mappings in {@code unfiltered} whose values * satisfy a predicate. The returned multimap is a live view of * {@code unfiltered}; changes to one affect the other. * * <p>The resulting multimap's views have iterators that don't support * {@code remove()}, but all other methods are supported by the multimap and * its views. When adding a value that doesn't satisfy the predicate, the * multimap's {@code put()}, {@code putAll()}, and {@code replaceValues()} * methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on * the filtered multimap or its views, only mappings whose value satisfy the * filter will be removed from the underlying multimap. * * <p>The returned multimap isn't threadsafe or serializable, even if * {@code unfiltered} is. * * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate * across every key/value mapping in the underlying multimap and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered multimap 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. * * @since 11.0 */ public static <K, V> Multimap<K, V> filterValues( Multimap<K, V> unfiltered, final Predicate<? super V> valuePredicate) { return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate)); } /** * Returns a multimap containing the mappings in {@code unfiltered} whose values * satisfy a predicate. The returned multimap is a live view of * {@code unfiltered}; changes to one affect the other. * * <p>The resulting multimap's views have iterators that don't support * {@code remove()}, but all other methods are supported by the multimap and * its views. When adding a value that doesn't satisfy the predicate, the * multimap's {@code put()}, {@code putAll()}, and {@code replaceValues()} * methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on * the filtered multimap or its views, only mappings whose value satisfy the * filter will be removed from the underlying multimap. * * <p>The returned multimap isn't threadsafe or serializable, even if * {@code unfiltered} is. * * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate * across every key/value mapping in the underlying multimap and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered multimap 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. * * @since 14.0 */ public static <K, V> SetMultimap<K, V> filterValues( SetMultimap<K, V> unfiltered, final Predicate<? super V> valuePredicate) { return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate)); } /** * Returns a multimap containing the mappings in {@code unfiltered} that * satisfy a predicate. The returned multimap is a live view of * {@code unfiltered}; changes to one affect the other. * * <p>The resulting multimap's views have iterators that don't support * {@code remove()}, but all other methods are supported by the multimap and * its views. When adding a key/value pair that doesn't satisfy the predicate, * multimap's {@code put()}, {@code putAll()}, and {@code replaceValues()} * methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on * the filtered multimap or its views, only mappings whose keys satisfy the * filter will be removed from the underlying multimap. * * <p>The returned multimap isn't threadsafe or serializable, even if * {@code unfiltered} is. * * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate * across every key/value mapping in the underlying multimap and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered multimap and use the copy. * * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with * equals</i>, as documented at {@link Predicate#apply}. * * @since 11.0 */ public static <K, V> Multimap<K, V> filterEntries( Multimap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { checkNotNull(entryPredicate); if (unfiltered instanceof SetMultimap) { return filterEntries((SetMultimap<K, V>) unfiltered, entryPredicate); } return (unfiltered instanceof FilteredMultimap) ? filterFiltered((FilteredMultimap<K, V>) unfiltered, entryPredicate) : new FilteredEntryMultimap<K, V>(checkNotNull(unfiltered), entryPredicate); } /** * Returns a multimap containing the mappings in {@code unfiltered} that * satisfy a predicate. The returned multimap is a live view of * {@code unfiltered}; changes to one affect the other. * * <p>The resulting multimap's views have iterators that don't support * {@code remove()}, but all other methods are supported by the multimap and * its views. When adding a key/value pair that doesn't satisfy the predicate, * multimap's {@code put()}, {@code putAll()}, and {@code replaceValues()} * methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on * the filtered multimap or its views, only mappings whose keys satisfy the * filter will be removed from the underlying multimap. * * <p>The returned multimap isn't threadsafe or serializable, even if * {@code unfiltered} is. * * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate * across every key/value mapping in the underlying multimap and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered multimap and use the copy. * * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with * equals</i>, as documented at {@link Predicate#apply}. * * @since 14.0 */ public static <K, V> SetMultimap<K, V> filterEntries( SetMultimap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { checkNotNull(entryPredicate); return (unfiltered instanceof FilteredSetMultimap) ? filterFiltered((FilteredSetMultimap<K, V>) unfiltered, entryPredicate) : new FilteredEntrySetMultimap<K, V>(checkNotNull(unfiltered), entryPredicate); } /** * Support removal operations when filtering a filtered multimap. Since a * filtered multimap has iterators that don't support remove, passing one to * the FilteredEntryMultimap constructor would lead to a multimap whose removal * operations would fail. This method combines the predicates to avoid that * problem. */ private static <K, V> Multimap<K, V> filterFiltered(FilteredMultimap<K, V> multimap, Predicate<? super Entry<K, V>> entryPredicate) { Predicate<Entry<K, V>> predicate = Predicates.and(multimap.entryPredicate(), entryPredicate); return new FilteredEntryMultimap<K, V>(multimap.unfiltered(), predicate); } /** * Support removal operations when filtering a filtered multimap. Since a filtered multimap has * iterators that don't support remove, passing one to the FilteredEntryMultimap constructor would * lead to a multimap whose removal operations would fail. This method combines the predicates to * avoid that problem. */ private static <K, V> SetMultimap<K, V> filterFiltered( FilteredSetMultimap<K, V> multimap, Predicate<? super Entry<K, V>> entryPredicate) { Predicate<Entry<K, V>> predicate = Predicates.and(multimap.entryPredicate(), entryPredicate); return new FilteredEntrySetMultimap<K, V>(multimap.unfiltered(), predicate); } static boolean equalsImpl(Multimap<?, ?> multimap, @Nullable Object object) { if (object == multimap) { return true; } if (object instanceof Multimap) { Multimap<?, ?> that = (Multimap<?, ?>) object; return multimap.asMap().equals(that.asMap()); } return false; } // TODO(jlevy): Create methods that filter a SortedSetMultimap. }
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.Map.Entry; import java.util.Set; import javax.annotation.Nullable; /** * A multimap which forwards all its method calls to another multimap. * Subclasses should override one or more methods to modify the behavior of * the backing multimap as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * @author Robert Konigsberg * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingMultimap<K, V> extends ForwardingObject implements Multimap<K, V> { /** Constructor for use by subclasses. */ protected ForwardingMultimap() {} @Override protected abstract Multimap<K, V> delegate(); @Override public Map<K, Collection<V>> asMap() { return delegate().asMap(); } @Override public void clear() { delegate().clear(); } @Override public boolean containsEntry(@Nullable Object key, @Nullable Object value) { return delegate().containsEntry(key, value); } @Override public boolean containsKey(@Nullable Object key) { return delegate().containsKey(key); } @Override public boolean containsValue(@Nullable Object value) { return delegate().containsValue(value); } @Override public Collection<Entry<K, V>> entries() { return delegate().entries(); } @Override public Collection<V> get(@Nullable K key) { return delegate().get(key); } @Override public boolean isEmpty() { return delegate().isEmpty(); } @Override public Multiset<K> keys() { return delegate().keys(); } @Override public Set<K> keySet() { return delegate().keySet(); } @Override public boolean put(K key, V value) { return delegate().put(key, value); } @Override public boolean putAll(K key, Iterable<? extends V> values) { return delegate().putAll(key, values); } @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { return delegate().putAll(multimap); } @Override public boolean remove(@Nullable Object key, @Nullable Object value) { return delegate().remove(key, value); } @Override public Collection<V> removeAll(@Nullable Object key) { return delegate().removeAll(key); } @Override public Collection<V> replaceValues(K key, Iterable<? extends V> values) { return delegate().replaceValues(key, values); } @Override public int size() { return delegate().size(); } @Override public Collection<V> values() { return delegate().values(); } @Override public boolean equals(@Nullable Object object) { return object == this || delegate().equals(object); } @Override public int hashCode() { return delegate().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.checkArgument; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; /** * Implementation of {@code Multimap} that does not allow duplicate key-value * entries and that returns collections whose iterators follow the ordering in * which the data was added to the multimap. * * <p>The collections returned by {@code keySet}, {@code keys}, and {@code * asMap} iterate through the keys in the order they were first added to the * multimap. Similarly, {@code get}, {@code removeAll}, and {@code * replaceValues} return collections that iterate through the values in the * order they were added. The collections generated by {@code entries} and * {@code values} iterate across the key-value mappings in the order they were * added to the multimap. * * <p>The iteration ordering of the collections generated by {@code keySet}, * {@code keys}, and {@code asMap} has a few subtleties. As long as the set of * keys remains unchanged, adding or removing mappings does not affect the key * iteration order. However, if you remove all values associated with a key and * then add the key back to the multimap, that key will come last in the key * iteration order. * * <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>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#synchronizedSetMultimap}. * * <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 * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public final class LinkedHashMultimap<K, V> extends AbstractSetMultimap<K, V> { /** * Creates a new, empty {@code LinkedHashMultimap} with the default initial * capacities. */ public static <K, V> LinkedHashMultimap<K, V> create() { return new LinkedHashMultimap<K, V>(DEFAULT_KEY_CAPACITY, DEFAULT_VALUE_SET_CAPACITY); } /** * Constructs an empty {@code LinkedHashMultimap} with enough capacity to hold * the specified numbers of keys and values without rehashing. * * @param expectedKeys the expected number of distinct keys * @param expectedValuesPerKey the expected average number of values per key * @throws IllegalArgumentException if {@code expectedKeys} or {@code * expectedValuesPerKey} is negative */ public static <K, V> LinkedHashMultimap<K, V> create( int expectedKeys, int expectedValuesPerKey) { return new LinkedHashMultimap<K, V>( Maps.capacity(expectedKeys), Maps.capacity(expectedValuesPerKey)); } /** * Constructs a {@code LinkedHashMultimap} with the same mappings as the * specified multimap. If a key-value mapping appears multiple times in the * input multimap, it only appears once in the constructed multimap. The new * multimap has the same {@link Multimap#entries()} iteration order as the * input multimap, except for excluding duplicate mappings. * * @param multimap the multimap whose contents are copied to this multimap */ public static <K, V> LinkedHashMultimap<K, V> create( Multimap<? extends K, ? extends V> multimap) { LinkedHashMultimap<K, V> result = create(multimap.keySet().size(), DEFAULT_VALUE_SET_CAPACITY); result.putAll(multimap); return result; } private interface ValueSetLink<K, V> { ValueSetLink<K, V> getPredecessorInValueSet(); ValueSetLink<K, V> getSuccessorInValueSet(); void setPredecessorInValueSet(ValueSetLink<K, V> entry); void setSuccessorInValueSet(ValueSetLink<K, V> entry); } private static <K, V> void succeedsInValueSet(ValueSetLink<K, V> pred, ValueSetLink<K, V> succ) { pred.setSuccessorInValueSet(succ); succ.setPredecessorInValueSet(pred); } private static <K, V> void succeedsInMultimap( ValueEntry<K, V> pred, ValueEntry<K, V> succ) { pred.setSuccessorInMultimap(succ); succ.setPredecessorInMultimap(pred); } private static <K, V> void deleteFromValueSet(ValueSetLink<K, V> entry) { succeedsInValueSet(entry.getPredecessorInValueSet(), entry.getSuccessorInValueSet()); } private static <K, V> void deleteFromMultimap(ValueEntry<K, V> entry) { succeedsInMultimap(entry.getPredecessorInMultimap(), entry.getSuccessorInMultimap()); } /** * LinkedHashMultimap entries are in no less than three coexisting linked lists: * a bucket in the hash table for a Set<V> associated with a key, the linked list * of insertion-ordered entries in that Set<V>, and the linked list of entries * in the LinkedHashMultimap as a whole. */ @VisibleForTesting static final class ValueEntry<K, V> extends ImmutableEntry<K, V> implements ValueSetLink<K, V> { final int smearedValueHash; @Nullable ValueEntry<K, V> nextInValueBucket; ValueSetLink<K, V> predecessorInValueSet; ValueSetLink<K, V> successorInValueSet; ValueEntry<K, V> predecessorInMultimap; ValueEntry<K, V> successorInMultimap; ValueEntry(@Nullable K key, @Nullable V value, int smearedValueHash, @Nullable ValueEntry<K, V> nextInValueBucket) { super(key, value); this.smearedValueHash = smearedValueHash; this.nextInValueBucket = nextInValueBucket; } boolean matchesValue(@Nullable Object v, int smearedVHash) { return smearedValueHash == smearedVHash && Objects.equal(getValue(), v); } @Override public ValueSetLink<K, V> getPredecessorInValueSet() { return predecessorInValueSet; } @Override public ValueSetLink<K, V> getSuccessorInValueSet() { return successorInValueSet; } @Override public void setPredecessorInValueSet(ValueSetLink<K, V> entry) { predecessorInValueSet = entry; } @Override public void setSuccessorInValueSet(ValueSetLink<K, V> entry) { successorInValueSet = entry; } public ValueEntry<K, V> getPredecessorInMultimap() { return predecessorInMultimap; } public ValueEntry<K, V> getSuccessorInMultimap() { return successorInMultimap; } public void setSuccessorInMultimap(ValueEntry<K, V> multimapSuccessor) { this.successorInMultimap = multimapSuccessor; } public void setPredecessorInMultimap(ValueEntry<K, V> multimapPredecessor) { this.predecessorInMultimap = multimapPredecessor; } } private static final int DEFAULT_KEY_CAPACITY = 16; private static final int DEFAULT_VALUE_SET_CAPACITY = 2; @VisibleForTesting static final double VALUE_SET_LOAD_FACTOR = 1.0; @VisibleForTesting transient int valueSetCapacity = DEFAULT_VALUE_SET_CAPACITY; private transient ValueEntry<K, V> multimapHeaderEntry; private LinkedHashMultimap(int keyCapacity, int valueSetCapacity) { super(new LinkedHashMap<K, Collection<V>>(keyCapacity)); checkArgument(valueSetCapacity >= 0, "expectedValuesPerKey must be >= 0 but was %s", valueSetCapacity); this.valueSetCapacity = valueSetCapacity; this.multimapHeaderEntry = new ValueEntry<K, V>(null, null, 0, null); succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry); } /** * {@inheritDoc} * * <p>Creates an empty {@code LinkedHashSet} for a collection of values for * one key. * * @return a new {@code LinkedHashSet} containing a collection of values for * one key */ @Override Set<V> createCollection() { return new LinkedHashSet<V>(valueSetCapacity); } /** * {@inheritDoc} * * <p>Creates a decorated insertion-ordered set that also keeps track of the * order in which key-value pairs are added to the multimap. * * @param key key to associate with values in the collection * @return a new decorated set containing a collection of values for one key */ @Override Collection<V> createCollection(K key) { return new ValueSet(key, valueSetCapacity); } /** * {@inheritDoc} * * <p>If {@code values} is not empty and the multimap already contains a * mapping for {@code key}, the {@code keySet()} ordering is unchanged. * However, the provided values always come last in the {@link #entries()} and * {@link #values()} iteration orderings. */ @Override public Set<V> replaceValues(@Nullable K key, Iterable<? extends V> values) { return super.replaceValues(key, values); } /** * Returns a set of all key-value pairs. Changes to the returned set will * update the underlying multimap, and vice versa. The entries set does not * support the {@code add} or {@code addAll} operations. * * <p>The iterator generated by the returned set traverses the entries in the * order they were added to the multimap. * * <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 Set<Map.Entry<K, V>> entries() { return super.entries(); } /** * Returns a collection of all values in the multimap. Changes to the returned * collection will update the underlying multimap, and vice versa. * * <p>The iterator generated by the returned collection traverses the values * in the order they were added to the multimap. */ @Override public Collection<V> values() { return super.values(); } @VisibleForTesting final class ValueSet extends Sets.ImprovedAbstractSet<V> implements ValueSetLink<K, V> { /* * We currently use a fixed load factor of 1.0, a bit higher than normal to reduce memory * consumption. */ private final K key; @VisibleForTesting ValueEntry<K, V>[] hashTable; private int size = 0; private int modCount = 0; // We use the set object itself as the end of the linked list, avoiding an unnecessary // entry object per key. private ValueSetLink<K, V> firstEntry; private ValueSetLink<K, V> lastEntry; ValueSet(K key, int expectedValues) { this.key = key; this.firstEntry = this; this.lastEntry = this; // Round expected values up to a power of 2 to get the table size. int tableSize = Hashing.closedTableSize(expectedValues, VALUE_SET_LOAD_FACTOR); @SuppressWarnings("unchecked") ValueEntry<K, V>[] hashTable = new ValueEntry[tableSize]; this.hashTable = hashTable; } private int mask() { return hashTable.length - 1; } @Override public ValueSetLink<K, V> getPredecessorInValueSet() { return lastEntry; } @Override public ValueSetLink<K, V> getSuccessorInValueSet() { return firstEntry; } @Override public void setPredecessorInValueSet(ValueSetLink<K, V> entry) { lastEntry = entry; } @Override public void setSuccessorInValueSet(ValueSetLink<K, V> entry) { firstEntry = entry; } @Override public Iterator<V> iterator() { return new Iterator<V>() { ValueSetLink<K, V> nextEntry = firstEntry; ValueEntry<K, V> toRemove; int expectedModCount = modCount; private void checkForComodification() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } @Override public boolean hasNext() { checkForComodification(); return nextEntry != ValueSet.this; } @Override public V next() { if (!hasNext()) { throw new NoSuchElementException(); } ValueEntry<K, V> entry = (ValueEntry<K, V>) nextEntry; V result = entry.getValue(); toRemove = entry; nextEntry = entry.getSuccessorInValueSet(); return result; } @Override public void remove() { checkForComodification(); Iterators.checkRemove(toRemove != null); ValueSet.this.remove(toRemove.getValue()); expectedModCount = modCount; toRemove = null; } }; } @Override public int size() { return size; } @Override public boolean contains(@Nullable Object o) { int smearedHash = Hashing.smearedHash(o); for (ValueEntry<K, V> entry = hashTable[smearedHash & mask()]; entry != null; entry = entry.nextInValueBucket) { if (entry.matchesValue(o, smearedHash)) { return true; } } return false; } @Override public boolean add(@Nullable V value) { int smearedHash = Hashing.smearedHash(value); int bucket = smearedHash & mask(); ValueEntry<K, V> rowHead = hashTable[bucket]; for (ValueEntry<K, V> entry = rowHead; entry != null; entry = entry.nextInValueBucket) { if (entry.matchesValue(value, smearedHash)) { return false; } } ValueEntry<K, V> newEntry = new ValueEntry<K, V>(key, value, smearedHash, rowHead); succeedsInValueSet(lastEntry, newEntry); succeedsInValueSet(newEntry, this); succeedsInMultimap(multimapHeaderEntry.getPredecessorInMultimap(), newEntry); succeedsInMultimap(newEntry, multimapHeaderEntry); hashTable[bucket] = newEntry; size++; modCount++; rehashIfNecessary(); return true; } private void rehashIfNecessary() { if (Hashing.needsResizing(size, hashTable.length, VALUE_SET_LOAD_FACTOR)) { @SuppressWarnings("unchecked") ValueEntry<K, V>[] hashTable = new ValueEntry[this.hashTable.length * 2]; this.hashTable = hashTable; int mask = hashTable.length - 1; for (ValueSetLink<K, V> entry = firstEntry; entry != this; entry = entry.getSuccessorInValueSet()) { ValueEntry<K, V> valueEntry = (ValueEntry<K, V>) entry; int bucket = valueEntry.smearedValueHash & mask; valueEntry.nextInValueBucket = hashTable[bucket]; hashTable[bucket] = valueEntry; } } } @Override public boolean remove(@Nullable Object o) { int smearedHash = Hashing.smearedHash(o); int bucket = smearedHash & mask(); ValueEntry<K, V> prev = null; for (ValueEntry<K, V> entry = hashTable[bucket]; entry != null; prev = entry, entry = entry.nextInValueBucket) { if (entry.matchesValue(o, smearedHash)) { if (prev == null) { // first entry in the bucket hashTable[bucket] = entry.nextInValueBucket; } else { prev.nextInValueBucket = entry.nextInValueBucket; } deleteFromValueSet(entry); deleteFromMultimap(entry); size--; modCount++; return true; } } return false; } @Override public void clear() { Arrays.fill(hashTable, null); size = 0; for (ValueSetLink<K, V> entry = firstEntry; entry != this; entry = entry.getSuccessorInValueSet()) { ValueEntry<K, V> valueEntry = (ValueEntry<K, V>) entry; deleteFromMultimap(valueEntry); } succeedsInValueSet(this, this); modCount++; } } @Override Iterator<Map.Entry<K, V>> entryIterator() { return new Iterator<Map.Entry<K, V>>() { ValueEntry<K, V> nextEntry = multimapHeaderEntry.successorInMultimap; ValueEntry<K, V> toRemove; @Override public boolean hasNext() { return nextEntry != multimapHeaderEntry; } @Override public Map.Entry<K, V> next() { if (!hasNext()) { throw new NoSuchElementException(); } ValueEntry<K, V> result = nextEntry; toRemove = result; nextEntry = nextEntry.successorInMultimap; return result; } @Override public void remove() { Iterators.checkRemove(toRemove != null); LinkedHashMultimap.this.remove(toRemove.getKey(), toRemove.getValue()); toRemove = null; } }; } @Override Iterator<V> valueIterator() { return Maps.valueIterator(entryIterator()); } @Override public void clear() { super.clear(); succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry); } /** * @serialData the expected values per key, the number of distinct keys, * the number of entries, and the entries in order */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeInt(valueSetCapacity); stream.writeInt(keySet().size()); for (K key : keySet()) { stream.writeObject(key); } stream.writeInt(size()); for (Map.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(); multimapHeaderEntry = new ValueEntry<K, V>(null, null, 0, null); succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry); valueSetCapacity = stream.readInt(); int distinctKeys = stream.readInt(); Map<K, Collection<V>> map = new LinkedHashMap<K, Collection<V>>(Maps.capacity(distinctKeys)); for (int i = 0; i < distinctKeys; i++) { @SuppressWarnings("unchecked") K key = (K) stream.readObject(); map.put(key, createCollection(key)); } int entries = stream.readInt(); for (int i = 0; i < entries; i++) { @SuppressWarnings("unchecked") K key = (K) stream.readObject(); @SuppressWarnings("unchecked") V value = (V) stream.readObject(); map.get(key).add(value); } setMap(map); } @GwtIncompatible("java serialization not supported") private static final long serialVersionUID = 1; }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; import java.util.PriorityQueue; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.TimeUnit; /** * Static utility methods pertaining to {@link Queue} and {@link Deque} instances. * Also see this class's counterparts {@link Lists}, {@link Sets}, and {@link Maps}. * * @author Kurt Alfred Kluever * @since 11.0 */ public final class Queues { private Queues() {} // ArrayBlockingQueue /** * Creates an empty {@code ArrayBlockingQueue} with the given (fixed) capacity * and nonfair access policy. */ public static <E> ArrayBlockingQueue<E> newArrayBlockingQueue(int capacity) { return new ArrayBlockingQueue<E>(capacity); } // ArrayDeque /** * Creates an empty {@code ArrayDeque}. * * @since 12.0 */ public static <E> ArrayDeque<E> newArrayDeque() { return new ArrayDeque<E>(); } /** * Creates an {@code ArrayDeque} containing the elements of the specified iterable, * in the order they are returned by the iterable's iterator. * * @since 12.0 */ public static <E> ArrayDeque<E> newArrayDeque(Iterable<? extends E> elements) { if (elements instanceof Collection) { return new ArrayDeque<E>(Collections2.cast(elements)); } ArrayDeque<E> deque = new ArrayDeque<E>(); Iterables.addAll(deque, elements); return deque; } // ConcurrentLinkedQueue /** * Creates an empty {@code ConcurrentLinkedQueue}. */ public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue() { return new ConcurrentLinkedQueue<E>(); } /** * Creates a {@code ConcurrentLinkedQueue} containing the elements of the specified iterable, * in the order they are returned by the iterable's iterator. */ public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue( Iterable<? extends E> elements) { if (elements instanceof Collection) { return new ConcurrentLinkedQueue<E>(Collections2.cast(elements)); } ConcurrentLinkedQueue<E> queue = new ConcurrentLinkedQueue<E>(); Iterables.addAll(queue, elements); return queue; } // LinkedBlockingDeque /** * Creates an empty {@code LinkedBlockingDeque} with a capacity of {@link Integer#MAX_VALUE}. * * @since 12.0 */ public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque() { return new LinkedBlockingDeque<E>(); } /** * Creates an empty {@code LinkedBlockingDeque} with the given (fixed) capacity. * * @throws IllegalArgumentException if {@code capacity} is less than 1 * @since 12.0 */ public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(int capacity) { return new LinkedBlockingDeque<E>(capacity); } /** * Creates a {@code LinkedBlockingDeque} with a capacity of {@link Integer#MAX_VALUE}, * containing the elements of the specified iterable, * in the order they are returned by the iterable's iterator. * * @since 12.0 */ public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(Iterable<? extends E> elements) { if (elements instanceof Collection) { return new LinkedBlockingDeque<E>(Collections2.cast(elements)); } LinkedBlockingDeque<E> deque = new LinkedBlockingDeque<E>(); Iterables.addAll(deque, elements); return deque; } // LinkedBlockingQueue /** * Creates an empty {@code LinkedBlockingQueue} with a capacity of {@link Integer#MAX_VALUE}. */ public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue() { return new LinkedBlockingQueue<E>(); } /** * Creates an empty {@code LinkedBlockingQueue} with the given (fixed) capacity. * * @throws IllegalArgumentException if {@code capacity} is less than 1 */ public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(int capacity) { return new LinkedBlockingQueue<E>(capacity); } /** * Creates a {@code LinkedBlockingQueue} with a capacity of {@link Integer#MAX_VALUE}, * containing the elements of the specified iterable, * in the order they are returned by the iterable's iterator. * * @param elements the elements that the queue should contain, in order * @return a new {@code LinkedBlockingQueue} containing those elements */ public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(Iterable<? extends E> elements) { if (elements instanceof Collection) { return new LinkedBlockingQueue<E>(Collections2.cast(elements)); } LinkedBlockingQueue<E> queue = new LinkedBlockingQueue<E>(); Iterables.addAll(queue, elements); return queue; } // LinkedList: see {@link com.google.common.collect.Lists} // PriorityBlockingQueue /** * Creates an empty {@code PriorityBlockingQueue} with the ordering given by its * elements' natural ordering. * * @since 11.0 (requires that {@code E} be {@code Comparable} since 15.0). */ public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue() { return new PriorityBlockingQueue<E>(); } /** * Creates a {@code PriorityBlockingQueue} containing the given elements. * * <b>Note:</b> If the specified iterable is a {@code SortedSet} or a {@code PriorityQueue}, * this priority queue will be ordered according to the same ordering. * * @since 11.0 (requires that {@code E} be {@code Comparable} since 15.0). */ public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue( Iterable<? extends E> elements) { if (elements instanceof Collection) { return new PriorityBlockingQueue<E>(Collections2.cast(elements)); } PriorityBlockingQueue<E> queue = new PriorityBlockingQueue<E>(); Iterables.addAll(queue, elements); return queue; } // PriorityQueue /** * Creates an empty {@code PriorityQueue} with the ordering given by its * elements' natural ordering. * * @since 11.0 (requires that {@code E} be {@code Comparable} since 15.0). */ public static <E extends Comparable> PriorityQueue<E> newPriorityQueue() { return new PriorityQueue<E>(); } /** * Creates a {@code PriorityQueue} containing the given elements. * * <b>Note:</b> If the specified iterable is a {@code SortedSet} or a {@code PriorityQueue}, * this priority queue will be ordered according to the same ordering. * * @since 11.0 (requires that {@code E} be {@code Comparable} since 15.0). */ public static <E extends Comparable> PriorityQueue<E> newPriorityQueue( Iterable<? extends E> elements) { if (elements instanceof Collection) { return new PriorityQueue<E>(Collections2.cast(elements)); } PriorityQueue<E> queue = new PriorityQueue<E>(); Iterables.addAll(queue, elements); return queue; } // SynchronousQueue /** * Creates an empty {@code SynchronousQueue} with nonfair access policy. */ public static <E> SynchronousQueue<E> newSynchronousQueue() { return new SynchronousQueue<E>(); } /** * Drains the queue as {@link BlockingQueue#drainTo(Collection, int)}, but if the requested * {@code numElements} elements are not available, it will wait for them up to the specified * timeout. * * @param q the blocking queue to be drained * @param buffer where to add the transferred elements * @param numElements the number of elements to be waited for * @param timeout how long to wait before giving up, in units of {@code unit} * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter * @return the number of elements transferred * @throws InterruptedException if interrupted while waiting */ @Beta public static <E> int drain(BlockingQueue<E> q, Collection<? super E> buffer, int numElements, long timeout, TimeUnit unit) throws InterruptedException { Preconditions.checkNotNull(buffer); /* * This code performs one System.nanoTime() more than necessary, and in return, the time to * execute Queue#drainTo is not added *on top* of waiting for the timeout (which could make * the timeout arbitrarily inaccurate, given a queue that is slow to drain). */ long deadline = System.nanoTime() + unit.toNanos(timeout); int added = 0; while (added < numElements) { // we could rely solely on #poll, but #drainTo might be more efficient when there are multiple // elements already available (e.g. LinkedBlockingQueue#drainTo locks only once) added += q.drainTo(buffer, numElements - added); if (added < numElements) { // not enough elements immediately available; will have to poll E e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS); if (e == null) { break; // we already waited enough, and there are no more elements in sight } buffer.add(e); added++; } } return added; } /** * Drains the queue as {@linkplain #drain(BlockingQueue, Collection, int, long, TimeUnit)}, * but with a different behavior in case it is interrupted while waiting. In that case, the * operation will continue as usual, and in the end the thread's interruption status will be set * (no {@code InterruptedException} is thrown). * * @param q the blocking queue to be drained * @param buffer where to add the transferred elements * @param numElements the number of elements to be waited for * @param timeout how long to wait before giving up, in units of {@code unit} * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter * @return the number of elements transferred */ @Beta public static <E> int drainUninterruptibly(BlockingQueue<E> q, Collection<? super E> buffer, int numElements, long timeout, TimeUnit unit) { Preconditions.checkNotNull(buffer); long deadline = System.nanoTime() + unit.toNanos(timeout); int added = 0; boolean interrupted = false; try { while (added < numElements) { // we could rely solely on #poll, but #drainTo might be more efficient when there are // multiple elements already available (e.g. LinkedBlockingQueue#drainTo locks only once) added += q.drainTo(buffer, numElements - added); if (added < numElements) { // not enough elements immediately available; will have to poll E e; // written exactly once, by a successful (uninterrupted) invocation of #poll while (true) { try { e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS); break; } catch (InterruptedException ex) { interrupted = true; // note interruption and retry } } if (e == null) { break; // we already waited enough, and there are no more elements in sight } buffer.add(e); added++; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } return added; } /** * Returns a synchronized (thread-safe) queue backed by the specified queue. In order to * guarantee serial access, it is critical that <b>all</b> access to the backing queue is * accomplished through the returned queue. * * <p>It is imperative that the user manually synchronize on the returned queue when accessing * the queue's iterator: <pre> {@code * * Queue<E> queue = Queues.synchronizedQueue(MinMaxPriorityQueue.<E>create()); * ... * queue.add(element); // Needn't be in synchronized block * ... * synchronized (queue) { // Must synchronize on queue! * Iterator<E> i = queue.iterator(); // Must be in synchronized block * while (i.hasNext()) { * foo(i.next()); * } * }}</pre> * * <p>Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned queue will be serializable if the specified queue is serializable. * * @param queue the queue to be wrapped in a synchronized view * @return a synchronized view of the specified queue * @since 14.0 */ @Beta public static <E> Queue<E> synchronizedQueue(Queue<E> queue) { return Synchronized.queue(queue, null); } /** * Returns a synchronized (thread-safe) deque backed by the specified deque. In order to * guarantee serial access, it is critical that <b>all</b> access to the backing deque is * accomplished through the returned deque. * * <p>It is imperative that the user manually synchronize on the returned deque when accessing * any of the deque's iterators: <pre> {@code * * Deque<E> deque = Queues.synchronizedDeque(Queues.<E>newArrayDeque()); * ... * deque.add(element); // Needn't be in synchronized block * ... * synchronized (deque) { // Must synchronize on deque! * Iterator<E> i = deque.iterator(); // Must be in synchronized block * while (i.hasNext()) { * foo(i.next()); * } * }}</pre> * * <p>Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned deque will be serializable if the specified deque is serializable. * * @param deque the deque to be wrapped in a synchronized view * @return a synchronized view of the specified deque * @since 15.0 */ @Beta public static <E> Deque<E> synchronizedDeque(Deque<E> deque) { return Synchronized.deque(deque, 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 static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.GwtCompatible; import java.util.NoSuchElementException; /** * This class provides a skeletal implementation of the {@code Iterator} * interface, to make this interface easier to implement for certain types of * data sources. * * <p>{@code Iterator} requires its implementations to support querying the * end-of-data status without changing the iterator's state, using the {@link * #hasNext} method. But many data sources, such as {@link * java.io.Reader#read()}, do not expose this information; the only way to * discover whether there is any data left is by trying to retrieve it. These * types of data sources are ordinarily difficult to write iterators for. But * using this class, one must implement only the {@link #computeNext} method, * and invoke the {@link #endOfData} method when appropriate. * * <p>Another example is an iterator that skips over null elements in a backing * iterator. This could be implemented as: <pre> {@code * * public static Iterator<String> skipNulls(final Iterator<String> in) { * return new AbstractIterator<String>() { * protected String computeNext() { * while (in.hasNext()) { * String s = in.next(); * if (s != null) { * return s; * } * } * return endOfData(); * } * }; * }}</pre> * * <p>This class supports iterators that include null elements. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ // When making changes to this class, please also update the copy at // com.google.common.base.AbstractIterator @GwtCompatible public abstract class AbstractIterator<T> extends UnmodifiableIterator<T> { private State state = State.NOT_READY; /** Constructor for use by subclasses. */ protected AbstractIterator() {} private enum State { /** We have computed the next element and haven't returned it yet. */ READY, /** We haven't yet computed or have already returned the element. */ NOT_READY, /** We have reached the end of the data and are finished. */ DONE, /** We've suffered an exception and are kaput. */ FAILED, } private T next; /** * Returns the next element. <b>Note:</b> the implementation must call {@link * #endOfData()} when there are no elements left in the iteration. Failure to * do so could result in an infinite loop. * * <p>The initial invocation of {@link #hasNext()} or {@link #next()} calls * this method, as does the first invocation of {@code hasNext} or {@code * next} following each successful call to {@code next}. Once the * implementation either invokes {@code endOfData} or throws an exception, * {@code computeNext} is guaranteed to never be called again. * * <p>If this method throws an exception, it will propagate outward to the * {@code hasNext} or {@code next} invocation that invoked this method. Any * further attempts to use the iterator will result in an {@link * IllegalStateException}. * * <p>The implementation of this method may not invoke the {@code hasNext}, * {@code next}, or {@link #peek()} methods on this instance; if it does, an * {@code IllegalStateException} will result. * * @return the next element if there was one. If {@code endOfData} was called * during execution, the return value will be ignored. * @throws RuntimeException if any unrecoverable error happens. This exception * will propagate outward to the {@code hasNext()}, {@code next()}, or * {@code peek()} invocation that invoked this method. Any further * attempts to use the iterator will result in an * {@link IllegalStateException}. */ protected abstract T computeNext(); /** * Implementations of {@link #computeNext} <b>must</b> invoke this method when * there are no elements left in the iteration. * * @return {@code null}; a convenience so your {@code computeNext} * implementation can use the simple statement {@code return endOfData();} */ protected final T endOfData() { state = State.DONE; return null; } @Override public final boolean hasNext() { checkState(state != State.FAILED); switch (state) { case DONE: return false; case READY: return true; default: } return tryToComputeNext(); } private boolean tryToComputeNext() { state = State.FAILED; // temporary pessimism next = computeNext(); if (state != State.DONE) { state = State.READY; return true; } return false; } @Override public final T next() { if (!hasNext()) { throw new NoSuchElementException(); } state = State.NOT_READY; return next; } /** * Returns the next element in the iteration without advancing the iteration, * according to the contract of {@link PeekingIterator#peek()}. * * <p>Implementations of {@code AbstractIterator} that wish to expose this * functionality should implement {@code PeekingIterator}. */ public final T peek() { if (!hasNext()) { throw new NoSuchElementException(); } return next; } }
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.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 java.util.Collections; import java.util.NoSuchElementException; import java.util.Set; /** * A sorted set of contiguous values in a given {@link DiscreteDomain}. * * <p><b>Warning:</b> Be extremely careful what you do with conceptually large instances (such as * {@code ContiguousSet.create(Range.greaterThan(0), DiscreteDomain.integers()}). Certain * operations on such a set can be performed efficiently, but others (such as {@link Set#hashCode} * or {@link Collections#frequency}) can cause major performance problems. * * @author Gregory Kick * @since 10.0 */ @Beta @GwtCompatible(emulated = true) @SuppressWarnings("rawtypes") // allow ungenerified Comparable types public abstract class ContiguousSet<C extends Comparable> extends ImmutableSortedSet<C> { /** * Returns a {@code ContiguousSet} containing the same values in the given domain * {@linkplain Range#contains contained} by the range. * * @throws IllegalArgumentException if neither range nor the domain has a lower bound, or if * neither has an upper bound * * @since 13.0 */ public static <C extends Comparable> ContiguousSet<C> create( Range<C> range, DiscreteDomain<C> domain) { checkNotNull(range); checkNotNull(domain); Range<C> effectiveRange = range; try { if (!range.hasLowerBound()) { effectiveRange = effectiveRange.intersection(Range.atLeast(domain.minValue())); } if (!range.hasUpperBound()) { effectiveRange = effectiveRange.intersection(Range.atMost(domain.maxValue())); } } catch (NoSuchElementException e) { throw new IllegalArgumentException(e); } // Per class spec, we are allowed to throw CCE if necessary boolean empty = effectiveRange.isEmpty() || Range.compareOrThrow( range.lowerBound.leastValueAbove(domain), range.upperBound.greatestValueBelow(domain)) > 0; return empty ? new EmptyContiguousSet<C>(domain) : new RegularContiguousSet<C>(effectiveRange, domain); } final DiscreteDomain<C> domain; ContiguousSet(DiscreteDomain<C> domain) { super(Ordering.natural()); this.domain = domain; } @Override public ContiguousSet<C> headSet(C toElement) { return headSetImpl(checkNotNull(toElement), false); } /** * @since 12.0 */ @GwtIncompatible("NavigableSet") @Override public ContiguousSet<C> headSet(C toElement, boolean inclusive) { return headSetImpl(checkNotNull(toElement), inclusive); } @Override public ContiguousSet<C> subSet(C fromElement, C toElement) { checkNotNull(fromElement); checkNotNull(toElement); checkArgument(comparator().compare(fromElement, toElement) <= 0); return subSetImpl(fromElement, true, toElement, false); } /** * @since 12.0 */ @GwtIncompatible("NavigableSet") @Override public ContiguousSet<C> subSet(C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) { checkNotNull(fromElement); checkNotNull(toElement); checkArgument(comparator().compare(fromElement, toElement) <= 0); return subSetImpl(fromElement, fromInclusive, toElement, toInclusive); } @Override public ContiguousSet<C> tailSet(C fromElement) { return tailSetImpl(checkNotNull(fromElement), true); } /** * @since 12.0 */ @GwtIncompatible("NavigableSet") @Override public ContiguousSet<C> tailSet(C fromElement, boolean inclusive) { return tailSetImpl(checkNotNull(fromElement), inclusive); } /* * These methods perform most headSet, subSet, and tailSet logic, besides parameter validation. */ /*@Override*/ abstract ContiguousSet<C> headSetImpl(C toElement, boolean inclusive); /*@Override*/ abstract ContiguousSet<C> subSetImpl(C fromElement, boolean fromInclusive, C toElement, boolean toInclusive); /*@Override*/ abstract ContiguousSet<C> tailSetImpl(C fromElement, boolean inclusive); /** * Returns the set of values that are contained in both this set and the other. * * <p>This method should always be used instead of * {@link Sets#intersection} for {@link ContiguousSet} instances. */ public abstract ContiguousSet<C> intersection(ContiguousSet<C> other); /** * Returns a range, closed on both ends, whose endpoints are the minimum and maximum values * contained in this set. This is equivalent to {@code range(CLOSED, CLOSED)}. * * @throws NoSuchElementException if this set is empty */ public abstract Range<C> range(); /** * Returns the minimal range with the given boundary types for which all values in this set are * {@linkplain Range#contains(Comparable) contained} within the range. * * <p>Note that this method will return ranges with unbounded endpoints if {@link BoundType#OPEN} * is requested for a domain minimum or maximum. For example, if {@code set} was created from the * range {@code [1..Integer.MAX_VALUE]} then {@code set.range(CLOSED, OPEN)} must return * {@code [1..∞)}. * * @throws NoSuchElementException if this set is empty */ public abstract Range<C> range(BoundType lowerBoundType, BoundType upperBoundType); /** Returns a short-hand representation of the contents such as {@code "[1..100]"}. */ @Override public String toString() { return range().toString(); } /** * Not supported. {@code ContiguousSet} instances are constructed with {@link #create}. This * method exists only to hide {@link ImmutableSet#builder} from consumers of {@code * ContiguousSet}. * * @throws UnsupportedOperationException always * @deprecated Use {@link #create}. */ @Deprecated public static <E> ImmutableSortedSet.Builder<E> builder() { throw new UnsupportedOperationException(); } }
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.checkArgument; 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.KeyPresentBehavior.ANY_PRESENT; import static com.google.common.collect.SortedLists.KeyPresentBehavior.FIRST_AFTER; import static com.google.common.collect.SortedLists.KeyPresentBehavior.FIRST_PRESENT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; /** * An immutable sorted set with one or more elements. TODO(jlevy): Consider * separate class for a single-element sorted set. * * @author Jared Levy * @author Louis Wasserman */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") final class RegularImmutableSortedSet<E> extends ImmutableSortedSet<E> { private transient final ImmutableList<E> elements; RegularImmutableSortedSet( ImmutableList<E> elements, Comparator<? super E> comparator) { super(comparator); this.elements = elements; checkArgument(!elements.isEmpty()); } @Override public UnmodifiableIterator<E> iterator() { return elements.iterator(); } @GwtIncompatible("NavigableSet") @Override public UnmodifiableIterator<E> descendingIterator() { return elements.reverse().iterator(); } @Override public boolean isEmpty() { return false; } @Override public int size() { return elements.size(); } @Override public boolean contains(Object o) { try { return o != null && unsafeBinarySearch(o) >= 0; } catch (ClassCastException e) { return false; } } @Override public boolean containsAll(Collection<?> targets) { // TODO(jlevy): For optimal performance, use a binary search when // targets.size() < size() / log(size()) // TODO(kevinb): see if we can share code with OrderedIterator after it // graduates from labs. if (targets instanceof Multiset) { targets = ((Multiset<?>) targets).elementSet(); } if (!SortedIterables.hasSameComparator(comparator(), targets) || (targets.size() <= 1)) { return super.containsAll(targets); } /* * If targets is a sorted set with the same comparator, containsAll can run * in O(n) time stepping through the two collections. */ PeekingIterator<E> thisIterator = Iterators.peekingIterator(iterator()); Iterator<?> thatIterator = targets.iterator(); Object target = thatIterator.next(); try { while (thisIterator.hasNext()) { int cmp = unsafeCompare(thisIterator.peek(), target); if (cmp < 0) { thisIterator.next(); } else if (cmp == 0) { if (!thatIterator.hasNext()) { return true; } target = thatIterator.next(); } else if (cmp > 0) { return false; } } } catch (NullPointerException e) { return false; } catch (ClassCastException e) { return false; } return false; } private int unsafeBinarySearch(Object key) throws ClassCastException { return Collections.binarySearch(elements, key, unsafeComparator()); } @Override boolean isPartialView() { return elements.isPartialView(); } @Override int copyIntoArray(Object[] dst, int offset) { return elements.copyIntoArray(dst, offset); } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (!(object instanceof Set)) { return false; } Set<?> that = (Set<?>) object; if (size() != that.size()) { return false; } if (SortedIterables.hasSameComparator(comparator, that)) { Iterator<?> otherIterator = that.iterator(); try { Iterator<E> iterator = iterator(); while (iterator.hasNext()) { Object element = iterator.next(); Object otherElement = otherIterator.next(); if (otherElement == null || unsafeCompare(element, otherElement) != 0) { return false; } } return true; } catch (ClassCastException e) { return false; } catch (NoSuchElementException e) { return false; // concurrent change to other set } } return this.containsAll(that); } @Override public E first() { return elements.get(0); } @Override public E last() { return elements.get(size() - 1); } @Override public E lower(E element) { int index = headIndex(element, false) - 1; return (index == -1) ? null : elements.get(index); } @Override public E floor(E element) { int index = headIndex(element, true) - 1; return (index == -1) ? null : elements.get(index); } @Override public E ceiling(E element) { int index = tailIndex(element, true); return (index == size()) ? null : elements.get(index); } @Override public E higher(E element) { int index = tailIndex(element, false); return (index == size()) ? null : elements.get(index); } @Override ImmutableSortedSet<E> headSetImpl(E toElement, boolean inclusive) { return getSubSet(0, headIndex(toElement, inclusive)); } int headIndex(E toElement, boolean inclusive) { return SortedLists.binarySearch( elements, checkNotNull(toElement), comparator(), inclusive ? FIRST_AFTER : FIRST_PRESENT, NEXT_HIGHER); } @Override ImmutableSortedSet<E> subSetImpl( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return tailSetImpl(fromElement, fromInclusive) .headSetImpl(toElement, toInclusive); } @Override ImmutableSortedSet<E> tailSetImpl(E fromElement, boolean inclusive) { return getSubSet(tailIndex(fromElement, inclusive), size()); } int tailIndex(E fromElement, boolean inclusive) { return SortedLists.binarySearch( elements, checkNotNull(fromElement), comparator(), inclusive ? FIRST_PRESENT : FIRST_AFTER, NEXT_HIGHER); } // 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; } ImmutableSortedSet<E> getSubSet(int newFromIndex, int newToIndex) { if (newFromIndex == 0 && newToIndex == size()) { return this; } else if (newFromIndex < newToIndex) { return new RegularImmutableSortedSet<E>( elements.subList(newFromIndex, newToIndex), comparator); } else { return emptySet(comparator); } } @Override int indexOf(@Nullable Object target) { if (target == null) { return -1; } int position; try { position = SortedLists.binarySearch(elements, target, unsafeComparator(), ANY_PRESENT, INVERTED_INSERTION_INDEX); } catch (ClassCastException e) { return -1; } return (position >= 0) ? position : -1; } @Override ImmutableList<E> createAsList() { return new ImmutableSortedAsList<E>(this, elements); } @Override ImmutableSortedSet<E> createDescendingSet() { return new RegularImmutableSortedSet<E>(elements.reverse(), Ordering.from(comparator).reverse()); } }
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 javax.annotation.Nullable; /** * Wraps an exception that occurred during a computation. * * @author Bob Lee * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public class ComputationException extends RuntimeException { /** * Creates a new instance with the given cause. */ public ComputationException(@Nullable Throwable cause) { super(cause); } 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 com.google.common.primitives.Ints; import javax.annotation.Nullable; /** * Static methods for implementing hash-based collections. * * @author Kevin Bourrillion * @author Jesse Wilson * @author Austin Appleby */ @GwtCompatible final class Hashing { private Hashing() {} private static final int C1 = 0xcc9e2d51; private static final int C2 = 0x1b873593; /* * This method was rewritten in Java from an intermediate step of the Murmur hash function in * http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp, which contained the * following header: * * MurmurHash3 was written by Austin Appleby, and is placed in the public domain. The author * hereby disclaims copyright to this source code. */ static int smear(int hashCode) { return C2 * Integer.rotateLeft(hashCode * C1, 15); } static int smearedHash(@Nullable Object o) { return smear((o == null) ? 0 : o.hashCode()); } private static int MAX_TABLE_SIZE = Ints.MAX_POWER_OF_TWO; static int closedTableSize(int expectedEntries, double loadFactor) { // Get the recommended table size. // Round down to the nearest power of 2. expectedEntries = Math.max(expectedEntries, 2); int tableSize = Integer.highestOneBit(expectedEntries); // Check to make sure that we will not exceed the maximum load factor. if (expectedEntries > (int) (loadFactor * tableSize)) { tableSize <<= 1; return (tableSize > 0) ? tableSize : MAX_TABLE_SIZE; } return tableSize; } static boolean needsResizing(int size, int tableSize, double loadFactor) { return size > loadFactor * tableSize && tableSize < MAX_TABLE_SIZE; } }
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.Preconditions; /** * A constraint that an element must satisfy in order to be added to a * collection. For example, {@link Constraints#notNull()}, which prevents a * collection from including any null elements, could be implemented like this: * <pre> {@code * * public Object checkElement(Object element) { * if (element == null) { * throw new NullPointerException(); * } * return element; * }}</pre> * * <p>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 element. 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. * * @see Constraints * @see MapConstraint * @author Mike Bostock * @since 3.0 * @deprecated Use {@link Preconditions} for basic checks. In place of * constrained collections, we encourage you to check your preconditions * explicitly instead of leaving that work to the collection implementation. * For the specific case of rejecting null, consider the immutable * collections. * This interface is scheduled for removal in Guava 16.0. */ @Beta @Deprecated @GwtCompatible public interface Constraint<E> { /** * Throws a suitable {@code RuntimeException} if the specified element 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. * * @param element the element to check * @return the provided element */ E checkElement(E element); /** * Returns a brief human readable description of this constraint, such as * "Not null" or "Positive number". */ @Override String toString(); }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import javax.annotation.Nullable; /** An ordering that treats {@code null} as less than all other values. */ @GwtCompatible(serializable = true) final class NullsFirstOrdering<T> extends Ordering<T> implements Serializable { final Ordering<? super T> ordering; NullsFirstOrdering(Ordering<? super T> ordering) { this.ordering = ordering; } @Override public int compare(@Nullable T left, @Nullable T right) { if (left == right) { return 0; } if (left == null) { return RIGHT_IS_GREATER; } if (right == null) { return LEFT_IS_GREATER; } return ordering.compare(left, right); } @Override public <S extends T> Ordering<S> reverse() { // ordering.reverse() might be optimized, so let it do its thing return ordering.reverse().nullsLast(); } @SuppressWarnings("unchecked") // still need the right way to explain this @Override public <S extends T> Ordering<S> nullsFirst() { return (Ordering<S>) this; } @Override public <S extends T> Ordering<S> nullsLast() { return ordering.nullsLast(); } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof NullsFirstOrdering) { NullsFirstOrdering<?> that = (NullsFirstOrdering<?>) object; return this.ordering.equals(that.ordering); } return false; } @Override public int hashCode() { return ordering.hashCode() ^ 957692532; // meaningless } @Override public String toString() { return ordering + ".nullsFirst()"; } 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 static com.google.common.collect.Multisets.checkNonnegative; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.primitives.Ints; import java.io.InvalidObjectException; import java.io.ObjectStreamException; import java.io.Serializable; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * Basic implementation of {@code Multiset<E>} backed by an instance of {@code * Map<E, Count>}. * * <p>For serialization to work, the subclass must specify explicit {@code * readObject} and {@code writeObject} methods. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) abstract class AbstractMapBasedMultiset<E> extends AbstractMultiset<E> implements Serializable { private transient Map<E, Count> backingMap; /* * Cache the size for efficiency. Using a long lets us avoid the need for * overflow checking and ensures that size() will function correctly even if * the multiset had once been larger than Integer.MAX_VALUE. */ private transient long size; /** Standard constructor. */ protected AbstractMapBasedMultiset(Map<E, Count> backingMap) { this.backingMap = checkNotNull(backingMap); this.size = super.size(); } /** Used during deserialization only. The backing map must be empty. */ void setBackingMap(Map<E, Count> backingMap) { this.backingMap = backingMap; } // Required Implementations /** * {@inheritDoc} * * <p>Invoking {@link Multiset.Entry#getCount} on an entry in the returned * set always returns the current count of that element in the multiset, as * opposed to the count at the time the entry was retrieved. */ @Override public Set<Multiset.Entry<E>> entrySet() { return super.entrySet(); } @Override Iterator<Entry<E>> entryIterator() { final Iterator<Map.Entry<E, Count>> backingEntries = backingMap.entrySet().iterator(); return new Iterator<Multiset.Entry<E>>() { Map.Entry<E, Count> toRemove; @Override public boolean hasNext() { return backingEntries.hasNext(); } @Override public Multiset.Entry<E> next() { final Map.Entry<E, Count> mapEntry = backingEntries.next(); toRemove = mapEntry; return new Multisets.AbstractEntry<E>() { @Override public E getElement() { return mapEntry.getKey(); } @Override public int getCount() { Count count = mapEntry.getValue(); if (count == null || count.get() == 0) { Count frequency = backingMap.get(getElement()); if (frequency != null) { return frequency.get(); } } return (count == null) ? 0 : count.get(); } }; } @Override public void remove() { Iterators.checkRemove(toRemove != null); size -= toRemove.getValue().getAndSet(0); backingEntries.remove(); toRemove = null; } }; } @Override public void clear() { for (Count frequency : backingMap.values()) { frequency.set(0); } backingMap.clear(); size = 0L; } @Override int distinctElements() { return backingMap.size(); } // Optimizations - Query Operations @Override public int size() { return Ints.saturatedCast(size); } @Override public Iterator<E> iterator() { return new MapBasedMultisetIterator(); } /* * Not subclassing AbstractMultiset$MultisetIterator because next() needs to * retrieve the Map.Entry<E, Count> entry, which can then be used for * a more efficient remove() call. */ private class MapBasedMultisetIterator implements Iterator<E> { final Iterator<Map.Entry<E, Count>> entryIterator; Map.Entry<E, Count> currentEntry; int occurrencesLeft; boolean canRemove; MapBasedMultisetIterator() { this.entryIterator = backingMap.entrySet().iterator(); } @Override public boolean hasNext() { return occurrencesLeft > 0 || entryIterator.hasNext(); } @Override public E next() { if (occurrencesLeft == 0) { currentEntry = entryIterator.next(); occurrencesLeft = currentEntry.getValue().get(); } occurrencesLeft--; canRemove = true; return currentEntry.getKey(); } @Override public void remove() { checkState(canRemove, "no calls to next() since the last call to remove()"); int frequency = currentEntry.getValue().get(); if (frequency <= 0) { throw new ConcurrentModificationException(); } if (currentEntry.getValue().addAndGet(-1) == 0) { entryIterator.remove(); } size--; canRemove = false; } } @Override public int count(@Nullable Object element) { Count frequency = Maps.safeGet(backingMap, element); return (frequency == null) ? 0 : frequency.get(); } // Optional Operations - Modification Operations /** * {@inheritDoc} * * @throws IllegalArgumentException if the call would result in more than * {@link Integer#MAX_VALUE} occurrences of {@code element} in this * multiset. */ @Override public int add(@Nullable E element, int occurrences) { if (occurrences == 0) { return count(element); } checkArgument( occurrences > 0, "occurrences cannot be negative: %s", occurrences); Count frequency = backingMap.get(element); int oldCount; if (frequency == null) { oldCount = 0; backingMap.put(element, new Count(occurrences)); } else { oldCount = frequency.get(); long newCount = (long) oldCount + (long) occurrences; checkArgument(newCount <= Integer.MAX_VALUE, "too many occurrences: %s", newCount); frequency.getAndAdd(occurrences); } size += occurrences; return oldCount; } @Override public int remove(@Nullable Object element, int occurrences) { if (occurrences == 0) { return count(element); } checkArgument( occurrences > 0, "occurrences cannot be negative: %s", occurrences); Count frequency = backingMap.get(element); if (frequency == null) { return 0; } int oldCount = frequency.get(); int numberRemoved; if (oldCount > occurrences) { numberRemoved = occurrences; } else { numberRemoved = oldCount; backingMap.remove(element); } frequency.addAndGet(-numberRemoved); size -= numberRemoved; return oldCount; } // Roughly a 33% performance improvement over AbstractMultiset.setCount(). @Override public int setCount(@Nullable E element, int count) { checkNonnegative(count, "count"); Count existingCounter; int oldCount; if (count == 0) { existingCounter = backingMap.remove(element); oldCount = getAndSet(existingCounter, count); } else { existingCounter = backingMap.get(element); oldCount = getAndSet(existingCounter, count); if (existingCounter == null) { backingMap.put(element, new Count(count)); } } size += (count - oldCount); return oldCount; } private static int getAndSet(Count i, int count) { if (i == null) { return 0; } return i.getAndSet(count); } // Don't allow default serialization. @GwtIncompatible("java.io.ObjectStreamException") @SuppressWarnings("unused") // actually used during deserialization private void readObjectNoData() throws ObjectStreamException { throw new InvalidObjectException("Stream data required"); } @GwtIncompatible("not needed in emulated source.") private static final long serialVersionUID = -2250766705698539974L; }
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 com.google.common.annotations.GwtIncompatible; import com.google.common.base.Equivalence; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.collect.MapMaker.RemovalListener; import com.google.common.collect.MapMaker.RemovalNotification; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; /** * A class exactly like {@link MapMaker}, except restricted in the types of maps it can build. * For the most part, you should probably just ignore the existence of this class. * * @param <K0> the base type for all key types of maps built by this map maker * @param <V0> the base type for all value types of maps built by this map maker * @author Kevin Bourrillion * @since 7.0 * @deprecated This class existed only to support the generic paramterization necessary for the * caching functionality in {@code MapMaker}. That functionality has been moved to {@link * com.google.common.cache.CacheBuilder}, which is a properly generified class and thus needs no * "Generic" equivalent; simple use {@code CacheBuilder} naturally. For general migration * instructions, see the <a * href="http://code.google.com/p/guava-libraries/wiki/MapMakerMigration">MapMaker Migration * Guide</a>. This class is scheduled for removal in Guava 16.0. */ @Beta @Deprecated @GwtCompatible(emulated = true) public abstract class GenericMapMaker<K0, V0> { @GwtIncompatible("To be supported") enum NullListener implements RemovalListener<Object, Object> { INSTANCE; @Override public void onRemoval(RemovalNotification<Object, Object> notification) {} } // Set by MapMaker, but sits in this class to preserve the type relationship @GwtIncompatible("To be supported") RemovalListener<K0, V0> removalListener; // No subclasses but our own GenericMapMaker() {} /** * See {@link MapMaker#keyEquivalence}. */ @GwtIncompatible("To be supported") abstract GenericMapMaker<K0, V0> keyEquivalence(Equivalence<Object> equivalence); /** * See {@link MapMaker#initialCapacity}. */ public abstract GenericMapMaker<K0, V0> initialCapacity(int initialCapacity); /** * See {@link MapMaker#maximumSize}. */ abstract GenericMapMaker<K0, V0> maximumSize(int maximumSize); /** * See {@link MapMaker#concurrencyLevel}. */ public abstract GenericMapMaker<K0, V0> concurrencyLevel(int concurrencyLevel); /** * See {@link MapMaker#weakKeys}. */ @GwtIncompatible("java.lang.ref.WeakReference") public abstract GenericMapMaker<K0, V0> weakKeys(); /** * See {@link MapMaker#weakValues}. */ @GwtIncompatible("java.lang.ref.WeakReference") public abstract GenericMapMaker<K0, V0> weakValues(); /** * See {@link MapMaker#softValues}. * * @deprecated Caching functionality in {@code MapMaker} has been moved to {@link * com.google.common.cache.CacheBuilder}, with {@link #softValues} being replaced by {@link * com.google.common.cache.CacheBuilder#softValues}. Note that {@code CacheBuilder} is simply * an enhanced API for an implementation which was branched from {@code MapMaker}. <b>This * method is scheduled for deletion in August 2014.</b> */ @Deprecated @GwtIncompatible("java.lang.ref.SoftReference") public abstract GenericMapMaker<K0, V0> softValues(); /** * See {@link MapMaker#expireAfterWrite}. */ abstract GenericMapMaker<K0, V0> expireAfterWrite(long duration, TimeUnit unit); /** * See {@link MapMaker#expireAfterAccess}. */ @GwtIncompatible("To be supported") abstract GenericMapMaker<K0, V0> expireAfterAccess(long duration, TimeUnit unit); /* * Note that MapMaker's removalListener() is not here, because once you're interacting with a * GenericMapMaker you've already called that, and shouldn't be calling it again. */ @SuppressWarnings("unchecked") // safe covariant cast @GwtIncompatible("To be supported") <K extends K0, V extends V0> RemovalListener<K, V> getRemovalListener() { return (RemovalListener<K, V>) Objects.firstNonNull(removalListener, NullListener.INSTANCE); } /** * See {@link MapMaker#makeMap}. */ public abstract <K extends K0, V extends V0> ConcurrentMap<K, V> makeMap(); /** * See {@link MapMaker#makeCustomMap}. */ @GwtIncompatible("MapMakerInternalMap") abstract <K, V> MapMakerInternalMap<K, V> makeCustomMap(); /** * See {@link MapMaker#makeComputingMap}. */ @Deprecated abstract <K extends K0, V extends V0> ConcurrentMap<K, V> makeComputingMap( Function<? super K, ? extends V> computingFunction); }
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 java.io.Serializable; import javax.annotation.Nullable; /** * A mutable value of type {@code int}, for multisets to use in tracking counts of values. * * @author Louis Wasserman */ @GwtCompatible final class Count implements Serializable { private int value; Count(int value) { this.value = value; } public int get() { return value; } public int getAndAdd(int delta) { int result = value; value = result + delta; return result; } public int addAndGet(int delta) { return value += delta; } public void set(int newValue) { value = newValue; } public int getAndSet(int newValue) { int result = value; value = newValue; return result; } @Override public int hashCode() { return value; } @Override public boolean equals(@Nullable Object obj) { return obj instanceof Count && ((Count) obj).value == value; } @Override public String toString() { return Integer.toString(value); } }
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 com.google.common.annotations.VisibleForTesting; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Implementation of {@code Multimap} that uses an {@code ArrayList} to store * the values for a given key. A {@link HashMap} associates each key with an * {@link ArrayList} of values. * * <p>When iterating through the collections supplied by this class, the * ordering of values for a given key agrees with the order in which the values * were added. * * <p>This multimap allows duplicate key-value pairs. After adding a new * key-value pair equal to an existing key-value pair, the {@code * ArrayListMultimap} will contain entries for both the new value and the old * value. * * <p>Keys and values may be null. All optional multimap methods are supported, * and all returned views are modifiable. * * <p>The lists returned by {@link #get}, {@link #removeAll}, and {@link * #replaceValues} all implement {@link java.util.RandomAccess}. * * <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 Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public final class ArrayListMultimap<K, V> extends AbstractListMultimap<K, V> { // Default from ArrayList private static final int DEFAULT_VALUES_PER_KEY = 3; @VisibleForTesting transient int expectedValuesPerKey; /** * Creates a new, empty {@code ArrayListMultimap} with the default initial * capacities. */ public static <K, V> ArrayListMultimap<K, V> create() { return new ArrayListMultimap<K, V>(); } /** * Constructs an empty {@code ArrayListMultimap} with enough capacity to hold * the specified numbers of keys and values without resizing. * * @param expectedKeys the expected number of distinct keys * @param expectedValuesPerKey the expected average number of values per key * @throws IllegalArgumentException if {@code expectedKeys} or {@code * expectedValuesPerKey} is negative */ public static <K, V> ArrayListMultimap<K, V> create( int expectedKeys, int expectedValuesPerKey) { return new ArrayListMultimap<K, V>(expectedKeys, expectedValuesPerKey); } /** * Constructs an {@code ArrayListMultimap} with the same mappings as the * specified multimap. * * @param multimap the multimap whose contents are copied to this multimap */ public static <K, V> ArrayListMultimap<K, V> create( Multimap<? extends K, ? extends V> multimap) { return new ArrayListMultimap<K, V>(multimap); } private ArrayListMultimap() { super(new HashMap<K, Collection<V>>()); expectedValuesPerKey = DEFAULT_VALUES_PER_KEY; } private ArrayListMultimap(int expectedKeys, int expectedValuesPerKey) { super(Maps.<K, Collection<V>>newHashMapWithExpectedSize(expectedKeys)); checkArgument(expectedValuesPerKey >= 0); this.expectedValuesPerKey = expectedValuesPerKey; } private ArrayListMultimap(Multimap<? extends K, ? extends V> multimap) { this(multimap.keySet().size(), (multimap instanceof ArrayListMultimap) ? ((ArrayListMultimap<?, ?>) multimap).expectedValuesPerKey : DEFAULT_VALUES_PER_KEY); putAll(multimap); } /** * Creates a new, empty {@code ArrayList} to hold the collection of values for * an arbitrary key. */ @Override List<V> createCollection() { return new ArrayList<V>(expectedValuesPerKey); } /** * Reduces the memory used by this {@code ArrayListMultimap}, if feasible. */ public void trimToSize() { for (Collection<V> collection : backingMap().values()) { ArrayList<V> arrayList = (ArrayList<V>) collection; arrayList.trimToSize(); } } /** * @serialData expectedValuesPerKey, number of distinct keys, and then for * each distinct key: the key, number of values for that key, and the * key's values */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeInt(expectedValuesPerKey); Serialization.writeMultimap(this, stream); } @GwtIncompatible("java.io.ObjectOutputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); expectedValuesPerKey = stream.readInt(); int distinctKeys = Serialization.readCount(stream); Map<K, Collection<V>> map = Maps.newHashMapWithExpectedSize(distinctKeys); setMap(map); Serialization.populateMultimap(this, stream, distinctKeys); } @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 com.google.common.base.Preconditions; import java.util.Set; import javax.annotation.Nullable; /** * Implementation of {@link ImmutableSet} with exactly one element. * * @author Kevin Bourrillion * @author Nick Kralevich */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // uses writeReplace(), not default serialization final class SingletonImmutableSet<E> extends ImmutableSet<E> { final transient E element; // This is transient because it will be recalculated on the first // call to hashCode(). // // A race condition is avoided since threads will either see that the value // is zero and recalculate it themselves, or two threads will see it at // the same time, and both recalculate it. If the cachedHashCode is 0, // it will always be recalculated, unfortunately. private transient int cachedHashCode; SingletonImmutableSet(E element) { this.element = Preconditions.checkNotNull(element); } SingletonImmutableSet(E element, int hashCode) { // Guaranteed to be non-null by the presence of the pre-computed hash code. this.element = element; cachedHashCode = hashCode; } @Override public int size() { return 1; } @Override public boolean isEmpty() { return false; } @Override public boolean contains(Object target) { return element.equals(target); } @Override public UnmodifiableIterator<E> iterator() { return Iterators.singletonIterator(element); } @Override boolean isPartialView() { return false; } @Override int copyIntoArray(Object[] dst, int offset) { dst[offset] = element; return offset + 1; } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof Set) { Set<?> that = (Set<?>) object; return that.size() == 1 && element.equals(that.iterator().next()); } return false; } @Override public final int hashCode() { // Racy single-check. int code = cachedHashCode; if (code == 0) { cachedHashCode = code = element.hashCode(); } return code; } @Override boolean isHashCodeFast() { return cachedHashCode != 0; } @Override public String toString() { String elementToString = element.toString(); return new StringBuilder(elementToString.length() + 2) .append('[') .append(elementToString) .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 com.google.common.annotations.GwtCompatible; import java.util.SortedMap; /** * An object representing the differences between two sorted maps. * * @author Louis Wasserman * @since 8.0 */ @GwtCompatible public interface SortedMapDifference<K, V> extends MapDifference<K, V> { @Override SortedMap<K, V> entriesOnlyOnLeft(); @Override SortedMap<K, V> entriesOnlyOnRight(); @Override SortedMap<K, V> entriesInCommon(); @Override SortedMap<K, ValueDifference<V>> entriesDiffering(); }
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.annotations.GwtIncompatible; import java.io.Serializable; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; /** * An empty contiguous set. * * @author Gregory Kick */ @GwtCompatible(emulated = true) @SuppressWarnings("unchecked") // allow ungenerified Comparable types final class EmptyContiguousSet<C extends Comparable> extends ContiguousSet<C> { EmptyContiguousSet(DiscreteDomain<C> domain) { super(domain); } @Override public C first() { throw new NoSuchElementException(); } @Override public C last() { throw new NoSuchElementException(); } @Override public int size() { return 0; } @Override public ContiguousSet<C> intersection(ContiguousSet<C> other) { return this; } @Override public Range<C> range() { throw new NoSuchElementException(); } @Override public Range<C> range(BoundType lowerBoundType, BoundType upperBoundType) { throw new NoSuchElementException(); } @Override ContiguousSet<C> headSetImpl(C toElement, boolean inclusive) { return this; } @Override ContiguousSet<C> subSetImpl( C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) { return this; } @Override ContiguousSet<C> tailSetImpl(C fromElement, boolean fromInclusive) { return this; } @GwtIncompatible("not used by GWT emulation") @Override int indexOf(Object target) { return -1; } @Override public UnmodifiableIterator<C> iterator() { return Iterators.emptyIterator(); } @GwtIncompatible("NavigableSet") @Override public UnmodifiableIterator<C> descendingIterator() { return Iterators.emptyIterator(); } @Override boolean isPartialView() { return false; } @Override public boolean isEmpty() { return true; } @Override public ImmutableList<C> asList() { return ImmutableList.of(); } @Override public String toString() { return "[]"; } @Override public boolean equals(@Nullable Object object) { if (object instanceof Set) { Set<?> that = (Set<?>) object; return that.isEmpty(); } return false; } @Override public int hashCode() { return 0; } @GwtIncompatible("serialization") private static final class SerializedForm<C extends Comparable> implements Serializable { private final DiscreteDomain<C> domain; private SerializedForm(DiscreteDomain<C> domain) { this.domain = domain; } private Object readResolve() { return new EmptyContiguousSet<C>(domain); } private static final long serialVersionUID = 0; } @GwtIncompatible("serialization") @Override Object writeReplace() { return new SerializedForm<C>(domain); } @GwtIncompatible("NavigableSet") ImmutableSortedSet<C> createDescendingSet() { return new EmptyImmutableSortedSet<C>(Ordering.natural().reverse()); } }
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 java.util.Iterator; import java.util.Map; import java.util.Set; /** * Workaround for * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6312706"> * EnumMap bug</a>. If you want to pass an {@code EnumMap}, with the * intention of using its {@code entrySet()} method, you should * wrap the {@code EnumMap} in this class instead. * * <p>This class is not thread-safe even if the underlying map is. * * @author Dimitris Andreou */ @GwtCompatible final class WellBehavedMap<K, V> extends ForwardingMap<K, V> { private final Map<K, V> delegate; private Set<Entry<K, V>> entrySet; private WellBehavedMap(Map<K, V> delegate) { this.delegate = delegate; } /** * Wraps the given map into a {@code WellBehavedEntriesMap}, which * intercepts its {@code entrySet()} method by taking the * {@code Set<K> keySet()} and transforming it to * {@code Set<Entry<K, V>>}. All other invocations are delegated as-is. */ static <K, V> WellBehavedMap<K, V> wrap(Map<K, V> delegate) { return new WellBehavedMap<K, V>(delegate); } @Override protected Map<K, V> delegate() { return delegate; } @Override public Set<Entry<K, V>> entrySet() { Set<Entry<K, V>> es = entrySet; if (es != null) { return es; } return entrySet = new EntrySet(); } private final class EntrySet extends Maps.EntrySet<K, V> { @Override Map<K, V> map() { return WellBehavedMap.this; } @Override public Iterator<Entry<K, V>> iterator() { return new TransformedIterator<K, Entry<K, V>>(keySet().iterator()) { @Override Entry<K, V> transform(final K key) { return new AbstractMapEntry<K, V>() { @Override public K getKey() { return key; } @Override public V getValue() { return get(key); } @Override public V setValue(V value) { return put(key, value); } }; } }; } } }
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.AbstractMap; import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; /** * A {@link BiMap} backed by two hash tables. This implementation allows null keys and values. A * {@code HashBiMap} and its inverse are both serializable. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap"> {@code BiMap} * </a>. * * @author Louis Wasserman * @author Mike Bostock * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class HashBiMap<K, V> extends AbstractMap<K, V> implements BiMap<K, V>, Serializable { /** * Returns a new, empty {@code HashBiMap} with the default initial capacity (16). */ public static <K, V> HashBiMap<K, V> create() { return create(16); } /** * Constructs a new, empty bimap with the specified expected size. * * @param expectedSize the expected number of entries * @throws IllegalArgumentException if the specified expected size is negative */ public static <K, V> HashBiMap<K, V> create(int expectedSize) { return new HashBiMap<K, V>(expectedSize); } /** * Constructs a new bimap containing initial values from {@code map}. The bimap is created with an * initial capacity sufficient to hold the mappings in the specified map. */ public static <K, V> HashBiMap<K, V> create(Map<? extends K, ? extends V> map) { HashBiMap<K, V> bimap = create(map.size()); bimap.putAll(map); return bimap; } private static final class BiEntry<K, V> extends ImmutableEntry<K, V> { final int keyHash; final int valueHash; @Nullable BiEntry<K, V> nextInKToVBucket; @Nullable BiEntry<K, V> nextInVToKBucket; BiEntry(K key, int keyHash, V value, int valueHash) { super(key, value); this.keyHash = keyHash; this.valueHash = valueHash; } } private static final double LOAD_FACTOR = 1.0; private transient BiEntry<K, V>[] hashTableKToV; private transient BiEntry<K, V>[] hashTableVToK; private transient int size; private transient int mask; private transient int modCount; private HashBiMap(int expectedSize) { init(expectedSize); } private void init(int expectedSize) { checkArgument(expectedSize >= 0, "expectedSize must be >= 0 but was %s", expectedSize); int tableSize = Hashing.closedTableSize(expectedSize, LOAD_FACTOR); this.hashTableKToV = createTable(tableSize); this.hashTableVToK = createTable(tableSize); this.mask = tableSize - 1; this.modCount = 0; this.size = 0; } /** * Finds and removes {@code entry} from the bucket linked lists in both the * key-to-value direction and the value-to-key direction. */ private void delete(BiEntry<K, V> entry) { int keyBucket = entry.keyHash & mask; BiEntry<K, V> prevBucketEntry = null; for (BiEntry<K, V> bucketEntry = hashTableKToV[keyBucket]; true; bucketEntry = bucketEntry.nextInKToVBucket) { if (bucketEntry == entry) { if (prevBucketEntry == null) { hashTableKToV[keyBucket] = entry.nextInKToVBucket; } else { prevBucketEntry.nextInKToVBucket = entry.nextInKToVBucket; } break; } prevBucketEntry = bucketEntry; } int valueBucket = entry.valueHash & mask; prevBucketEntry = null; for (BiEntry<K, V> bucketEntry = hashTableVToK[valueBucket];; bucketEntry = bucketEntry.nextInVToKBucket) { if (bucketEntry == entry) { if (prevBucketEntry == null) { hashTableVToK[valueBucket] = entry.nextInVToKBucket; } else { prevBucketEntry.nextInVToKBucket = entry.nextInVToKBucket; } break; } prevBucketEntry = bucketEntry; } size--; modCount++; } private void insert(BiEntry<K, V> entry) { int keyBucket = entry.keyHash & mask; entry.nextInKToVBucket = hashTableKToV[keyBucket]; hashTableKToV[keyBucket] = entry; int valueBucket = entry.valueHash & mask; entry.nextInVToKBucket = hashTableVToK[valueBucket]; hashTableVToK[valueBucket] = entry; size++; modCount++; } private static int hash(@Nullable Object o) { return Hashing.smear((o == null) ? 0 : o.hashCode()); } private BiEntry<K, V> seekByKey(@Nullable Object key, int keyHash) { for (BiEntry<K, V> entry = hashTableKToV[keyHash & mask]; entry != null; entry = entry.nextInKToVBucket) { if (keyHash == entry.keyHash && Objects.equal(key, entry.key)) { return entry; } } return null; } private BiEntry<K, V> seekByValue(@Nullable Object value, int valueHash) { for (BiEntry<K, V> entry = hashTableVToK[valueHash & mask]; entry != null; entry = entry.nextInVToKBucket) { if (valueHash == entry.valueHash && Objects.equal(value, entry.value)) { return entry; } } return null; } @Override public boolean containsKey(@Nullable Object key) { return seekByKey(key, hash(key)) != null; } @Override public boolean containsValue(@Nullable Object value) { return seekByValue(value, hash(value)) != null; } @Nullable @Override public V get(@Nullable Object key) { BiEntry<K, V> entry = seekByKey(key, hash(key)); return (entry == null) ? null : entry.value; } @Override public V put(@Nullable K key, @Nullable V value) { return put(key, value, false); } @Override public V forcePut(@Nullable K key, @Nullable V value) { return put(key, value, true); } private V put(@Nullable K key, @Nullable V value, boolean force) { int keyHash = hash(key); int valueHash = hash(value); BiEntry<K, V> oldEntryForKey = seekByKey(key, keyHash); if (oldEntryForKey != null && valueHash == oldEntryForKey.valueHash && Objects.equal(value, oldEntryForKey.value)) { return value; } BiEntry<K, V> oldEntryForValue = seekByValue(value, valueHash); if (oldEntryForValue != null) { if (force) { delete(oldEntryForValue); } else { throw new IllegalArgumentException("value already present: " + value); } } if (oldEntryForKey != null) { delete(oldEntryForKey); } BiEntry<K, V> newEntry = new BiEntry<K, V>(key, keyHash, value, valueHash); insert(newEntry); rehashIfNecessary(); return (oldEntryForKey == null) ? null : oldEntryForKey.value; } @Nullable private K putInverse(@Nullable V value, @Nullable K key, boolean force) { int valueHash = hash(value); int keyHash = hash(key); BiEntry<K, V> oldEntryForValue = seekByValue(value, valueHash); if (oldEntryForValue != null && keyHash == oldEntryForValue.keyHash && Objects.equal(key, oldEntryForValue.key)) { return key; } BiEntry<K, V> oldEntryForKey = seekByKey(key, keyHash); if (oldEntryForKey != null) { if (force) { delete(oldEntryForKey); } else { throw new IllegalArgumentException("value already present: " + key); } } if (oldEntryForValue != null) { delete(oldEntryForValue); } BiEntry<K, V> newEntry = new BiEntry<K, V>(key, keyHash, value, valueHash); insert(newEntry); rehashIfNecessary(); return (oldEntryForValue == null) ? null : oldEntryForValue.key; } private void rehashIfNecessary() { BiEntry<K, V>[] oldKToV = hashTableKToV; if (Hashing.needsResizing(size, oldKToV.length, LOAD_FACTOR)) { int newTableSize = oldKToV.length * 2; this.hashTableKToV = createTable(newTableSize); this.hashTableVToK = createTable(newTableSize); this.mask = newTableSize - 1; this.size = 0; for (int bucket = 0; bucket < oldKToV.length; bucket++) { BiEntry<K, V> entry = oldKToV[bucket]; while (entry != null) { BiEntry<K, V> nextEntry = entry.nextInKToVBucket; insert(entry); entry = nextEntry; } } this.modCount++; } } @SuppressWarnings("unchecked") private BiEntry<K, V>[] createTable(int length) { return new BiEntry[length]; } @Override public V remove(@Nullable Object key) { BiEntry<K, V> entry = seekByKey(key, hash(key)); if (entry == null) { return null; } else { delete(entry); return entry.value; } } @Override public void clear() { size = 0; Arrays.fill(hashTableKToV, null); Arrays.fill(hashTableVToK, null); modCount++; } @Override public int size() { return size; } abstract class Itr<T> implements Iterator<T> { int nextBucket = 0; BiEntry<K, V> next = null; BiEntry<K, V> toRemove = null; int expectedModCount = modCount; private void checkForConcurrentModification() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } @Override public boolean hasNext() { checkForConcurrentModification(); if (next != null) { return true; } while (nextBucket < hashTableKToV.length) { if (hashTableKToV[nextBucket] != null) { next = hashTableKToV[nextBucket++]; return true; } nextBucket++; } return false; } @Override public T next() { checkForConcurrentModification(); if (!hasNext()) { throw new NoSuchElementException(); } BiEntry<K, V> entry = next; next = entry.nextInKToVBucket; toRemove = entry; return output(entry); } @Override public void remove() { checkForConcurrentModification(); checkState(toRemove != null, "Only one remove() call allowed per call to next"); delete(toRemove); expectedModCount = modCount; toRemove = null; } abstract T output(BiEntry<K, V> entry); } @Override public Set<K> keySet() { return new KeySet(); } private final class KeySet extends Maps.KeySet<K, V> { KeySet() { super(HashBiMap.this); } @Override public Iterator<K> iterator() { return new Itr<K>() { @Override K output(BiEntry<K, V> entry) { return entry.key; } }; } @Override public boolean remove(@Nullable Object o) { BiEntry<K, V> entry = seekByKey(o, hash(o)); if (entry == null) { return false; } else { delete(entry); return true; } } } @Override public Set<V> values() { return inverse().keySet(); } @Override public Set<Entry<K, V>> entrySet() { return new EntrySet(); } private final class EntrySet extends Maps.EntrySet<K, V> { @Override Map<K, V> map() { return HashBiMap.this; } @Override public Iterator<Entry<K, V>> iterator() { return new Itr<Entry<K, V>>() { @Override Entry<K, V> output(BiEntry<K, V> entry) { return new MapEntry(entry); } class MapEntry extends AbstractMapEntry<K, V> { BiEntry<K, V> delegate; MapEntry(BiEntry<K, V> entry) { this.delegate = entry; } @Override public K getKey() { return delegate.key; } @Override public V getValue() { return delegate.value; } @Override public V setValue(V value) { V oldValue = delegate.value; int valueHash = hash(value); if (valueHash == delegate.valueHash && Objects.equal(value, oldValue)) { return value; } checkArgument( seekByValue(value, valueHash) == null, "value already present: %s", value); delete(delegate); BiEntry<K, V> newEntry = new BiEntry<K, V>(delegate.key, delegate.keyHash, value, valueHash); insert(newEntry); expectedModCount = modCount; if (toRemove == delegate) { toRemove = newEntry; } delegate = newEntry; return oldValue; } } }; } } private transient BiMap<V, K> inverse; @Override public BiMap<V, K> inverse() { return (inverse == null) ? inverse = new Inverse() : inverse; } private final class Inverse extends AbstractMap<V, K> implements BiMap<V, K>, Serializable { BiMap<K, V> forward() { return HashBiMap.this; } @Override public int size() { return size; } @Override public void clear() { forward().clear(); } @Override public boolean containsKey(@Nullable Object value) { return forward().containsValue(value); } @Override public K get(@Nullable Object value) { BiEntry<K, V> entry = seekByValue(value, hash(value)); return (entry == null) ? null : entry.key; } @Override public K put(@Nullable V value, @Nullable K key) { return putInverse(value, key, false); } @Override public K forcePut(@Nullable V value, @Nullable K key) { return putInverse(value, key, true); } @Override public K remove(@Nullable Object value) { BiEntry<K, V> entry = seekByValue(value, hash(value)); if (entry == null) { return null; } else { delete(entry); return entry.key; } } @Override public BiMap<K, V> inverse() { return forward(); } @Override public Set<V> keySet() { return new InverseKeySet(); } private final class InverseKeySet extends Maps.KeySet<V, K> { InverseKeySet() { super(Inverse.this); } @Override public boolean remove(@Nullable Object o) { BiEntry<K, V> entry = seekByValue(o, hash(o)); if (entry == null) { return false; } else { delete(entry); return true; } } @Override public Iterator<V> iterator() { return new Itr<V>() { @Override V output(BiEntry<K, V> entry) { return entry.value; } }; } } @Override public Set<K> values() { return forward().keySet(); } @Override public Set<Entry<V, K>> entrySet() { return new Maps.EntrySet<V, K>() { @Override Map<V, K> map() { return Inverse.this; } @Override public Iterator<Entry<V, K>> iterator() { return new Itr<Entry<V, K>>() { @Override Entry<V, K> output(BiEntry<K, V> entry) { return new InverseEntry(entry); } class InverseEntry extends AbstractMapEntry<V, K> { BiEntry<K, V> delegate; InverseEntry(BiEntry<K, V> entry) { this.delegate = entry; } @Override public V getKey() { return delegate.value; } @Override public K getValue() { return delegate.key; } @Override public K setValue(K key) { K oldKey = delegate.key; int keyHash = hash(key); if (keyHash == delegate.keyHash && Objects.equal(key, oldKey)) { return key; } checkArgument(seekByKey(key, keyHash) == null, "value already present: %s", key); delete(delegate); BiEntry<K, V> newEntry = new BiEntry<K, V>(key, keyHash, delegate.value, delegate.valueHash); insert(newEntry); expectedModCount = modCount; // This is safe because entries can only get bumped up to earlier in the iteration, // so they can't get revisited. return oldKey; } } }; } }; } Object writeReplace() { return new InverseSerializedForm<K, V>(HashBiMap.this); } } private static final class InverseSerializedForm<K, V> implements Serializable { private final HashBiMap<K, V> bimap; InverseSerializedForm(HashBiMap<K, V> bimap) { this.bimap = bimap; } Object readResolve() { return bimap.inverse(); } } /** * @serialData the number of entries, first key, first value, second key, second value, and so on. */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); Serialization.writeMap(this, stream); } @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); int size = Serialization.readCount(stream); init(size); Serialization.populateMap(this, stream, size); } @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 com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.util.Collection; import java.util.Comparator; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; /** * An empty immutable sorted set. * * @author Jared Levy */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // uses writeReplace(), not default serialization class EmptyImmutableSortedSet<E> extends ImmutableSortedSet<E> { EmptyImmutableSortedSet(Comparator<? super E> comparator) { super(comparator); } @Override public int size() { return 0; } @Override public boolean isEmpty() { return true; } @Override public boolean contains(@Nullable Object target) { return false; } @Override public boolean containsAll(Collection<?> targets) { return targets.isEmpty(); } @Override public UnmodifiableIterator<E> iterator() { return Iterators.emptyIterator(); } @GwtIncompatible("NavigableSet") @Override public UnmodifiableIterator<E> descendingIterator() { return Iterators.emptyIterator(); } @Override boolean isPartialView() { return false; } @Override public ImmutableList<E> asList() { return ImmutableList.of(); } @Override int copyIntoArray(Object[] dst, int offset) { return offset; } @Override public boolean equals(@Nullable Object object) { if (object instanceof Set) { Set<?> that = (Set<?>) object; return that.isEmpty(); } return false; } @Override public int hashCode() { return 0; } @Override public String toString() { return "[]"; } @Override public E first() { throw new NoSuchElementException(); } @Override public E last() { throw new NoSuchElementException(); } @Override ImmutableSortedSet<E> headSetImpl(E toElement, boolean inclusive) { return this; } @Override ImmutableSortedSet<E> subSetImpl( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return this; } @Override ImmutableSortedSet<E> tailSetImpl(E fromElement, boolean inclusive) { return this; } @Override int indexOf(@Nullable Object target) { return -1; } @Override ImmutableSortedSet<E> createDescendingSet() { return new EmptyImmutableSortedSet<E>(Ordering.from(comparator).reverse()); } }
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.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import javax.annotation.Nullable; /** * A list which forwards all its method calls to another list. Subclasses should * override one or more methods to modify the behavior of the backing list as * desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p>This class does not implement {@link java.util.RandomAccess}. If the * delegate supports random access, the {@code ForwardingList} subclass should * implement the {@code RandomAccess} interface. * * <p><b>Warning:</b> The methods of {@code ForwardingList} 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 and any collection views they return are not * guaranteed to be thread-safe, even when all of the methods that they depend * on are thread-safe. * * @author Mike Bostock * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingList<E> extends ForwardingCollection<E> implements List<E> { // TODO(user): identify places where thread safety is actually lost /** Constructor for use by subclasses. */ protected ForwardingList() {} @Override protected abstract List<E> delegate(); @Override public void add(int index, E element) { delegate().add(index, element); } @Override public boolean addAll(int index, Collection<? extends E> elements) { return delegate().addAll(index, elements); } @Override public E get(int index) { return delegate().get(index); } @Override public int indexOf(Object element) { return delegate().indexOf(element); } @Override public int lastIndexOf(Object element) { return delegate().lastIndexOf(element); } @Override public ListIterator<E> listIterator() { return delegate().listIterator(); } @Override public ListIterator<E> listIterator(int index) { return delegate().listIterator(index); } @Override public E remove(int index) { return delegate().remove(index); } @Override public E set(int index, E element) { return delegate().set(index, element); } @Override public List<E> subList(int fromIndex, int toIndex) { return delegate().subList(fromIndex, toIndex); } @Override public boolean equals(@Nullable Object object) { return object == this || delegate().equals(object); } @Override public int hashCode() { return delegate().hashCode(); } /** * A sensible default implementation of {@link #add(Object)}, in terms of * {@link #add(int, Object)}. If you override {@link #add(int, Object)}, you * may wish to override {@link #add(Object)} to forward to this * implementation. * * @since 7.0 */ protected boolean standardAdd(E element) { add(size(), element); return true; } /** * A sensible default implementation of {@link #addAll(int, Collection)}, in * terms of the {@code add} method of {@link #listIterator(int)}. If you * override {@link #listIterator(int)}, you may wish to override {@link * #addAll(int, Collection)} to forward to this implementation. * * @since 7.0 */ protected boolean standardAddAll( int index, Iterable<? extends E> elements) { return Lists.addAllImpl(this, index, elements); } /** * A sensible default implementation of {@link #indexOf}, in terms of {@link * #listIterator()}. If you override {@link #listIterator()}, you may wish to * override {@link #indexOf} to forward to this implementation. * * @since 7.0 */ protected int standardIndexOf(@Nullable Object element) { return Lists.indexOfImpl(this, element); } /** * A sensible default implementation of {@link #lastIndexOf}, in terms of * {@link #listIterator(int)}. If you override {@link #listIterator(int)}, you * may wish to override {@link #lastIndexOf} to forward to this * implementation. * * @since 7.0 */ protected int standardLastIndexOf(@Nullable Object element) { return Lists.lastIndexOfImpl(this, element); } /** * A sensible default implementation of {@link #iterator}, in terms of * {@link #listIterator()}. If you override {@link #listIterator()}, you may * wish to override {@link #iterator} to forward to this implementation. * * @since 7.0 */ protected Iterator<E> standardIterator() { return listIterator(); } /** * A sensible default implementation of {@link #listIterator()}, in terms of * {@link #listIterator(int)}. If you override {@link #listIterator(int)}, you * may wish to override {@link #listIterator()} to forward to this * implementation. * * @since 7.0 */ protected ListIterator<E> standardListIterator() { return listIterator(0); } /** * A sensible default implementation of {@link #listIterator(int)}, in terms * of {@link #size}, {@link #get(int)}, {@link #set(int, Object)}, {@link * #add(int, Object)}, and {@link #remove(int)}. If you override any of these * methods, you may wish to override {@link #listIterator(int)} to forward to * this implementation. * * @since 7.0 */ @Beta protected ListIterator<E> standardListIterator(int start) { return Lists.listIteratorImpl(this, start); } /** * A sensible default implementation of {@link #subList(int, int)}. If you * override any other methods, you may wish to override {@link #subList(int, * int)} to forward to this implementation. * * @since 7.0 */ @Beta protected List<E> standardSubList(int fromIndex, int toIndex) { return Lists.subListImpl(this, fromIndex, toIndex); } /** * A sensible definition of {@link #equals(Object)} in terms of {@link #size} * and {@link #iterator}. If you override either of those methods, you may * wish to override {@link #equals(Object)} to forward to this implementation. * * @since 7.0 */ @Beta protected boolean standardEquals(@Nullable Object object) { return Lists.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 * #hashCode} to forward to this implementation. * * @since 7.0 */ @Beta protected int standardHashCode() { return Lists.hashCodeImpl(this); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Predicates.alwaysTrue; import static com.google.common.base.Predicates.equalTo; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; import static com.google.common.collect.Maps.safeContainsKey; import static com.google.common.collect.Maps.safeGet; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.collect.Maps.ImprovedAbstractMap; import com.google.common.collect.Sets.ImprovedAbstractSet; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.annotation.Nullable; /** * {@link Table} implementation backed by a map that associates row keys with * column key / value secondary maps. This class provides rapid access to * records by the row key alone or by both keys, but not by just the column key. * * <p>The views returned by {@link #column}, {@link #columnKeySet()}, and {@link * #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. * * @author Jared Levy */ @GwtCompatible class StandardTable<R, C, V> extends AbstractTable<R, C, V> implements Serializable { @GwtTransient final Map<R, Map<C, V>> backingMap; @GwtTransient final Supplier<? extends Map<C, V>> factory; StandardTable(Map<R, Map<C, V>> backingMap, Supplier<? extends Map<C, V>> factory) { this.backingMap = backingMap; this.factory = factory; } // Accessors @Override public boolean contains( @Nullable Object rowKey, @Nullable Object columnKey) { return rowKey != null && columnKey != null && super.contains(rowKey, columnKey); } @Override public boolean containsColumn(@Nullable Object columnKey) { if (columnKey == null) { return false; } for (Map<C, V> map : backingMap.values()) { if (safeContainsKey(map, columnKey)) { return true; } } return false; } @Override public boolean containsRow(@Nullable Object rowKey) { return rowKey != null && safeContainsKey(backingMap, rowKey); } @Override public boolean containsValue(@Nullable Object value) { return value != null && super.containsValue(value); } @Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) { return (rowKey == null || columnKey == null) ? null : super.get(rowKey, columnKey); } @Override public boolean isEmpty() { return backingMap.isEmpty(); } @Override public int size() { int size = 0; for (Map<C, V> map : backingMap.values()) { size += map.size(); } return size; } // Mutators @Override public void clear() { backingMap.clear(); } private Map<C, V> getOrCreate(R rowKey) { Map<C, V> map = backingMap.get(rowKey); if (map == null) { map = factory.get(); backingMap.put(rowKey, map); } return map; } @Override public V put(R rowKey, C columnKey, V value) { checkNotNull(rowKey); checkNotNull(columnKey); checkNotNull(value); return getOrCreate(rowKey).put(columnKey, value); } @Override public V remove( @Nullable Object rowKey, @Nullable Object columnKey) { if ((rowKey == null) || (columnKey == null)) { return null; } Map<C, V> map = safeGet(backingMap, rowKey); if (map == null) { return null; } V value = map.remove(columnKey); if (map.isEmpty()) { backingMap.remove(rowKey); } return value; } private Map<R, V> removeColumn(Object column) { Map<R, V> output = new LinkedHashMap<R, V>(); Iterator<Entry<R, Map<C, V>>> iterator = backingMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<R, Map<C, V>> entry = iterator.next(); V value = entry.getValue().remove(column); if (value != null) { output.put(entry.getKey(), value); if (entry.getValue().isEmpty()) { iterator.remove(); } } } return output; } private boolean containsMapping( Object rowKey, Object columnKey, Object value) { return value != null && value.equals(get(rowKey, columnKey)); } /** Remove a row key / column key / value mapping, if present. */ private boolean removeMapping(Object rowKey, Object columnKey, Object value) { if (containsMapping(rowKey, columnKey, value)) { remove(rowKey, columnKey); return true; } return false; } // Views /** * Abstract set whose {@code isEmpty()} returns whether the table is empty and * whose {@code clear()} clears all table mappings. */ private abstract class TableSet<T> extends ImprovedAbstractSet<T> { @Override public boolean isEmpty() { return backingMap.isEmpty(); } @Override public void clear() { backingMap.clear(); } } /** * {@inheritDoc} * * <p>The set's iterator traverses the mappings for the first row, the * mappings for the second row, and so on. * * <p>Each cell is an immutable snapshot of a row key / column key / value * mapping, taken at the time the cell is returned by a method call to the * set or its iterator. */ @Override public Set<Cell<R, C, V>> cellSet() { return super.cellSet(); } @Override Iterator<Cell<R, C, V>> cellIterator() { return new CellIterator(); } private class CellIterator implements Iterator<Cell<R, C, V>> { final Iterator<Entry<R, Map<C, V>>> rowIterator = backingMap.entrySet().iterator(); Entry<R, Map<C, V>> rowEntry; Iterator<Entry<C, V>> columnIterator = Iterators.emptyModifiableIterator(); @Override public boolean hasNext() { return rowIterator.hasNext() || columnIterator.hasNext(); } @Override public Cell<R, C, V> next() { if (!columnIterator.hasNext()) { rowEntry = rowIterator.next(); columnIterator = rowEntry.getValue().entrySet().iterator(); } Entry<C, V> columnEntry = columnIterator.next(); return Tables.immutableCell( rowEntry.getKey(), columnEntry.getKey(), columnEntry.getValue()); } @Override public void remove() { columnIterator.remove(); if (rowEntry.getValue().isEmpty()) { rowIterator.remove(); } } } @Override public Map<C, V> row(R rowKey) { return new Row(rowKey); } class Row extends ImprovedAbstractMap<C, V> { final R rowKey; Row(R rowKey) { this.rowKey = checkNotNull(rowKey); } Map<C, V> backingRowMap; Map<C, V> backingRowMap() { return (backingRowMap == null || (backingRowMap.isEmpty() && backingMap.containsKey(rowKey))) ? backingRowMap = computeBackingRowMap() : backingRowMap; } Map<C, V> computeBackingRowMap() { return backingMap.get(rowKey); } // Call this every time we perform a removal. void maintainEmptyInvariant() { if (backingRowMap() != null && backingRowMap.isEmpty()) { backingMap.remove(rowKey); backingRowMap = null; } } @Override public boolean containsKey(Object key) { Map<C, V> backingRowMap = backingRowMap(); return (key != null && backingRowMap != null) && Maps.safeContainsKey(backingRowMap, key); } @Override public V get(Object key) { Map<C, V> backingRowMap = backingRowMap(); return (key != null && backingRowMap != null) ? Maps.safeGet(backingRowMap, key) : null; } @Override public V put(C key, V value) { checkNotNull(key); checkNotNull(value); if (backingRowMap != null && !backingRowMap.isEmpty()) { return backingRowMap.put(key, value); } return StandardTable.this.put(rowKey, key, value); } @Override public V remove(Object key) { Map<C, V> backingRowMap = backingRowMap(); if (backingRowMap == null) { return null; } V result = Maps.safeRemove(backingRowMap, key); maintainEmptyInvariant(); return result; } @Override public void clear() { Map<C, V> backingRowMap = backingRowMap(); if (backingRowMap != null) { backingRowMap.clear(); } maintainEmptyInvariant(); } @Override protected Set<Entry<C, V>> createEntrySet() { return new RowEntrySet(); } private final class RowEntrySet extends Maps.EntrySet<C, V> { @Override Map<C, V> map() { return Row.this; } @Override public int size() { Map<C, V> map = backingRowMap(); return (map == null) ? 0 : map.size(); } @Override public Iterator<Entry<C, V>> iterator() { final Map<C, V> map = backingRowMap(); if (map == null) { return Iterators.emptyModifiableIterator(); } final Iterator<Entry<C, V>> iterator = map.entrySet().iterator(); return new Iterator<Entry<C, V>>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Entry<C, V> next() { final Entry<C, V> entry = iterator.next(); return new ForwardingMapEntry<C, V>() { @Override protected Entry<C, V> delegate() { return entry; } @Override public V setValue(V value) { return super.setValue(checkNotNull(value)); } @Override public boolean equals(Object object) { // TODO(user): identify why this affects GWT tests return standardEquals(object); } }; } @Override public void remove() { iterator.remove(); maintainEmptyInvariant(); } }; } } } /** * {@inheritDoc} * * <p>The returned map's views have iterators that don't support * {@code remove()}. */ @Override public Map<R, V> column(C columnKey) { return new Column(columnKey); } private class Column extends ImprovedAbstractMap<R, V> { final C columnKey; Column(C columnKey) { this.columnKey = checkNotNull(columnKey); } @Override public V put(R key, V value) { return StandardTable.this.put(key, columnKey, value); } @Override public V get(Object key) { return StandardTable.this.get(key, columnKey); } @Override public boolean containsKey(Object key) { return StandardTable.this.contains(key, columnKey); } @Override public V remove(Object key) { return StandardTable.this.remove(key, columnKey); } /** * Removes all {@code Column} mappings whose row key and value satisfy the * given predicate. */ boolean removeIf(Predicate<? super Entry<R, V>> predicate) { boolean changed = false; Iterator<Entry<R, Map<C, V>>> iterator = backingMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<R, Map<C, V>> entry = iterator.next(); Map<C, V> map = entry.getValue(); V value = map.get(columnKey); if (value != null && predicate.apply(Maps.immutableEntry(entry.getKey(), value))) { map.remove(columnKey); changed = true; if (map.isEmpty()) { iterator.remove(); } } } return changed; } @Override Set<Entry<R, V>> createEntrySet() { return new EntrySet(); } private class EntrySet extends ImprovedAbstractSet<Entry<R, V>> { @Override public Iterator<Entry<R, V>> iterator() { return new EntrySetIterator(); } @Override public int size() { int size = 0; for (Map<C, V> map : backingMap.values()) { if (map.containsKey(columnKey)) { size++; } } return size; } @Override public boolean isEmpty() { return !containsColumn(columnKey); } @Override public void clear() { removeIf(alwaysTrue()); } @Override public boolean contains(Object o) { if (o instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) o; return containsMapping(entry.getKey(), columnKey, entry.getValue()); } return false; } @Override public boolean remove(Object obj) { if (obj instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) obj; return removeMapping(entry.getKey(), columnKey, entry.getValue()); } return false; } @Override public boolean retainAll(Collection<?> c) { return removeIf(not(in(c))); } } private class EntrySetIterator extends AbstractIterator<Entry<R, V>> { final Iterator<Entry<R, Map<C, V>>> iterator = backingMap.entrySet().iterator(); @Override protected Entry<R, V> computeNext() { while (iterator.hasNext()) { final Entry<R, Map<C, V>> entry = iterator.next(); if (entry.getValue().containsKey(columnKey)) { return new AbstractMapEntry<R, V>() { @Override public R getKey() { return entry.getKey(); } @Override public V getValue() { return entry.getValue().get(columnKey); } @Override public V setValue(V value) { return entry.getValue().put(columnKey, checkNotNull(value)); } }; } } return endOfData(); } } @Override Set<R> createKeySet() { return new KeySet(); } private class KeySet extends Maps.KeySet<R, V> { KeySet() { super(Column.this); } @Override public boolean contains(Object obj) { return StandardTable.this.contains(obj, columnKey); } @Override public boolean remove(Object obj) { return StandardTable.this.remove(obj, columnKey) != null; } @Override public boolean retainAll(final Collection<?> c) { return removeIf(Maps.<R>keyPredicateOnEntries(not(in(c)))); } } @Override Collection<V> createValues() { return new Values(); } private class Values extends Maps.Values<R, V> { Values() { super(Column.this); } @Override public boolean remove(Object obj) { return obj != null && removeIf(Maps.<V>valuePredicateOnEntries(equalTo(obj))); } @Override public boolean removeAll(final Collection<?> c) { return removeIf(Maps.<V>valuePredicateOnEntries(in(c))); } @Override public boolean retainAll(final Collection<?> c) { return removeIf(Maps.<V>valuePredicateOnEntries(not(in(c)))); } } } @Override public Set<R> rowKeySet() { return rowMap().keySet(); } private transient Set<C> columnKeySet; /** * {@inheritDoc} * * <p>The returned set has an iterator that does not support {@code remove()}. * * <p>The set's iterator traverses the columns of the first row, the * columns of the second row, etc., skipping any columns that have * appeared previously. */ @Override public Set<C> columnKeySet() { Set<C> result = columnKeySet; return (result == null) ? columnKeySet = new ColumnKeySet() : result; } private class ColumnKeySet extends TableSet<C> { @Override public Iterator<C> iterator() { return createColumnKeyIterator(); } @Override public int size() { return Iterators.size(iterator()); } @Override public boolean remove(Object obj) { if (obj == null) { return false; } boolean changed = false; Iterator<Map<C, V>> iterator = backingMap.values().iterator(); while (iterator.hasNext()) { Map<C, V> map = iterator.next(); if (map.keySet().remove(obj)) { changed = true; if (map.isEmpty()) { iterator.remove(); } } } return changed; } @Override public boolean removeAll(Collection<?> c) { checkNotNull(c); boolean changed = false; Iterator<Map<C, V>> iterator = backingMap.values().iterator(); while (iterator.hasNext()) { Map<C, V> map = iterator.next(); // map.keySet().removeAll(c) can throw a NPE when map is a TreeMap with // natural ordering and c contains a null. if (Iterators.removeAll(map.keySet().iterator(), c)) { changed = true; if (map.isEmpty()) { iterator.remove(); } } } return changed; } @Override public boolean retainAll(Collection<?> c) { checkNotNull(c); boolean changed = false; Iterator<Map<C, V>> iterator = backingMap.values().iterator(); while (iterator.hasNext()) { Map<C, V> map = iterator.next(); if (map.keySet().retainAll(c)) { changed = true; if (map.isEmpty()) { iterator.remove(); } } } return changed; } @Override public boolean contains(Object obj) { return containsColumn(obj); } } /** * Creates an iterator that returns each column value with duplicates * omitted. */ Iterator<C> createColumnKeyIterator() { return new ColumnKeyIterator(); } private class ColumnKeyIterator extends AbstractIterator<C> { // Use the same map type to support TreeMaps with comparators that aren't // consistent with equals(). final Map<C, V> seen = factory.get(); final Iterator<Map<C, V>> mapIterator = backingMap.values().iterator(); Iterator<Entry<C, V>> entryIterator = Iterators.emptyIterator(); @Override protected C computeNext() { while (true) { if (entryIterator.hasNext()) { Entry<C, V> entry = entryIterator.next(); if (!seen.containsKey(entry.getKey())) { seen.put(entry.getKey(), entry.getValue()); return entry.getKey(); } } else if (mapIterator.hasNext()) { entryIterator = mapIterator.next().entrySet().iterator(); } else { return endOfData(); } } } } /** * {@inheritDoc} * * <p>The collection's iterator traverses the values for the first row, * the values for the second row, and so on. */ @Override public Collection<V> values() { return super.values(); } private transient Map<R, Map<C, V>> rowMap; @Override public Map<R, Map<C, V>> rowMap() { Map<R, Map<C, V>> result = rowMap; return (result == null) ? rowMap = createRowMap() : result; } Map<R, Map<C, V>> createRowMap() { return new RowMap(); } class RowMap extends ImprovedAbstractMap<R, Map<C, V>> { @Override public boolean containsKey(Object key) { return containsRow(key); } // performing cast only when key is in backing map and has the correct type @SuppressWarnings("unchecked") @Override public Map<C, V> get(Object key) { return containsRow(key) ? row((R) key) : null; } @Override public Map<C, V> remove(Object key) { return (key == null) ? null : backingMap.remove(key); } @Override protected Set<Entry<R, Map<C, V>>> createEntrySet() { return new EntrySet(); } class EntrySet extends TableSet<Entry<R, Map<C, V>>> { @Override public Iterator<Entry<R, Map<C, V>>> iterator() { return Maps.asMapEntryIterator(backingMap.keySet(), new Function<R, Map<C, V>>() { @Override public Map<C, V> apply(R rowKey) { return row(rowKey); } }); } @Override public int size() { return backingMap.size(); } @Override public boolean contains(Object obj) { if (obj instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) obj; return entry.getKey() != null && entry.getValue() instanceof Map && Collections2.safeContains(backingMap.entrySet(), entry); } return false; } @Override public boolean remove(Object obj) { if (obj instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) obj; return entry.getKey() != null && entry.getValue() instanceof Map && backingMap.entrySet().remove(entry); } return false; } } } private transient ColumnMap columnMap; @Override public Map<C, Map<R, V>> columnMap() { ColumnMap result = columnMap; return (result == null) ? columnMap = new ColumnMap() : result; } private class ColumnMap extends ImprovedAbstractMap<C, Map<R, V>> { // The cast to C occurs only when the key is in the map, implying that it // has the correct type. @SuppressWarnings("unchecked") @Override public Map<R, V> get(Object key) { return containsColumn(key) ? column((C) key) : null; } @Override public boolean containsKey(Object key) { return containsColumn(key); } @Override public Map<R, V> remove(Object key) { return containsColumn(key) ? removeColumn(key) : null; } @Override public Set<Entry<C, Map<R, V>>> createEntrySet() { return new ColumnMapEntrySet(); } @Override public Set<C> keySet() { return columnKeySet(); } @Override Collection<Map<R, V>> createValues() { return new ColumnMapValues(); } class ColumnMapEntrySet extends TableSet<Entry<C, Map<R, V>>> { @Override public Iterator<Entry<C, Map<R, V>>> iterator() { return Maps.asMapEntryIterator(columnKeySet(), new Function<C, Map<R, V>>() { @Override public Map<R, V> apply(C columnKey) { return column(columnKey); } }); } @Override public int size() { return columnKeySet().size(); } @Override public boolean contains(Object obj) { if (obj instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) obj; if (containsColumn(entry.getKey())) { // The cast to C occurs only when the key is in the map, implying // that it has the correct type. @SuppressWarnings("unchecked") C columnKey = (C) entry.getKey(); return get(columnKey).equals(entry.getValue()); } } return false; } @Override public boolean remove(Object obj) { if (contains(obj)) { Entry<?, ?> entry = (Entry<?, ?>) obj; removeColumn(entry.getKey()); return true; } return false; } @Override public boolean removeAll(Collection<?> c) { /* * We can't inherit the normal implementation (which calls * Sets.removeAllImpl(Set, *Collection*) because, under some * circumstances, it attempts to call columnKeySet().iterator().remove, * which is unsupported. */ checkNotNull(c); return Sets.removeAllImpl(this, c.iterator()); } @Override public boolean retainAll(Collection<?> c) { checkNotNull(c); boolean changed = false; for (C columnKey : Lists.newArrayList(columnKeySet().iterator())) { if (!c.contains(Maps.immutableEntry(columnKey, column(columnKey)))) { removeColumn(columnKey); changed = true; } } return changed; } } private class ColumnMapValues extends Maps.Values<C, Map<R, V>> { ColumnMapValues() { super(ColumnMap.this); } @Override public boolean remove(Object obj) { for (Entry<C, Map<R, V>> entry : ColumnMap.this.entrySet()) { if (entry.getValue().equals(obj)) { removeColumn(entry.getKey()); return true; } } return false; } @Override public boolean removeAll(Collection<?> c) { checkNotNull(c); boolean changed = false; for (C columnKey : Lists.newArrayList(columnKeySet().iterator())) { if (c.contains(column(columnKey))) { removeColumn(columnKey); changed = true; } } return changed; } @Override public boolean retainAll(Collection<?> c) { checkNotNull(c); boolean changed = false; for (C columnKey : Lists.newArrayList(columnKeySet().iterator())) { if (!c.contains(column(columnKey))) { removeColumn(columnKey); changed = true; } } return changed; } } } 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 static com.google.common.base.Predicates.and; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; import static com.google.common.math.LongMath.binomial; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.math.IntMath; import com.google.common.primitives.Ints; import java.util.AbstractCollection; 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; import javax.annotation.Nullable; /** * Provides static methods for working with {@code Collection} instances. * * @author Chris Povirk * @author Mike Bostock * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public final class Collections2 { private Collections2() {} /** * Returns the elements of {@code unfiltered} that satisfy a predicate. The * returned collection is a live view of {@code unfiltered}; changes to one * affect the other. * * <p>The resulting collection's iterator does not support {@code remove()}, * but all other collection methods are supported. When given an element that * doesn't satisfy the predicate, the collection'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 * collection, only elements that satisfy the filter will be removed from the * underlying collection. * * <p>The returned collection isn't threadsafe or serializable, even if * {@code unfiltered} is. * * <p>Many of the filtered collection's methods, such as {@code size()}, * iterate across every element in the underlying collection 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 can we omit that Iterables link when building gwt // javadoc? public static <E> Collection<E> filter( Collection<E> unfiltered, Predicate<? super E> predicate) { if (unfiltered instanceof FilteredCollection) { // Support clear(), removeAll(), and retainAll() when filtering a filtered // collection. return ((FilteredCollection<E>) unfiltered).createCombined(predicate); } return new FilteredCollection<E>( checkNotNull(unfiltered), checkNotNull(predicate)); } /** * Delegates to {@link Collection#contains}. Returns {@code false} if the * {@code contains} method throws a {@code ClassCastException} or * {@code NullPointerException}. */ static boolean safeContains( Collection<?> collection, @Nullable Object object) { checkNotNull(collection); try { return collection.contains(object); } catch (ClassCastException e) { return false; } catch (NullPointerException e) { return false; } } /** * Delegates to {@link Collection#remove}. Returns {@code false} if the * {@code remove} method throws a {@code ClassCastException} or * {@code NullPointerException}. */ static boolean safeRemove(Collection<?> collection, @Nullable Object object) { checkNotNull(collection); try { return collection.remove(object); } catch (ClassCastException e) { return false; } catch (NullPointerException e) { return false; } } static class FilteredCollection<E> extends AbstractCollection<E> { final Collection<E> unfiltered; final Predicate<? super E> predicate; FilteredCollection(Collection<E> unfiltered, Predicate<? super E> predicate) { this.unfiltered = unfiltered; this.predicate = predicate; } FilteredCollection<E> createCombined(Predicate<? super E> newPredicate) { return new FilteredCollection<E>(unfiltered, Predicates.<E>and(predicate, newPredicate)); // .<E> above needed to compile in JDK 5 } @Override public boolean add(E element) { checkArgument(predicate.apply(element)); return unfiltered.add(element); } @Override public boolean addAll(Collection<? extends E> collection) { for (E element : collection) { checkArgument(predicate.apply(element)); } return unfiltered.addAll(collection); } @Override public void clear() { Iterables.removeIf(unfiltered, predicate); } @Override public boolean contains(@Nullable Object element) { if (safeContains(unfiltered, element)) { @SuppressWarnings("unchecked") // element is in unfiltered, so it must be an E E e = (E) element; return predicate.apply(e); } return false; } @Override public boolean containsAll(Collection<?> collection) { return containsAllImpl(this, collection); } @Override public boolean isEmpty() { return !Iterables.any(unfiltered, predicate); } @Override public Iterator<E> iterator() { return Iterators.filter(unfiltered.iterator(), predicate); } @Override public boolean remove(Object element) { return contains(element) && unfiltered.remove(element); } @Override public boolean removeAll(final Collection<?> collection) { return Iterables.removeIf(unfiltered, and(predicate, in(collection))); } @Override public boolean retainAll(final Collection<?> collection) { return Iterables.removeIf(unfiltered, and(predicate, not(in(collection)))); } @Override public int size() { return Iterators.size(iterator()); } @Override public Object[] toArray() { // creating an ArrayList so filtering happens once return Lists.newArrayList(iterator()).toArray(); } @Override public <T> T[] toArray(T[] array) { return Lists.newArrayList(iterator()).toArray(array); } } /** * Returns a collection that applies {@code function} to each element of * {@code fromCollection}. The returned collection is a live view of {@code * fromCollection}; changes to one affect the other. * * <p>The returned collection's {@code add()} and {@code addAll()} methods * throw an {@link UnsupportedOperationException}. All other collection * methods are supported, as long as {@code fromCollection} supports them. * * <p>The returned collection isn't threadsafe or serializable, even if * {@code fromCollection} is. * * <p>When a live view is <i>not</i> needed, it may be faster to copy the * transformed collection and use the copy. * * <p>If the input {@code Collection} is known to be a {@code List}, consider * {@link Lists#transform}. If only an {@code Iterable} is available, use * {@link Iterables#transform}. */ public static <F, T> Collection<T> transform(Collection<F> fromCollection, Function<? super F, T> function) { return new TransformedCollection<F, T>(fromCollection, function); } static class TransformedCollection<F, T> extends AbstractCollection<T> { final Collection<F> fromCollection; final Function<? super F, ? extends T> function; TransformedCollection(Collection<F> fromCollection, Function<? super F, ? extends T> function) { this.fromCollection = checkNotNull(fromCollection); this.function = checkNotNull(function); } @Override public void clear() { fromCollection.clear(); } @Override public boolean isEmpty() { return fromCollection.isEmpty(); } @Override public Iterator<T> iterator() { return Iterators.transform(fromCollection.iterator(), function); } @Override public int size() { return fromCollection.size(); } } /** * Returns {@code true} if the collection {@code self} contains all of the * elements in the collection {@code c}. * * <p>This method iterates over the specified collection {@code c}, checking * each element returned by the iterator in turn to see if it is contained in * the specified collection {@code self}. If all elements are so contained, * {@code true} is returned, otherwise {@code false}. * * @param self a collection which might contain all elements in {@code c} * @param c a collection whose elements might be contained by {@code self} */ static boolean containsAllImpl(Collection<?> self, Collection<?> c) { return Iterables.all(c, Predicates.in(self)); } /** * An implementation of {@link Collection#toString()}. */ static String toStringImpl(final Collection<?> collection) { StringBuilder sb = newStringBuilderForCollection(collection.size()).append('['); STANDARD_JOINER.appendTo( sb, Iterables.transform(collection, new Function<Object, Object>() { @Override public Object apply(Object input) { return input == collection ? "(this Collection)" : input; } })); return sb.append(']').toString(); } /** * Returns best-effort-sized StringBuilder based on the given collection size. */ static StringBuilder newStringBuilderForCollection(int size) { checkArgument(size >= 0, "size must be non-negative"); return new StringBuilder((int) Math.min(size * 8L, Ints.MAX_POWER_OF_TWO)); } /** * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */ static <T> Collection<T> cast(Iterable<T> iterable) { return (Collection<T>) iterable; } static final Joiner STANDARD_JOINER = Joiner.on(", ").useForNull("null"); /** * Returns a {@link Collection} of all the permutations of the specified * {@link Iterable}. * * <p><i>Notes:</i> This is an implementation of the algorithm for * Lexicographical Permutations Generation, described in Knuth's "The Art of * Computer Programming", Volume 4, Chapter 7, Section 7.2.1.2. The * iteration order follows the lexicographical order. This means that * the first permutation will be in ascending order, and the last will be in * descending order. * * <p>Duplicate elements are considered equal. For example, the list [1, 1] * will have only one permutation, instead of two. This is why the elements * have to implement {@link Comparable}. * * <p>An empty iterable has only one permutation, which is an empty list. * * <p>This method is equivalent to * {@code Collections2.orderedPermutations(list, Ordering.natural())}. * * @param elements the original iterable whose elements have to be permuted. * @return an immutable {@link Collection} containing all the different * permutations of the original iterable. * @throws NullPointerException if the specified iterable is null or has any * null elements. * @since 12.0 */ @Beta public static <E extends Comparable<? super E>> Collection<List<E>> orderedPermutations(Iterable<E> elements) { return orderedPermutations(elements, Ordering.natural()); } /** * Returns a {@link Collection} of all the permutations of the specified * {@link Iterable} using the specified {@link Comparator} for establishing * the lexicographical ordering. * * <p>Examples: <pre> {@code * * for (List<String> perm : orderedPermutations(asList("b", "c", "a"))) { * println(perm); * } * // -> ["a", "b", "c"] * // -> ["a", "c", "b"] * // -> ["b", "a", "c"] * // -> ["b", "c", "a"] * // -> ["c", "a", "b"] * // -> ["c", "b", "a"] * * for (List<Integer> perm : orderedPermutations(asList(1, 2, 2, 1))) { * println(perm); * } * // -> [1, 1, 2, 2] * // -> [1, 2, 1, 2] * // -> [1, 2, 2, 1] * // -> [2, 1, 1, 2] * // -> [2, 1, 2, 1] * // -> [2, 2, 1, 1]}</pre> * * <p><i>Notes:</i> This is an implementation of the algorithm for * Lexicographical Permutations Generation, described in Knuth's "The Art of * Computer Programming", Volume 4, Chapter 7, Section 7.2.1.2. The * iteration order follows the lexicographical order. This means that * the first permutation will be in ascending order, and the last will be in * descending order. * * <p>Elements that compare equal are considered equal and no new permutations * are created by swapping them. * * <p>An empty iterable has only one permutation, which is an empty list. * * @param elements the original iterable whose elements have to be permuted. * @param comparator a comparator for the iterable's elements. * @return an immutable {@link Collection} containing all the different * permutations of the original iterable. * @throws NullPointerException If the specified iterable is null, has any * null elements, or if the specified comparator is null. * @since 12.0 */ @Beta public static <E> Collection<List<E>> orderedPermutations( Iterable<E> elements, Comparator<? super E> comparator) { return new OrderedPermutationCollection<E>(elements, comparator); } private static final class OrderedPermutationCollection<E> extends AbstractCollection<List<E>> { final ImmutableList<E> inputList; final Comparator<? super E> comparator; final int size; OrderedPermutationCollection(Iterable<E> input, Comparator<? super E> comparator) { this.inputList = Ordering.from(comparator).immutableSortedCopy(input); this.comparator = comparator; this.size = calculateSize(inputList, comparator); } /** * The number of permutations with repeated elements is calculated as * follows: * <ul> * <li>For an empty list, it is 1 (base case).</li> * <li>When r numbers are added to a list of n-r elements, the number of * permutations is increased by a factor of (n choose r).</li> * </ul> */ private static <E> int calculateSize( List<E> sortedInputList, Comparator<? super E> comparator) { long permutations = 1; int n = 1; int r = 1; while (n < sortedInputList.size()) { int comparison = comparator.compare( sortedInputList.get(n - 1), sortedInputList.get(n)); if (comparison < 0) { // We move to the next non-repeated element. permutations *= binomial(n, r); r = 0; if (!isPositiveInt(permutations)) { return Integer.MAX_VALUE; } } n++; r++; } permutations *= binomial(n, r); if (!isPositiveInt(permutations)) { return Integer.MAX_VALUE; } return (int) permutations; } @Override public int size() { return size; } @Override public boolean isEmpty() { return false; } @Override public Iterator<List<E>> iterator() { return new OrderedPermutationIterator<E>(inputList, comparator); } @Override public boolean contains(@Nullable Object obj) { if (obj instanceof List) { List<?> list = (List<?>) obj; return isPermutation(inputList, list); } return false; } @Override public String toString() { return "orderedPermutationCollection(" + inputList + ")"; } } private static final class OrderedPermutationIterator<E> extends AbstractIterator<List<E>> { List<E> nextPermutation; final Comparator<? super E> comparator; OrderedPermutationIterator(List<E> list, Comparator<? super E> comparator) { this.nextPermutation = Lists.newArrayList(list); this.comparator = comparator; } @Override protected List<E> computeNext() { if (nextPermutation == null) { return endOfData(); } ImmutableList<E> next = ImmutableList.copyOf(nextPermutation); calculateNextPermutation(); return next; } void calculateNextPermutation() { int j = findNextJ(); if (j == -1) { nextPermutation = null; return; } int l = findNextL(j); Collections.swap(nextPermutation, j, l); int n = nextPermutation.size(); Collections.reverse(nextPermutation.subList(j + 1, n)); } int findNextJ() { for (int k = nextPermutation.size() - 2; k >= 0; k--) { if (comparator.compare(nextPermutation.get(k), nextPermutation.get(k + 1)) < 0) { return k; } } return -1; } int findNextL(int j) { E ak = nextPermutation.get(j); for (int l = nextPermutation.size() - 1; l > j; l--) { if (comparator.compare(ak, nextPermutation.get(l)) < 0) { return l; } } throw new AssertionError("this statement should be unreachable"); } } /** * Returns a {@link Collection} of all the permutations of the specified * {@link Collection}. * * <p><i>Notes:</i> This is an implementation of the Plain Changes algorithm * for permutations generation, described in Knuth's "The Art of Computer * Programming", Volume 4, Chapter 7, Section 7.2.1.2. * * <p>If the input list contains equal elements, some of the generated * permutations will be equal. * * <p>An empty collection has only one permutation, which is an empty list. * * @param elements the original collection whose elements have to be permuted. * @return an immutable {@link Collection} containing all the different * permutations of the original collection. * @throws NullPointerException if the specified collection is null or has any * null elements. * @since 12.0 */ @Beta public static <E> Collection<List<E>> permutations( Collection<E> elements) { return new PermutationCollection<E>(ImmutableList.copyOf(elements)); } private static final class PermutationCollection<E> extends AbstractCollection<List<E>> { final ImmutableList<E> inputList; PermutationCollection(ImmutableList<E> input) { this.inputList = input; } @Override public int size() { return IntMath.factorial(inputList.size()); } @Override public boolean isEmpty() { return false; } @Override public Iterator<List<E>> iterator() { return new PermutationIterator<E>(inputList); } @Override public boolean contains(@Nullable Object obj) { if (obj instanceof List) { List<?> list = (List<?>) obj; return isPermutation(inputList, list); } return false; } @Override public String toString() { return "permutations(" + inputList + ")"; } } private static class PermutationIterator<E> extends AbstractIterator<List<E>> { final List<E> list; final int[] c; final int[] o; int j; PermutationIterator(List<E> list) { this.list = new ArrayList<E>(list); int n = list.size(); c = new int[n]; o = new int[n]; Arrays.fill(c, 0); Arrays.fill(o, 1); j = Integer.MAX_VALUE; } @Override protected List<E> computeNext() { if (j <= 0) { return endOfData(); } ImmutableList<E> next = ImmutableList.copyOf(list); calculateNextPermutation(); return next; } void calculateNextPermutation() { j = list.size() - 1; int s = 0; // Handle the special case of an empty list. Skip the calculation of the // next permutation. if (j == -1) { return; } while (true) { int q = c[j] + o[j]; if (q < 0) { switchDirection(); continue; } if (q == j + 1) { if (j == 0) { break; } s++; switchDirection(); continue; } Collections.swap(list, j - c[j] + s, j - q + s); c[j] = q; break; } } void switchDirection() { o[j] = -o[j]; j--; } } /** * Returns {@code true} if the second list is a permutation of the first. */ private static boolean isPermutation(List<?> first, List<?> second) { if (first.size() != second.size()) { return false; } Multiset<?> firstMultiset = HashMultiset.create(first); Multiset<?> secondMultiset = HashMultiset.create(second); return firstMultiset.equals(secondMultiset); } private static boolean isPositiveInt(long n) { return n >= 0 && n <= Integer.MAX_VALUE; } }
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 com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Implementation of {@link Multimap} using hash tables. * * <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>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#synchronizedSetMultimap}. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public final class HashMultimap<K, V> extends AbstractSetMultimap<K, V> { private static final int DEFAULT_VALUES_PER_KEY = 2; @VisibleForTesting transient int expectedValuesPerKey = DEFAULT_VALUES_PER_KEY; /** * Creates a new, empty {@code HashMultimap} with the default initial * capacities. */ public static <K, V> HashMultimap<K, V> create() { return new HashMultimap<K, V>(); } /** * Constructs an empty {@code HashMultimap} with enough capacity to hold the * specified numbers of keys and values without rehashing. * * @param expectedKeys the expected number of distinct keys * @param expectedValuesPerKey the expected average number of values per key * @throws IllegalArgumentException if {@code expectedKeys} or {@code * expectedValuesPerKey} is negative */ public static <K, V> HashMultimap<K, V> create( int expectedKeys, int expectedValuesPerKey) { return new HashMultimap<K, V>(expectedKeys, expectedValuesPerKey); } /** * Constructs a {@code HashMultimap} with the same mappings as the specified * multimap. If a key-value mapping appears multiple times in the input * multimap, it only appears once in the constructed multimap. * * @param multimap the multimap whose contents are copied to this multimap */ public static <K, V> HashMultimap<K, V> create( Multimap<? extends K, ? extends V> multimap) { return new HashMultimap<K, V>(multimap); } private HashMultimap() { super(new HashMap<K, Collection<V>>()); } private HashMultimap(int expectedKeys, int expectedValuesPerKey) { super(Maps.<K, Collection<V>>newHashMapWithExpectedSize(expectedKeys)); Preconditions.checkArgument(expectedValuesPerKey >= 0); this.expectedValuesPerKey = expectedValuesPerKey; } private HashMultimap(Multimap<? extends K, ? extends V> multimap) { super(Maps.<K, Collection<V>>newHashMapWithExpectedSize( multimap.keySet().size())); putAll(multimap); } /** * {@inheritDoc} * * <p>Creates an empty {@code HashSet} for a collection of values for one key. * * @return a new {@code HashSet} containing a collection of values for one key */ @Override Set<V> createCollection() { return Sets.<V>newHashSetWithExpectedSize(expectedValuesPerKey); } /** * @serialData expectedValuesPerKey, number of distinct keys, and then for * each distinct key: the key, number of values for that key, and the * key's values */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeInt(expectedValuesPerKey); Serialization.writeMultimap(this, stream); } @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); expectedValuesPerKey = stream.readInt(); int distinctKeys = Serialization.readCount(stream); Map<K, Collection<V>> map = Maps.newHashMapWithExpectedSize(distinctKeys); setMap(map); Serialization.populateMultimap(this, stream, distinctKeys); } @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.io.Serializable; import java.util.Comparator; /** An ordering that tries several comparators in order. */ @GwtCompatible(serializable = true) final class CompoundOrdering<T> extends Ordering<T> implements Serializable { final ImmutableList<Comparator<? super T>> comparators; CompoundOrdering(Comparator<? super T> primary, Comparator<? super T> secondary) { this.comparators = ImmutableList.<Comparator<? super T>>of(primary, secondary); } CompoundOrdering(Iterable<? extends Comparator<? super T>> comparators) { this.comparators = ImmutableList.copyOf(comparators); } @Override public int compare(T left, T right) { // Avoid using the Iterator to avoid generating garbage (issue 979). int size = comparators.size(); for (int i = 0; i < size; i++) { int result = comparators.get(i).compare(left, right); if (result != 0) { return result; } } return 0; } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof CompoundOrdering) { CompoundOrdering<?> that = (CompoundOrdering<?>) object; return this.comparators.equals(that.comparators); } return false; } @Override public int hashCode() { return comparators.hashCode(); } @Override public String toString() { return "Ordering.compound(" + comparators + ")"; } private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.List; import javax.annotation.Nullable; /** * An ordering that treats all references as equals, even nulls. * * @author Emily Soldal */ @GwtCompatible(serializable = true) final class AllEqualOrdering extends Ordering<Object> implements Serializable { static final AllEqualOrdering INSTANCE = new AllEqualOrdering(); @Override public int compare(@Nullable Object left, @Nullable Object right) { return 0; } @Override public <E> List<E> sortedCopy(Iterable<E> iterable) { return Lists.newArrayList(iterable); } @Override public <E> ImmutableList<E> immutableSortedCopy(Iterable<E> iterable) { return ImmutableList.copyOf(iterable); } @SuppressWarnings("unchecked") @Override public <S> Ordering<S> reverse() { return (Ordering<S>) this; } private Object readResolve() { return INSTANCE; } @Override public String toString() { return "Ordering.allEqual()"; } private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import java.util.SortedSet; /** * Superinterface of {@link SortedMultiset} to introduce a bridge method for * {@code elementSet()}, to ensure binary compatibility with older Guava versions * that specified {@code elementSet()} to return {@code SortedSet}. * * @author Louis Wasserman */ interface SortedMultisetBridge<E> extends Multiset<E> { @Override SortedSet<E> elementSet(); }
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.Collections; import java.util.Comparator; import java.util.Map; import java.util.SortedSet; import javax.annotation.Nullable; /** * Basic implementation of the {@link SortedSetMultimap} interface. It's a * wrapper around {@link AbstractMapBasedMultimap} that converts the returned * collections into sorted sets. The {@link #createCollection} method * must return a {@code SortedSet}. * * @author Jared Levy */ @GwtCompatible abstract class AbstractSortedSetMultimap<K, V> extends AbstractSetMultimap<K, V> implements SortedSetMultimap<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 AbstractSortedSetMultimap(Map<K, Collection<V>> map) { super(map); } @Override abstract SortedSet<V> createCollection(); @Override SortedSet<V> createUnmodifiableEmptyCollection() { Comparator<? super V> comparator = valueComparator(); if (comparator == null) { return Collections.unmodifiableSortedSet(createCollection()); } else { return ImmutableSortedSet.emptySet(valueComparator()); } } // Following Javadoc copied from Multimap and SortedSetMultimap. /** * 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 Collection} specified in the {@link Multimap} interface. */ @Override public SortedSet<V> get(@Nullable K key) { return (SortedSet<V>) super.get(key); } /** * Removes all values associated with a given key. The returned collection is * immutable. * * <p>Because a {@code SortedSetMultimap} has unique sorted values for a given * key, this method returns a {@link SortedSet}, instead of the * {@link Collection} specified in the {@link Multimap} interface. */ @Override public SortedSet<V> removeAll(@Nullable Object key) { return (SortedSet<V>) super.removeAll(key); } /** * Stores a collection of values with the same key, replacing any existing * values for that key. The returned collection is immutable. * * <p>Because a {@code SortedSetMultimap} has unique sorted values for a given * key, this method returns a {@link SortedSet}, 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 SortedSet<V> replaceValues( @Nullable K key, Iterable<? extends V> values) { return (SortedSet<V>) super.replaceValues(key, 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 public Map<K, Collection<V>> asMap() { return super.asMap(); } /** * {@inheritDoc} * * Consequently, the values do not follow their natural ordering or the * ordering of the value comparator. */ @Override public Collection<V> values() { return super.values(); } private static final long serialVersionUID = 430848587173315748L; }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.SortedLists.KeyAbsentBehavior.NEXT_LOWER; import static com.google.common.collect.SortedLists.KeyPresentBehavior.ANY_PRESENT; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.SortedLists.KeyAbsentBehavior; import com.google.common.collect.SortedLists.KeyPresentBehavior; import com.google.common.primitives.Ints; import java.io.Serializable; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; /** * An efficient immutable implementation of a {@link RangeSet}. * * @author Louis Wasserman * @since 14.0 */ @Beta public final class ImmutableRangeSet<C extends Comparable> extends AbstractRangeSet<C> implements Serializable { @SuppressWarnings("unchecked") private static final ImmutableRangeSet EMPTY = new ImmutableRangeSet(ImmutableList.of()); @SuppressWarnings("unchecked") private static final ImmutableRangeSet ALL = new ImmutableRangeSet(ImmutableList.of(Range.all())); /** * Returns an empty immutable range set. */ @SuppressWarnings("unchecked") public static <C extends Comparable> ImmutableRangeSet<C> of() { return EMPTY; } /** * Returns an immutable range set containing the single range {@link Range#all()}. */ @SuppressWarnings("unchecked") static <C extends Comparable> ImmutableRangeSet<C> all() { return ALL; } /** * Returns an immutable range set containing the specified single range. If {@link Range#isEmpty() * range.isEmpty()}, this is equivalent to {@link ImmutableRangeSet#of()}. */ public static <C extends Comparable> ImmutableRangeSet<C> of(Range<C> range) { checkNotNull(range); if (range.isEmpty()) { return of(); } else if (range.equals(Range.all())) { return all(); } else { return new ImmutableRangeSet<C>(ImmutableList.of(range)); } } /** * Returns an immutable copy of the specified {@code RangeSet}. */ public static <C extends Comparable> ImmutableRangeSet<C> copyOf(RangeSet<C> rangeSet) { checkNotNull(rangeSet); if (rangeSet.isEmpty()) { return of(); } else if (rangeSet.encloses(Range.<C>all())) { return all(); } if (rangeSet instanceof ImmutableRangeSet) { ImmutableRangeSet<C> immutableRangeSet = (ImmutableRangeSet<C>) rangeSet; if (!immutableRangeSet.isPartialView()) { return immutableRangeSet; } } return new ImmutableRangeSet<C>(ImmutableList.copyOf(rangeSet.asRanges())); } ImmutableRangeSet(ImmutableList<Range<C>> ranges) { this.ranges = ranges; } private ImmutableRangeSet(ImmutableList<Range<C>> ranges, ImmutableRangeSet<C> complement) { this.ranges = ranges; this.complement = complement; } private transient final ImmutableList<Range<C>> ranges; @Override public boolean encloses(Range<C> otherRange) { int index = SortedLists.binarySearch(ranges, Range.<C>lowerBoundFn(), otherRange.lowerBound, Ordering.natural(), ANY_PRESENT, NEXT_LOWER); return index != -1 && ranges.get(index).encloses(otherRange); } @Override public Range<C> rangeContaining(C value) { int index = SortedLists.binarySearch(ranges, Range.<C>lowerBoundFn(), Cut.belowValue(value), Ordering.natural(), ANY_PRESENT, NEXT_LOWER); if (index != -1) { Range<C> range = ranges.get(index); return range.contains(value) ? range : null; } return null; } @Override public Range<C> span() { if (ranges.isEmpty()) { throw new NoSuchElementException(); } return Range.create( ranges.get(0).lowerBound, ranges.get(ranges.size() - 1).upperBound); } @Override public boolean isEmpty() { return ranges.isEmpty(); } @Override public void add(Range<C> range) { throw new UnsupportedOperationException(); } @Override public void addAll(RangeSet<C> other) { throw new UnsupportedOperationException(); } @Override public void remove(Range<C> range) { throw new UnsupportedOperationException(); } @Override public void removeAll(RangeSet<C> other) { throw new UnsupportedOperationException(); } @Override public ImmutableSet<Range<C>> asRanges() { if (ranges.isEmpty()) { return ImmutableSet.of(); } return new RegularImmutableSortedSet<Range<C>>(ranges, Range.RANGE_LEX_ORDERING); } private transient ImmutableRangeSet<C> complement; private final class ComplementRanges extends ImmutableList<Range<C>> { // True if the "positive" range set is empty or bounded below. private final boolean positiveBoundedBelow; // True if the "positive" range set is empty or bounded above. private final boolean positiveBoundedAbove; private final int size; ComplementRanges() { this.positiveBoundedBelow = ranges.get(0).hasLowerBound(); this.positiveBoundedAbove = Iterables.getLast(ranges).hasUpperBound(); int size = ranges.size() - 1; if (positiveBoundedBelow) { size++; } if (positiveBoundedAbove) { size++; } this.size = size; } @Override public int size() { return size; } @Override public Range<C> get(int index) { checkElementIndex(index, size); Cut<C> lowerBound; if (positiveBoundedBelow) { lowerBound = (index == 0) ? Cut.<C>belowAll() : ranges.get(index - 1).upperBound; } else { lowerBound = ranges.get(index).upperBound; } Cut<C> upperBound; if (positiveBoundedAbove && index == size - 1) { upperBound = Cut.<C>aboveAll(); } else { upperBound = ranges.get(index + (positiveBoundedBelow ? 0 : 1)).lowerBound; } return Range.create(lowerBound, upperBound); } @Override boolean isPartialView() { return true; } } @Override public ImmutableRangeSet<C> complement() { ImmutableRangeSet<C> result = complement; if (result != null) { return result; } else if (ranges.isEmpty()) { return complement = all(); } else if (ranges.size() == 1 && ranges.get(0).equals(Range.all())) { return complement = of(); } else { ImmutableList<Range<C>> complementRanges = new ComplementRanges(); result = complement = new ImmutableRangeSet<C>(complementRanges, this); } return result; } /** * Returns a list containing the nonempty intersections of {@code range} * with the ranges in this range set. */ private ImmutableList<Range<C>> intersectRanges(final Range<C> range) { if (ranges.isEmpty() || range.isEmpty()) { return ImmutableList.of(); } else if (range.encloses(span())) { return ranges; } final int fromIndex; if (range.hasLowerBound()) { fromIndex = SortedLists.binarySearch( ranges, Range.<C>upperBoundFn(), range.lowerBound, KeyPresentBehavior.FIRST_AFTER, KeyAbsentBehavior.NEXT_HIGHER); } else { fromIndex = 0; } int toIndex; if (range.hasUpperBound()) { toIndex = SortedLists.binarySearch( ranges, Range.<C>lowerBoundFn(), range.upperBound, KeyPresentBehavior.FIRST_PRESENT, KeyAbsentBehavior.NEXT_HIGHER); } else { toIndex = ranges.size(); } final int length = toIndex - fromIndex; if (length == 0) { return ImmutableList.of(); } else { return new ImmutableList<Range<C>>() { @Override public int size() { return length; } @Override public Range<C> get(int index) { checkElementIndex(index, length); if (index == 0 || index == length - 1) { return ranges.get(index + fromIndex).intersection(range); } else { return ranges.get(index + fromIndex); } } @Override boolean isPartialView() { return true; } }; } } /** * Returns a view of the intersection of this range set with the given range. */ @Override public ImmutableRangeSet<C> subRangeSet(Range<C> range) { if (!isEmpty()) { Range<C> span = span(); if (range.encloses(span)) { return this; } else if (range.isConnected(span)) { return new ImmutableRangeSet<C>(intersectRanges(range)); } } return of(); } /** * Returns an {@link ImmutableSortedSet} containing the same values in the given domain * {@linkplain RangeSet#contains contained} by this range set. * * <p><b>Note:</b> {@code a.asSet(d).equals(b.asSet(d))} does not imply {@code a.equals(b)}! For * example, {@code a} and {@code b} could be {@code [2..4]} and {@code (1..5)}, or the empty * ranges {@code [3..3)} and {@code [4..4)}. * * <p><b>Warning:</b> Be extremely careful what you do with the {@code asSet} view of a large * range set (such as {@code ImmutableRangeSet.of(Range.greaterThan(0))}). Certain operations on * such a set can be performed efficiently, but others (such as {@link Set#hashCode} or * {@link Collections#frequency}) can cause major performance problems. * * <p>The returned set's {@link Object#toString} method returns a short-hand form of the set's * contents, such as {@code "[1..100]}"}. * * @throws IllegalArgumentException if neither this range nor the domain has a lower bound, or if * neither has an upper bound */ public ImmutableSortedSet<C> asSet(DiscreteDomain<C> domain) { checkNotNull(domain); if (isEmpty()) { return ImmutableSortedSet.of(); } Range<C> span = span().canonical(domain); if (!span.hasLowerBound()) { // according to the spec of canonical, neither this ImmutableRangeSet nor // the range have a lower bound throw new IllegalArgumentException( "Neither the DiscreteDomain nor this range set are bounded below"); } else if (!span.hasUpperBound()) { try { domain.maxValue(); } catch (NoSuchElementException e) { throw new IllegalArgumentException( "Neither the DiscreteDomain nor this range set are bounded above"); } } return new AsSet(domain); } private final class AsSet extends ImmutableSortedSet<C> { private final DiscreteDomain<C> domain; AsSet(DiscreteDomain<C> domain) { super(Ordering.natural()); this.domain = domain; } private transient Integer size; @Override public int size() { // racy single-check idiom Integer result = size; if (result == null) { long total = 0; for (Range<C> range : ranges) { total += ContiguousSet.create(range, domain).size(); if (total >= Integer.MAX_VALUE) { break; } } result = size = Ints.saturatedCast(total); } return result.intValue(); } @Override public UnmodifiableIterator<C> iterator() { return new AbstractIterator<C>() { final Iterator<Range<C>> rangeItr = ranges.iterator(); Iterator<C> elemItr = Iterators.emptyIterator(); @Override protected C computeNext() { while (!elemItr.hasNext()) { if (rangeItr.hasNext()) { elemItr = ContiguousSet.create(rangeItr.next(), domain).iterator(); } else { return endOfData(); } } return elemItr.next(); } }; } @Override @GwtIncompatible("NavigableSet") public UnmodifiableIterator<C> descendingIterator() { return new AbstractIterator<C>() { final Iterator<Range<C>> rangeItr = ranges.reverse().iterator(); Iterator<C> elemItr = Iterators.emptyIterator(); @Override protected C computeNext() { while (!elemItr.hasNext()) { if (rangeItr.hasNext()) { elemItr = ContiguousSet.create(rangeItr.next(), domain).descendingIterator(); } else { return endOfData(); } } return elemItr.next(); } }; } ImmutableSortedSet<C> subSet(Range<C> range) { return subRangeSet(range).asSet(domain); } @Override ImmutableSortedSet<C> headSetImpl(C toElement, boolean inclusive) { return subSet(Range.upTo(toElement, BoundType.forBoolean(inclusive))); } @Override ImmutableSortedSet<C> subSetImpl( C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) { if (!fromInclusive && !toInclusive && Range.compareOrThrow(fromElement, toElement) == 0) { return ImmutableSortedSet.of(); } return subSet(Range.range( fromElement, BoundType.forBoolean(fromInclusive), toElement, BoundType.forBoolean(toInclusive))); } @Override ImmutableSortedSet<C> tailSetImpl(C fromElement, boolean inclusive) { return subSet(Range.downTo(fromElement, BoundType.forBoolean(inclusive))); } @Override public boolean contains(@Nullable Object o) { if (o == null) { return false; } try { @SuppressWarnings("unchecked") // we catch CCE's C c = (C) o; return ImmutableRangeSet.this.contains(c); } catch (ClassCastException e) { return false; } } @Override int indexOf(Object target) { if (contains(target)) { @SuppressWarnings("unchecked") // if it's contained, it's definitely a C C c = (C) target; long total = 0; for (Range<C> range : ranges) { if (range.contains(c)) { return Ints.saturatedCast(total + ContiguousSet.create(range, domain).indexOf(c)); } else { total += ContiguousSet.create(range, domain).size(); } } throw new AssertionError("impossible"); } return -1; } @Override boolean isPartialView() { return ranges.isPartialView(); } @Override public String toString() { return ranges.toString(); } @Override Object writeReplace() { return new AsSetSerializedForm<C>(ranges, domain); } } private static class AsSetSerializedForm<C extends Comparable> implements Serializable { private final ImmutableList<Range<C>> ranges; private final DiscreteDomain<C> domain; AsSetSerializedForm(ImmutableList<Range<C>> ranges, DiscreteDomain<C> domain) { this.ranges = ranges; this.domain = domain; } Object readResolve() { return new ImmutableRangeSet<C>(ranges).asSet(domain); } } /** * Returns {@code true} if this immutable range set's implementation contains references to * user-created objects that aren't accessible via this range set's methods. This is generally * used to determine whether {@code copyOf} implementations should make an explicit copy to avoid * memory leaks. */ boolean isPartialView() { return ranges.isPartialView(); } /** * Returns a new builder for an immutable range set. */ public static <C extends Comparable<?>> Builder<C> builder() { return new Builder<C>(); } /** * A builder for immutable range sets. */ public static class Builder<C extends Comparable<?>> { private final RangeSet<C> rangeSet; public Builder() { this.rangeSet = TreeRangeSet.create(); } /** * Add the specified range to this builder. Adjacent/abutting ranges are permitted, but * empty ranges, or ranges with nonempty overlap, are forbidden. * * @throws IllegalArgumentException if {@code range} is empty or has nonempty intersection with * any ranges already added to the builder */ public Builder<C> add(Range<C> range) { if (range.isEmpty()) { throw new IllegalArgumentException("range must not be empty, but was " + range); } else if (!rangeSet.complement().encloses(range)) { for (Range<C> currentRange : rangeSet.asRanges()) { checkArgument( !currentRange.isConnected(range) || currentRange.intersection(range).isEmpty(), "Ranges may not overlap, but received %s and %s", currentRange, range); } throw new AssertionError("should have thrown an IAE above"); } rangeSet.add(range); return this; } /** * Add all ranges from the specified range set to this builder. Duplicate or connected ranges * are permitted, and will be merged in the resulting immutable range set. */ public Builder<C> addAll(RangeSet<C> ranges) { for (Range<C> range : ranges.asRanges()) { add(range); } return this; } /** * Returns an {@code ImmutableRangeSet} containing the ranges added to this builder. */ public ImmutableRangeSet<C> build() { return copyOf(rangeSet); } } private static final class SerializedForm<C extends Comparable> implements Serializable { private final ImmutableList<Range<C>> ranges; SerializedForm(ImmutableList<Range<C>> ranges) { this.ranges = ranges; } Object readResolve() { if (ranges.isEmpty()) { return of(); } else if (ranges.equals(ImmutableList.of(Range.all()))) { return all(); } else { return new ImmutableRangeSet<C>(ranges); } } } Object writeReplace() { return new SerializedForm<C>(ranges); } }
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.util.Collection; import java.util.Map; import java.util.Set; /** * A table which forwards all its method calls to another table. 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 Gregory Kick * @since 7.0 */ @GwtCompatible public abstract class ForwardingTable<R, C, V> extends ForwardingObject implements Table<R, C, V> { /** Constructor for use by subclasses. */ protected ForwardingTable() {} @Override protected abstract Table<R, C, V> delegate(); @Override public Set<Cell<R, C, V>> cellSet() { return delegate().cellSet(); } @Override public void clear() { delegate().clear(); } @Override public Map<R, V> column(C columnKey) { return delegate().column(columnKey); } @Override public Set<C> columnKeySet() { return delegate().columnKeySet(); } @Override public Map<C, Map<R, V>> columnMap() { return delegate().columnMap(); } @Override public boolean contains(Object rowKey, Object columnKey) { return delegate().contains(rowKey, columnKey); } @Override public boolean containsColumn(Object columnKey) { return delegate().containsColumn(columnKey); } @Override public boolean containsRow(Object rowKey) { return delegate().containsRow(rowKey); } @Override public boolean containsValue(Object value) { return delegate().containsValue(value); } @Override public V get(Object rowKey, Object columnKey) { return delegate().get(rowKey, columnKey); } @Override public boolean isEmpty() { return delegate().isEmpty(); } @Override public V put(R rowKey, C columnKey, V value) { return delegate().put(rowKey, columnKey, value); } @Override public void putAll(Table<? extends R, ? extends C, ? extends V> table) { delegate().putAll(table); } @Override public V remove(Object rowKey, Object columnKey) { return delegate().remove(rowKey, columnKey); } @Override public Map<C, V> row(R rowKey) { return delegate().row(rowKey); } @Override public Set<R> rowKeySet() { return delegate().rowKeySet(); } @Override public Map<R, Map<C, V>> rowMap() { return delegate().rowMap(); } @Override public int size() { return delegate().size(); } @Override public Collection<V> values() { return delegate().values(); } @Override public boolean equals(Object obj) { return (obj == this) || delegate().equals(obj); } @Override public int hashCode() { return delegate().hashCode(); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.annotation.Nullable; /** * An immutable {@link Multimap}. Does not permit null keys or values. * * <p>Unlike {@link Multimaps#unmodifiableMultimap(Multimap)}, which is * a <i>view</i> of a separate multimap which can still change, an instance of * {@code ImmutableMultimap} contains its own data and will <i>never</i> * change. {@code ImmutableMultimap} 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>In addition to methods defined by {@link Multimap}, an {@link #inverse} * method is also supported. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained"> * immutable collections</a>. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public abstract class ImmutableMultimap<K, V> extends AbstractMultimap<K, V> implements Serializable { /** Returns an empty multimap. */ public static <K, V> ImmutableMultimap<K, V> of() { return ImmutableListMultimap.of(); } /** * Returns an immutable multimap containing a single entry. */ public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1) { return ImmutableListMultimap.of(k1, v1); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1, K k2, V v2) { return ImmutableListMultimap.of(k1, v1, k2, v2); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3) { return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4); } /** * Returns an immutable multimap containing the given entries, in order. */ public static <K, V> ImmutableMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5); } // looking for of() with > 5 entries? Use the builder instead. /** * Returns a new builder. The generated builder is equivalent to the builder * created by the {@link Builder} constructor. */ public static <K, V> Builder<K, V> builder() { return new Builder<K, V>(); } /** * Multimap for {@link ImmutableMultimap.Builder} that maintains key and * value orderings, allows duplicate values, and performs better than * {@link LinkedListMultimap}. */ private static class BuilderMultimap<K, V> extends AbstractMapBasedMultimap<K, V> { BuilderMultimap() { super(new LinkedHashMap<K, Collection<V>>()); } @Override Collection<V> createCollection() { return Lists.newArrayList(); } private static final long serialVersionUID = 0; } /** * A builder for creating immutable multimap instances, especially * {@code public static final} multimaps ("constant multimaps"). Example: * <pre> {@code * * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP = * new ImmutableMultimap.Builder<String, Integer>() * .put("one", 1) * .putAll("several", 1, 2, 3) * .putAll("many", 1, 2, 3, 4, 5) * .build();}</pre> * * <p>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 class Builder<K, V> { Multimap<K, V> builderMultimap = new BuilderMultimap<K, V>(); Comparator<? super K> keyComparator; Comparator<? super V> valueComparator; /** * Creates a new builder. The returned builder is equivalent to the builder * generated by {@link ImmutableMultimap#builder}. */ public Builder() {} /** * Adds a key-value mapping to the built multimap. */ public Builder<K, V> put(K key, V value) { builderMultimap.put(checkNotNull(key), checkNotNull(value)); return this; } /** * Adds an entry to the built multimap. * * @since 11.0 */ public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { builderMultimap.put( checkNotNull(entry.getKey()), checkNotNull(entry.getValue())); return this; } /** * Stores a collection of values with the same key in the built multimap. * * @throws NullPointerException if {@code key}, {@code values}, or any * element in {@code values} is null. The builder is left in an invalid * state. */ public Builder<K, V> putAll(K key, Iterable<? extends V> values) { Collection<V> valueList = builderMultimap.get(checkNotNull(key)); for (V value : values) { valueList.add(checkNotNull(value)); } return this; } /** * Stores an array of values with the same key in the built multimap. * * @throws NullPointerException if the key or any value is null. The builder * is left in an invalid state. */ public Builder<K, V> putAll(K key, V... values) { return putAll(key, Arrays.asList(values)); } /** * Stores another multimap's entries in the built multimap. The generated * multimap's key and value orderings correspond to the iteration ordering * of the {@code multimap.asMap()} view, with new keys and values following * any existing keys and values. * * @throws NullPointerException if any key or value in {@code multimap} is * null. The builder is left in an invalid state. */ 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; } /** * Specifies the ordering of the generated multimap's keys. * * @since 8.0 */ public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) { this.keyComparator = checkNotNull(keyComparator); return this; } /** * Specifies the ordering of the generated multimap's values for each key. * * @since 8.0 */ public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) { this.valueComparator = checkNotNull(valueComparator); return this; } /** * Returns a newly-created immutable multimap. */ public ImmutableMultimap<K, V> build() { if (valueComparator != null) { for (Collection<V> values : builderMultimap.asMap().values()) { List<V> list = (List <V>) values; Collections.sort(list, valueComparator); } } if (keyComparator != null) { Multimap<K, V> sortedCopy = new BuilderMultimap<K, V>(); List<Map.Entry<K, Collection<V>>> entries = Lists.newArrayList( builderMultimap.asMap().entrySet()); Collections.sort( entries, Ordering.from(keyComparator).<K>onKeys()); for (Map.Entry<K, Collection<V>> entry : entries) { sortedCopy.putAll(entry.getKey(), entry.getValue()); } builderMultimap = sortedCopy; } return copyOf(builderMultimap); } } /** * Returns an immutable 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. * * <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> ImmutableMultimap<K, V> copyOf( Multimap<? extends K, ? extends V> multimap) { if (multimap instanceof ImmutableMultimap) { @SuppressWarnings("unchecked") // safe since multimap is not writable ImmutableMultimap<K, V> kvMultimap = (ImmutableMultimap<K, V>) multimap; if (!kvMultimap.isPartialView()) { return kvMultimap; } } return ImmutableListMultimap.copyOf(multimap); } final transient ImmutableMap<K, ? extends ImmutableCollection<V>> map; final transient int size; // These constants allow the deserialization code to set final fields. This // holder class makes sure they are not initialized unless an instance is // deserialized. @GwtIncompatible("java serialization is not supported") static class FieldSettersHolder { static final Serialization.FieldSetter<ImmutableMultimap> MAP_FIELD_SETTER = Serialization.getFieldSetter( ImmutableMultimap.class, "map"); static final Serialization.FieldSetter<ImmutableMultimap> SIZE_FIELD_SETTER = Serialization.getFieldSetter( ImmutableMultimap.class, "size"); static final Serialization.FieldSetter<ImmutableSetMultimap> EMPTY_SET_FIELD_SETTER = Serialization.getFieldSetter( ImmutableSetMultimap.class, "emptySet"); } ImmutableMultimap(ImmutableMap<K, ? extends ImmutableCollection<V>> map, int size) { this.map = map; this.size = size; } // mutators (not supported) /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public ImmutableCollection<V> removeAll(Object key) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public ImmutableCollection<V> replaceValues(K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public void clear() { throw new UnsupportedOperationException(); } /** * Returns an immutable collection of the values for the given key. If no * mappings in the multimap have the provided key, an empty immutable * collection is returned. The values are in the same order as the parameters * used to build this multimap. */ @Override public abstract ImmutableCollection<V> get(K key); /** * Returns an immutable multimap which is the inverse of this one. For every * key-value mapping in the original, the result will have a mapping with * key and value reversed. * * @since 11.0 */ public abstract ImmutableMultimap<V, K> inverse(); /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public boolean put(K key, V value) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public boolean putAll(K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public boolean remove(Object key, Object value) { throw new UnsupportedOperationException(); } /** * Returns {@code true} if this immutable multimap's implementation contains references to * user-created objects that aren't accessible via this multimap's methods. This is generally * used to determine whether {@code copyOf} implementations should make an explicit copy to avoid * memory leaks. */ boolean isPartialView() { return map.isPartialView(); } // accessors @Override public boolean containsKey(@Nullable Object key) { return map.containsKey(key); } @Override public boolean containsValue(@Nullable Object value) { return value != null && super.containsValue(value); } @Override public int size() { return size; } // views /** * Returns an immutable set of the distinct keys in this multimap. These keys * are ordered according to when they first appeared during the construction * of this multimap. */ @Override public ImmutableSet<K> keySet() { return map.keySet(); } /** * Returns an immutable map that associates each key with its corresponding * values in the multimap. */ @Override @SuppressWarnings("unchecked") // a widening cast public ImmutableMap<K, Collection<V>> asMap() { return (ImmutableMap) map; } @Override Map<K, Collection<V>> createAsMap() { throw new AssertionError("should never be called"); } /** * 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. */ @Override public ImmutableCollection<Entry<K, V>> entries() { return (ImmutableCollection<Entry<K, V>>) super.entries(); } @Override ImmutableCollection<Entry<K, V>> createEntries() { return new EntryCollection<K, V>(this); } private static class EntryCollection<K, V> extends ImmutableCollection<Entry<K, V>> { final ImmutableMultimap<K, V> multimap; EntryCollection(ImmutableMultimap<K, V> multimap) { this.multimap = multimap; } @Override public UnmodifiableIterator<Entry<K, V>> iterator() { return multimap.entryIterator(); } @Override boolean isPartialView() { return multimap.isPartialView(); } @Override public int size() { return multimap.size(); } @Override public boolean contains(Object object) { if (object instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) object; return multimap.containsEntry(entry.getKey(), entry.getValue()); } return false; } private static final long serialVersionUID = 0; } private abstract class Itr<T> extends UnmodifiableIterator<T> { final Iterator<Entry<K, Collection<V>>> mapIterator = asMap().entrySet().iterator(); K key = null; Iterator<V> valueIterator = Iterators.emptyIterator(); abstract T output(K key, V value); @Override public boolean hasNext() { return mapIterator.hasNext() || valueIterator.hasNext(); } @Override public T next() { if (!valueIterator.hasNext()) { Entry<K, Collection<V>> mapEntry = mapIterator.next(); key = mapEntry.getKey(); valueIterator = mapEntry.getValue().iterator(); } return output(key, valueIterator.next()); } } @Override UnmodifiableIterator<Entry<K, V>> entryIterator() { return new Itr<Entry<K, V>>() { @Override Entry<K, V> output(K key, V value) { return Maps.immutableEntry(key, value); } }; } /** * Returns a collection, which may contain duplicates, of all keys. The number * of times a key appears in the returned multiset equals the number of * mappings the key has in the multimap. Duplicate keys appear consecutively * in the multiset's iteration order. */ @Override public ImmutableMultiset<K> keys() { return (ImmutableMultiset<K>) super.keys(); } @Override ImmutableMultiset<K> createKeys() { return new Keys(); } @SuppressWarnings("serial") // Uses writeReplace, not default serialization class Keys extends ImmutableMultiset<K> { @Override public boolean contains(@Nullable Object object) { return containsKey(object); } @Override public int count(@Nullable Object element) { Collection<V> values = map.get(element); return (values == null) ? 0 : values.size(); } @Override public Set<K> elementSet() { return keySet(); } @Override public int size() { return ImmutableMultimap.this.size(); } @Override Multiset.Entry<K> getEntry(int index) { Map.Entry<K, ? extends Collection<V>> entry = map.entrySet().asList().get(index); return Multisets.immutableEntry(entry.getKey(), entry.getValue().size()); } @Override boolean isPartialView() { return true; } } /** * Returns an immutable collection of the values in this multimap. Its * iterator traverses the values for the first key, the values for the second * key, and so on. */ @Override public ImmutableCollection<V> values() { return (ImmutableCollection<V>) super.values(); } @Override ImmutableCollection<V> createValues() { return new Values<K, V>(this); } @Override UnmodifiableIterator<V> valueIterator() { return new Itr<V>() { @Override V output(K key, V value) { return value; } }; } private static final class Values<K, V> extends ImmutableCollection<V> { private transient final ImmutableMultimap<K, V> multimap; Values(ImmutableMultimap<K, V> multimap) { this.multimap = multimap; } @Override public boolean contains(@Nullable Object object) { return multimap.containsValue(object); } @Override public UnmodifiableIterator<V> iterator() { return multimap.valueIterator(); } @GwtIncompatible("not present in emulated superclass") @Override int copyIntoArray(Object[] dst, int offset) { for (ImmutableCollection<V> valueCollection : multimap.map.values()) { offset = valueCollection.copyIntoArray(dst, offset); } return offset; } @Override public int size() { return multimap.size(); } @Override boolean isPartialView() { return true; } private static final long serialVersionUID = 0; } 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 java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Field; import java.util.Collection; import java.util.Map; /** * Provides static methods for serializing collection classes. * * <p>This class assists the implementation of collection classes. Do not use * this class to serialize collections that are defined elsewhere. * * @author Jared Levy */ final class Serialization { private Serialization() {} /** * Reads a count corresponding to a serialized map, multiset, or multimap. It * returns the size of a map serialized by {@link * #writeMap(Map, ObjectOutputStream)}, the number of distinct elements in a * multiset serialized by {@link * #writeMultiset(Multiset, ObjectOutputStream)}, or the number of distinct * keys in a multimap serialized by {@link * #writeMultimap(Multimap, ObjectOutputStream)}. * * <p>The returned count may be used to construct an empty collection of the * appropriate capacity before calling any of the {@code populate} methods. */ static int readCount(ObjectInputStream stream) throws IOException { return stream.readInt(); } /** * Stores the contents of a map in an output stream, as part of serialization. * It does not support concurrent maps whose content may change while the * method is running. * * <p>The serialized output consists of the number of entries, first key, * first value, second key, second value, and so on. */ static <K, V> void writeMap(Map<K, V> map, ObjectOutputStream stream) throws IOException { stream.writeInt(map.size()); for (Map.Entry<K, V> entry : map.entrySet()) { stream.writeObject(entry.getKey()); stream.writeObject(entry.getValue()); } } /** * Populates a map by reading an input stream, as part of deserialization. * See {@link #writeMap} for the data format. */ static <K, V> void populateMap(Map<K, V> map, ObjectInputStream stream) throws IOException, ClassNotFoundException { int size = stream.readInt(); populateMap(map, stream, size); } /** * Populates a map by reading an input stream, as part of deserialization. * See {@link #writeMap} for the data format. The size is determined by a * prior call to {@link #readCount}. */ static <K, V> void populateMap(Map<K, V> map, ObjectInputStream stream, int size) throws IOException, ClassNotFoundException { for (int i = 0; i < size; i++) { @SuppressWarnings("unchecked") // reading data stored by writeMap K key = (K) stream.readObject(); @SuppressWarnings("unchecked") // reading data stored by writeMap V value = (V) stream.readObject(); map.put(key, value); } } /** * Stores the contents of a multiset in an output stream, as part of * serialization. It does not support concurrent multisets whose content may * change while the method is running. * * <p>The serialized output consists of the number of distinct elements, the * first element, its count, the second element, its count, and so on. */ static <E> void writeMultiset( Multiset<E> multiset, ObjectOutputStream stream) throws IOException { int entryCount = multiset.entrySet().size(); stream.writeInt(entryCount); for (Multiset.Entry<E> entry : multiset.entrySet()) { stream.writeObject(entry.getElement()); stream.writeInt(entry.getCount()); } } /** * Populates a multiset by reading an input stream, as part of * deserialization. See {@link #writeMultiset} for the data format. */ static <E> void populateMultiset( Multiset<E> multiset, ObjectInputStream stream) throws IOException, ClassNotFoundException { int distinctElements = stream.readInt(); populateMultiset(multiset, stream, distinctElements); } /** * Populates a multiset by reading an input stream, as part of * deserialization. See {@link #writeMultiset} for the data format. The number * of distinct elements is determined by a prior call to {@link #readCount}. */ static <E> void populateMultiset( Multiset<E> multiset, ObjectInputStream stream, int distinctElements) throws IOException, ClassNotFoundException { for (int i = 0; i < distinctElements; i++) { @SuppressWarnings("unchecked") // reading data stored by writeMultiset E element = (E) stream.readObject(); int count = stream.readInt(); multiset.add(element, count); } } /** * Stores the contents of a multimap in an output stream, as part of * serialization. It does not support concurrent multimaps whose content may * change while the method is running. The {@link Multimap#asMap} view * determines the ordering in which data is written to the stream. * * <p>The serialized output consists of the number of distinct keys, and then * for each distinct key: the key, the number of values for that key, and the * key's values. */ static <K, V> void writeMultimap( Multimap<K, V> multimap, ObjectOutputStream stream) throws IOException { stream.writeInt(multimap.asMap().size()); for (Map.Entry<K, Collection<V>> entry : multimap.asMap().entrySet()) { stream.writeObject(entry.getKey()); stream.writeInt(entry.getValue().size()); for (V value : entry.getValue()) { stream.writeObject(value); } } } /** * Populates a multimap by reading an input stream, as part of * deserialization. See {@link #writeMultimap} for the data format. */ static <K, V> void populateMultimap( Multimap<K, V> multimap, ObjectInputStream stream) throws IOException, ClassNotFoundException { int distinctKeys = stream.readInt(); populateMultimap(multimap, stream, distinctKeys); } /** * Populates a multimap by reading an input stream, as part of * deserialization. See {@link #writeMultimap} for the data format. The number * of distinct keys is determined by a prior call to {@link #readCount}. */ static <K, V> void populateMultimap( Multimap<K, V> multimap, ObjectInputStream stream, int distinctKeys) throws IOException, ClassNotFoundException { for (int i = 0; i < distinctKeys; i++) { @SuppressWarnings("unchecked") // reading data stored by writeMultimap K key = (K) stream.readObject(); Collection<V> values = multimap.get(key); int valueCount = stream.readInt(); for (int j = 0; j < valueCount; j++) { @SuppressWarnings("unchecked") // reading data stored by writeMultimap V value = (V) stream.readObject(); values.add(value); } } } // Secret sauce for setting final fields; don't make it public. static <T> FieldSetter<T> getFieldSetter( final Class<T> clazz, String fieldName) { try { Field field = clazz.getDeclaredField(fieldName); return new FieldSetter<T>(field); } catch (NoSuchFieldException e) { throw new AssertionError(e); // programmer error } } // Secret sauce for setting final fields; don't make it public. static final class FieldSetter<T> { private final Field field; private FieldSetter(Field field) { this.field = field; field.setAccessible(true); } void set(T instance, Object value) { try { field.set(instance, value); } catch (IllegalAccessException impossible) { throw new AssertionError(impossible); } } void set(T instance, int value) { try { field.set(instance, value); } catch (IllegalAccessException impossible) { throw new AssertionError(impossible); } } } }
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; /** * Indicates whether an endpoint of some range is contained in the range itself ("closed") or not * ("open"). If a range is unbounded on a side, it is neither open nor closed on that side; the * bound simply does not exist. * * @since 10.0 */ @GwtCompatible public enum BoundType { /** * The endpoint value <i>is not</i> considered part of the set ("exclusive"). */ OPEN { @Override BoundType flip() { return CLOSED; } }, /** * The endpoint value <i>is</i> considered part of the set ("inclusive"). */ CLOSED { @Override BoundType flip() { return OPEN; } }; /** * Returns the bound type corresponding to a boolean value for inclusivity. */ static BoundType forBoolean(boolean inclusive) { return inclusive ? CLOSED : OPEN; } abstract BoundType flip(); }
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 java.util.Collection; import java.util.Comparator; import javax.annotation.Nullable; /** * An empty immutable sorted multiset. * * @author Louis Wasserman */ @SuppressWarnings("serial") // Uses writeReplace, not default serialization final class EmptyImmutableSortedMultiset<E> extends ImmutableSortedMultiset<E> { private final ImmutableSortedSet<E> elementSet; EmptyImmutableSortedMultiset(Comparator<? super E> comparator) { this.elementSet = ImmutableSortedSet.emptySet(comparator); } @Override public Entry<E> firstEntry() { return null; } @Override public Entry<E> lastEntry() { return null; } @Override public int count(@Nullable Object element) { return 0; } @Override public boolean containsAll(Collection<?> targets) { return targets.isEmpty(); } @Override public int size() { return 0; } @Override public ImmutableSortedSet<E> elementSet() { return elementSet; } @Override Entry<E> getEntry(int index) { throw new AssertionError("should never be called"); } @Override public ImmutableSortedMultiset<E> headMultiset(E upperBound, BoundType boundType) { checkNotNull(upperBound); checkNotNull(boundType); return this; } @Override public ImmutableSortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) { checkNotNull(lowerBound); checkNotNull(boundType); return this; } @Override public UnmodifiableIterator<E> iterator() { return Iterators.emptyIterator(); } @Override public boolean equals(@Nullable Object object) { if (object instanceof Multiset) { Multiset<?> other = (Multiset<?>) object; return other.isEmpty(); } return false; } @Override boolean isPartialView() { return false; } @Override int copyIntoArray(Object[] dst, int offset) { return offset; } @Override public ImmutableList<E> asList() { return ImmutableList.of(); } }
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.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Maps.keyOrNull; import com.google.common.annotations.GwtCompatible; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Map; import java.util.NavigableMap; import java.util.SortedMap; import java.util.TreeMap; import javax.annotation.Nullable; /** * An immutable {@link SortedMap}. Does not permit null keys or values. * * <p>Unlike {@link Collections#unmodifiableSortedMap}, which is a <i>view</i> * of a separate map which can still change, an instance of {@code * ImmutableSortedMap} contains its own data and will <i>never</i> change. * {@code ImmutableSortedMap} is convenient for {@code public static final} maps * ("constant maps") and also lets you easily make a "defensive copy" of a map * 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 Jared Levy * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library; implements {@code * NavigableMap} since 12.0) */ @GwtCompatible(serializable = true, emulated = true) public abstract class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxverideShim<K, V> implements NavigableMap<K, V> { /* * TODO(kevinb): Confirm that ImmutableSortedMap is faster to construct and * uses less memory than TreeMap; then say so in the class Javadoc. */ private static final Comparator<Comparable> NATURAL_ORDER = Ordering.natural(); private static final ImmutableSortedMap<Comparable, Object> NATURAL_EMPTY_MAP = new EmptyImmutableSortedMap<Comparable, Object>(NATURAL_ORDER); static <K, V> ImmutableSortedMap<K, V> emptyMap(Comparator<? super K> comparator) { if (Ordering.natural().equals(comparator)) { return of(); } else { return new EmptyImmutableSortedMap<K, V>(comparator); } } static <K, V> ImmutableSortedMap<K, V> fromSortedEntries( Comparator<? super K> comparator, int size, Entry<K, V>[] entries) { if (size == 0) { return emptyMap(comparator); } ImmutableList.Builder<K> keyBuilder = ImmutableList.builder(); ImmutableList.Builder<V> valueBuilder = ImmutableList.builder(); for (int i = 0; i < size; i++) { Entry<K, V> entry = entries[i]; keyBuilder.add(entry.getKey()); valueBuilder.add(entry.getValue()); } return new RegularImmutableSortedMap<K, V>( new RegularImmutableSortedSet<K>(keyBuilder.build(), comparator), valueBuilder.build()); } static <K, V> ImmutableSortedMap<K, V> from( ImmutableSortedSet<K> keySet, ImmutableList<V> valueList) { if (keySet.isEmpty()) { return emptyMap(keySet.comparator()); } else { return new RegularImmutableSortedMap<K, V>( (RegularImmutableSortedSet<K>) keySet, valueList); } } /** * Returns the empty sorted map. */ @SuppressWarnings("unchecked") // unsafe, comparator() returns a comparator on the specified type // TODO(kevinb): evaluate whether or not of().comparator() should return null public static <K, V> ImmutableSortedMap<K, V> of() { return (ImmutableSortedMap<K, V>) NATURAL_EMPTY_MAP; } /** * Returns an immutable map containing a single entry. */ public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(K k1, V v1) { return from(ImmutableSortedSet.of(k1), ImmutableList.of(v1)); } /** * Returns an immutable sorted map containing the given entries, sorted by the * natural ordering of their keys. * * @throws IllegalArgumentException if the two keys are equal according to * their natural ordering */ @SuppressWarnings("unchecked") public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(K k1, V v1, K k2, V v2) { return fromEntries(Ordering.natural(), false, 2, entryOf(k1, v1), entryOf(k2, v2)); } /** * Returns an immutable sorted map containing the given entries, sorted by the * natural ordering of their keys. * * @throws IllegalArgumentException if any two keys are equal according to * their natural ordering */ @SuppressWarnings("unchecked") public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) { return fromEntries(Ordering.natural(), false, 3, entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3)); } /** * Returns an immutable sorted map containing the given entries, sorted by the * natural ordering of their keys. * * @throws IllegalArgumentException if any two keys are equal according to * their natural ordering */ @SuppressWarnings("unchecked") public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { return fromEntries(Ordering.natural(), false, 4, entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4)); } /** * Returns an immutable sorted map containing the given entries, sorted by the * natural ordering of their keys. * * @throws IllegalArgumentException if any two keys are equal according to * their natural ordering */ @SuppressWarnings("unchecked") public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { return fromEntries(Ordering.natural(), false, 5, entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5)); } /** * Returns an immutable map containing the same entries as {@code map}, sorted * by the natural ordering of the keys. * * <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 a map with keys * that are not mutually comparable. * * @throws ClassCastException if the keys in {@code map} are not mutually * comparable * @throws NullPointerException if any key or value in {@code map} is null * @throws IllegalArgumentException if any two keys are equal according to * their natural ordering */ public static <K, V> ImmutableSortedMap<K, V> copyOf( Map<? extends K, ? extends V> map) { // Hack around K not being a subtype of Comparable. // Unsafe, see ImmutableSortedSetFauxverideShim. @SuppressWarnings("unchecked") Ordering<K> naturalOrder = (Ordering<K>) Ordering.<Comparable>natural(); return copyOfInternal(map, naturalOrder); } /** * Returns an immutable map containing the same entries as {@code map}, with * keys sorted by the provided comparator. * * <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 map} is null * @throws IllegalArgumentException if any two keys are equal according to the * comparator */ public static <K, V> ImmutableSortedMap<K, V> copyOf( Map<? extends K, ? extends V> map, Comparator<? super K> comparator) { return copyOfInternal(map, checkNotNull(comparator)); } /** * Returns an immutable map containing the same entries as the provided sorted * map, with the same ordering. * * <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 map} is null */ @SuppressWarnings("unchecked") public static <K, V> ImmutableSortedMap<K, V> copyOfSorted( SortedMap<K, ? extends V> map) { Comparator<? super K> comparator = map.comparator(); if (comparator == null) { // If map has a null comparator, the keys should have a natural ordering, // even though K doesn't explicitly implement Comparable. comparator = (Comparator<? super K>) NATURAL_ORDER; } return copyOfInternal(map, comparator); } private static <K, V> ImmutableSortedMap<K, V> copyOfInternal( Map<? extends K, ? extends V> map, Comparator<? super K> comparator) { boolean sameComparator = false; if (map instanceof SortedMap) { SortedMap<?, ?> sortedMap = (SortedMap<?, ?>) map; Comparator<?> comparator2 = sortedMap.comparator(); sameComparator = (comparator2 == null) ? comparator == NATURAL_ORDER : comparator.equals(comparator2); } if (sameComparator && (map instanceof ImmutableSortedMap)) { // TODO(kevinb): Prove that this cast is safe, even though // Collections.unmodifiableSortedMap requires the same key type. @SuppressWarnings("unchecked") ImmutableSortedMap<K, V> kvMap = (ImmutableSortedMap<K, V>) map; if (!kvMap.isPartialView()) { return kvMap; } } // "adding" type params to an array of a raw type should be safe as // long as no one can ever cast that same array instance back to a // raw type. @SuppressWarnings("unchecked") Entry<K, V>[] entries = map.entrySet().toArray(new Entry[0]); return fromEntries(comparator, sameComparator, entries.length, entries); } static <K, V> ImmutableSortedMap<K, V> fromEntries( Comparator<? super K> comparator, boolean sameComparator, int size, Entry<K, V>... entries) { for (int i = 0; i < size; i++) { Entry<K, V> entry = entries[i]; entries[i] = entryOf(entry.getKey(), entry.getValue()); } if (!sameComparator) { sortEntries(comparator, size, entries); validateEntries(size, entries, comparator); } return fromSortedEntries(comparator, size, entries); } private static <K, V> void sortEntries( final Comparator<? super K> comparator, int size, Entry<K, V>[] entries) { Arrays.sort(entries, 0, size, Ordering.from(comparator).<K>onKeys()); } private static <K, V> void validateEntries(int size, Entry<K, V>[] entries, Comparator<? super K> comparator) { for (int i = 1; i < size; i++) { checkNoConflict(comparator.compare(entries[i - 1].getKey(), entries[i].getKey()) != 0, "key", entries[i - 1], entries[i]); } } /** * Returns a builder that creates immutable sorted maps whose keys are * ordered by their natural ordering. The sorted maps use {@link * Ordering#natural()} as the comparator. */ public static <K extends Comparable<?>, V> Builder<K, V> naturalOrder() { return new Builder<K, V>(Ordering.natural()); } /** * Returns a builder that creates immutable sorted maps with an explicit * comparator. If the comparator has a more general type than the map's keys, * such as creating a {@code SortedMap<Integer, String>} with a {@code * Comparator<Number>}, use the {@link Builder} constructor instead. * * @throws NullPointerException if {@code comparator} is null */ public static <K, V> Builder<K, V> orderedBy(Comparator<K> comparator) { return new Builder<K, V>(comparator); } /** * Returns a builder that creates immutable sorted maps whose keys are * ordered by the reverse of their natural ordering. */ public static <K extends Comparable<?>, V> Builder<K, V> reverseOrder() { return new Builder<K, V>(Ordering.natural().reverse()); } /** * A builder for creating immutable sorted map instances, especially {@code * public static final} maps ("constant maps"). Example: <pre> {@code * * static final ImmutableSortedMap<Integer, String> INT_TO_WORD = * new ImmutableSortedMap.Builder<Integer, String>(Ordering.natural()) * .put(1, "one") * .put(2, "two") * .put(3, "three") * .build();}</pre> * * <p>For <i>small</i> immutable sorted maps, the {@code ImmutableSortedMap.of()} * methods are even more convenient. * * <p>Builder instances can be reused - it is safe to call {@link #build} * multiple times to build multiple maps in series. Each map is a superset of * the maps created before it. * * @since 2.0 (imported from Google Collections Library) */ public static class Builder<K, V> extends ImmutableMap.Builder<K, V> { private final Comparator<? super K> comparator; /** * Creates a new builder. The returned builder is equivalent to the builder * generated by {@link ImmutableSortedMap#orderedBy}. */ @SuppressWarnings("unchecked") public Builder(Comparator<? super K> comparator) { this.comparator = checkNotNull(comparator); } /** * Associates {@code key} with {@code value} in the built map. Duplicate * keys, according to the comparator (which might be the keys' natural * order), are not allowed, and will cause {@link #build} to fail. */ @Override public Builder<K, V> put(K key, V value) { super.put(key, value); return this; } /** * Adds the given {@code entry} to the map, making it immutable if * necessary. Duplicate keys, according to the comparator (which might be * the keys' natural order), are not allowed, and will cause {@link #build} * to fail. * * @since 11.0 */ @Override public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { super.put(entry); return this; } /** * Associates all of the given map's keys and values in the built map. * Duplicate keys, according to the comparator (which might be the keys' * natural order), are not allowed, and will cause {@link #build} to fail. * * @throws NullPointerException if any key or value in {@code map} is null */ @Override public Builder<K, V> putAll(Map<? extends K, ? extends V> map) { super.putAll(map); return this; } /** * Returns a newly-created immutable sorted map. * * @throws IllegalArgumentException if any two keys are equal according to * the comparator (which might be the keys' natural order) */ @Override public ImmutableSortedMap<K, V> build() { return fromEntries(comparator, false, size, entries); } } ImmutableSortedMap() { } ImmutableSortedMap(ImmutableSortedMap<K, V> descendingMap) { this.descendingMap = descendingMap; } @Override public int size() { return values().size(); } @Override public boolean containsValue(@Nullable Object value) { return values().contains(value); } @Override boolean isPartialView() { return keySet().isPartialView() || values().isPartialView(); } /** * Returns an immutable set of the mappings in this map, sorted by the key * ordering. */ @Override public ImmutableSet<Entry<K, V>> entrySet() { return super.entrySet(); } /** * Returns an immutable sorted set of the keys in this map. */ @Override public abstract ImmutableSortedSet<K> keySet(); /** * Returns an immutable collection of the values in this map, sorted by the * ordering of the corresponding keys. */ @Override public abstract ImmutableCollection<V> values(); /** * Returns the comparator that orders the keys, which is * {@link Ordering#natural()} when the natural ordering of the keys is used. * Note that its behavior is not consistent with {@link TreeMap#comparator()}, * which returns {@code null} to indicate natural ordering. */ @Override public Comparator<? super K> comparator() { return keySet().comparator(); } @Override public K firstKey() { return keySet().first(); } @Override public K lastKey() { return keySet().last(); } /** * This method returns a {@code ImmutableSortedMap}, consisting of the entries * whose keys are less than {@code toKey}. * * <p>The {@link SortedMap#headMap} documentation states that a submap of a * submap throws an {@link IllegalArgumentException} if passed a {@code toKey} * greater than an earlier {@code toKey}. However, this method doesn't throw * an exception in that situation, but instead keeps the original {@code * toKey}. */ @Override public ImmutableSortedMap<K, V> headMap(K toKey) { return headMap(toKey, false); } /** * This method returns a {@code ImmutableSortedMap}, consisting of the entries * whose keys are less than (or equal to, if {@code inclusive}) {@code toKey}. * * <p>The {@link SortedMap#headMap} documentation states that a submap of a * submap throws an {@link IllegalArgumentException} if passed a {@code toKey} * greater than an earlier {@code toKey}. However, this method doesn't throw * an exception in that situation, but instead keeps the original {@code * toKey}. * * @since 12.0 */ @Override public abstract ImmutableSortedMap<K, V> headMap(K toKey, boolean inclusive); /** * This method returns a {@code ImmutableSortedMap}, consisting of the entries * whose keys ranges from {@code fromKey}, inclusive, to {@code toKey}, * exclusive. * * <p>The {@link SortedMap#subMap} documentation states that a submap of a * submap throws an {@link IllegalArgumentException} if passed a {@code * fromKey} less than an earlier {@code fromKey}. However, this method doesn't * throw an exception in that situation, but instead keeps the original {@code * fromKey}. Similarly, this method keeps the original {@code toKey}, instead * of throwing an exception, if passed a {@code toKey} greater than an earlier * {@code toKey}. */ @Override public ImmutableSortedMap<K, V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } /** * This method returns a {@code ImmutableSortedMap}, consisting of the entries * whose keys ranges from {@code fromKey} to {@code toKey}, inclusive or * exclusive as indicated by the boolean flags. * * <p>The {@link SortedMap#subMap} documentation states that a submap of a * submap throws an {@link IllegalArgumentException} if passed a {@code * fromKey} less than an earlier {@code fromKey}. However, this method doesn't * throw an exception in that situation, but instead keeps the original {@code * fromKey}. Similarly, this method keeps the original {@code toKey}, instead * of throwing an exception, if passed a {@code toKey} greater than an earlier * {@code toKey}. * * @since 12.0 */ @Override public ImmutableSortedMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { checkNotNull(fromKey); checkNotNull(toKey); checkArgument(comparator().compare(fromKey, toKey) <= 0, "expected fromKey <= toKey but %s > %s", fromKey, toKey); return headMap(toKey, toInclusive).tailMap(fromKey, fromInclusive); } /** * This method returns a {@code ImmutableSortedMap}, consisting of the entries * whose keys are greater than or equals to {@code fromKey}. * * <p>The {@link SortedMap#tailMap} documentation states that a submap of a * submap throws an {@link IllegalArgumentException} if passed a {@code * fromKey} less than an earlier {@code fromKey}. However, this method doesn't * throw an exception in that situation, but instead keeps the original {@code * fromKey}. */ @Override public ImmutableSortedMap<K, V> tailMap(K fromKey) { return tailMap(fromKey, true); } /** * This method returns a {@code ImmutableSortedMap}, consisting of the entries * whose keys are greater than (or equal to, if {@code inclusive}) * {@code fromKey}. * * <p>The {@link SortedMap#tailMap} documentation states that a submap of a * submap throws an {@link IllegalArgumentException} if passed a {@code * fromKey} less than an earlier {@code fromKey}. However, this method doesn't * throw an exception in that situation, but instead keeps the original {@code * fromKey}. * * @since 12.0 */ @Override public abstract ImmutableSortedMap<K, V> tailMap(K fromKey, boolean inclusive); @Override public Entry<K, V> lowerEntry(K key) { return headMap(key, false).lastEntry(); } @Override public K lowerKey(K key) { return keyOrNull(lowerEntry(key)); } @Override public Entry<K, V> floorEntry(K key) { return headMap(key, true).lastEntry(); } @Override public K floorKey(K key) { return keyOrNull(floorEntry(key)); } @Override public Entry<K, V> ceilingEntry(K key) { return tailMap(key, true).firstEntry(); } @Override public K ceilingKey(K key) { return keyOrNull(ceilingEntry(key)); } @Override public Entry<K, V> higherEntry(K key) { return tailMap(key, false).firstEntry(); } @Override public K higherKey(K key) { return keyOrNull(higherEntry(key)); } @Override public Entry<K, V> firstEntry() { return isEmpty() ? null : entrySet().asList().get(0); } @Override public Entry<K, V> lastEntry() { return isEmpty() ? null : entrySet().asList().get(size() - 1); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final Entry<K, V> pollFirstEntry() { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final Entry<K, V> pollLastEntry() { throw new UnsupportedOperationException(); } private transient ImmutableSortedMap<K, V> descendingMap; @Override public ImmutableSortedMap<K, V> descendingMap() { ImmutableSortedMap<K, V> result = descendingMap; if (result == null) { result = descendingMap = createDescendingMap(); } return result; } abstract ImmutableSortedMap<K, V> createDescendingMap(); @Override public ImmutableSortedSet<K> navigableKeySet() { return keySet(); } @Override public ImmutableSortedSet<K> descendingKeySet() { return keySet().descendingSet(); } /** * Serialized type for all ImmutableSortedMap instances. It captures the * logical contents and they are reconstructed using public factory methods. * This ensures that the implementation types remain as implementation * details. */ private static class SerializedForm extends ImmutableMap.SerializedForm { private final Comparator<Object> comparator; @SuppressWarnings("unchecked") SerializedForm(ImmutableSortedMap<?, ?> sortedMap) { super(sortedMap); comparator = (Comparator<Object>) sortedMap.comparator(); } @Override Object readResolve() { Builder<Object, Object> builder = new Builder<Object, Object>(comparator); return createMap(builder); } private static final long serialVersionUID = 0; } @Override Object writeReplace() { return new SerializedForm(this); } // This class is never actually serialized directly, but we have to make the // warning go away (and suppressing would suppress for all nested classes too) 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.Beta; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.math.BigInteger; import java.util.NoSuchElementException; /** * A descriptor for a <i>discrete</i> {@code Comparable} domain such as all * {@link Integer} instances. A discrete domain is one that supports the three basic * operations: {@link #next}, {@link #previous} and {@link #distance}, according * to their specifications. The methods {@link #minValue} and {@link #maxValue} * should also be overridden for bounded types. * * <p>A discrete domain always represents the <i>entire</i> set of values of its * type; it cannot represent partial domains such as "prime integers" or * "strings of length 5." * * <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 Kevin Bourrillion * @since 10.0 */ @GwtCompatible @Beta public abstract class DiscreteDomain<C extends Comparable> { /** * Returns the discrete domain for values of type {@code Integer}. * * @since 14.0 (since 10.0 as {@code DiscreteDomains.integers()}) */ 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; } @Override public String toString() { return "DiscreteDomain.integers()"; } private static final long serialVersionUID = 0; } /** * Returns the discrete domain for values of type {@code Long}. * * @since 14.0 (since 10.0 as {@code DiscreteDomains.longs()}) */ 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; } @Override public String toString() { return "DiscreteDomain.longs()"; } private static final long serialVersionUID = 0; } /** * Returns the discrete domain for values of type {@code BigInteger}. * * @since 15.0 */ 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 end.subtract(start).max(MIN_LONG).min(MAX_LONG).longValue(); } private Object readResolve() { return INSTANCE; } @Override public String toString() { return "DiscreteDomain.bigIntegers()"; } private static final long serialVersionUID = 0; } /** Constructor for use by subclasses. */ protected DiscreteDomain() {} /** * Returns the unique least value of type {@code C} that is greater than * {@code value}, or {@code null} if none exists. Inverse operation to {@link * #previous}. * * @param value any value of type {@code C} * @return the least value greater than {@code value}, or {@code null} if * {@code value} is {@code maxValue()} */ public abstract C next(C value); /** * Returns the unique greatest value of type {@code C} that is less than * {@code value}, or {@code null} if none exists. Inverse operation to {@link * #next}. * * @param value any value of type {@code C} * @return the greatest value less than {@code value}, or {@code null} if * {@code value} is {@code minValue()} */ public abstract C previous(C value); /** * Returns a signed value indicating how many nested invocations of {@link * #next} (if positive) or {@link #previous} (if negative) are needed to reach * {@code end} starting from {@code start}. For example, if {@code end = * next(next(next(start)))}, then {@code distance(start, end) == 3} and {@code * distance(end, start) == -3}. As well, {@code distance(a, a)} is always * zero. * * <p>Note that this function is necessarily well-defined for any discrete * type. * * @return the distance as described above, or {@link Long#MIN_VALUE} or * {@link Long#MAX_VALUE} if the distance is too small or too large, * respectively. */ public abstract long distance(C start, C end); /** * Returns the minimum value of type {@code C}, if it has one. The minimum * value is the unique value for which {@link Comparable#compareTo(Object)} * never returns a positive value for any input of type {@code C}. * * <p>The default implementation throws {@code NoSuchElementException}. * * @return the minimum value of type {@code C}; never null * @throws NoSuchElementException if the type has no (practical) minimum * value; for example, {@link java.math.BigInteger} */ public C minValue() { throw new NoSuchElementException(); } /** * Returns the maximum value of type {@code C}, if it has one. The maximum * value is the unique value for which {@link Comparable#compareTo(Object)} * never returns a negative value for any input of type {@code C}. * * <p>The default implementation throws {@code NoSuchElementException}. * * @return the maximum value of type {@code C}; never null * @throws NoSuchElementException if the type has no (practical) maximum * value; for example, {@link java.math.BigInteger} */ public C maxValue() { throw new NoSuchElementException(); } }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.util.Comparator; import javax.annotation.Nullable; /** * An empty immutable sorted map. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) @SuppressWarnings("serial") // uses writeReplace, not default serialization final class EmptyImmutableSortedMap<K, V> extends ImmutableSortedMap<K, V> { private final transient ImmutableSortedSet<K> keySet; EmptyImmutableSortedMap(Comparator<? super K> comparator) { this.keySet = ImmutableSortedSet.emptySet(comparator); } EmptyImmutableSortedMap( Comparator<? super K> comparator, ImmutableSortedMap<K, V> descendingMap) { super(descendingMap); this.keySet = ImmutableSortedSet.emptySet(comparator); } @Override public V get(@Nullable Object key) { return null; } @Override public ImmutableSortedSet<K> keySet() { return keySet; } @Override public int size() { return 0; } @Override public boolean isEmpty() { return true; } @Override public ImmutableCollection<V> values() { return ImmutableList.of(); } @Override public String toString() { return "{}"; } @Override boolean isPartialView() { return false; } @Override public ImmutableSet<Entry<K, V>> entrySet() { return ImmutableSet.of(); } @Override ImmutableSet<Entry<K, V>> createEntrySet() { throw new AssertionError("should never be called"); } @Override public ImmutableSetMultimap<K, V> asMultimap() { return ImmutableSetMultimap.of(); } @Override public ImmutableSortedMap<K, V> headMap(K toKey, boolean inclusive) { checkNotNull(toKey); return this; } @Override public ImmutableSortedMap<K, V> tailMap(K fromKey, boolean inclusive) { checkNotNull(fromKey); return this; } @Override ImmutableSortedMap<K, V> createDescendingMap() { return new EmptyImmutableSortedMap<K, V>(Ordering.from(comparator()).reverse(), this); } }
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.GwtCompatible; import com.google.common.base.Predicate; import java.util.Map.Entry; import java.util.Set; import javax.annotation.Nullable; /** * Implementation of {@link Multimaps#filterKeys(SetMultimap, Predicate)}. * * @author Louis Wasserman */ @GwtCompatible final class FilteredKeySetMultimap<K, V> extends FilteredKeyMultimap<K, V> implements FilteredSetMultimap<K, V> { FilteredKeySetMultimap(SetMultimap<K, V> unfiltered, Predicate<? super K> keyPredicate) { super(unfiltered, keyPredicate); } @Override public SetMultimap<K, V> unfiltered() { return (SetMultimap<K, V>) unfiltered; } @Override public Set<V> get(K key) { return (Set<V>) super.get(key); } @Override public Set<V> removeAll(Object key) { return (Set<V>) super.removeAll(key); } @Override public Set<V> replaceValues(K key, Iterable<? extends V> values) { return (Set<V>) super.replaceValues(key, values); } @Override public Set<Entry<K, V>> entries() { return (Set<Entry<K, V>>) super.entries(); } @Override Set<Entry<K, V>> createEntries() { return new EntrySet(); } class EntrySet extends Entries implements Set<Entry<K, V>> { @Override public int hashCode() { return Sets.hashCodeImpl(this); } @Override public boolean equals(@Nullable Object o) { return Sets.equalsImpl(this, o); } } }
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 java.io.Serializable; import java.util.Iterator; import javax.annotation.Nullable; /** An ordering that uses the reverse of a given order. */ @GwtCompatible(serializable = true) final class ReverseOrdering<T> extends Ordering<T> implements Serializable { final Ordering<? super T> forwardOrder; ReverseOrdering(Ordering<? super T> forwardOrder) { this.forwardOrder = checkNotNull(forwardOrder); } @Override public int compare(T a, T b) { return forwardOrder.compare(b, a); } @SuppressWarnings("unchecked") // how to explain? @Override public <S extends T> Ordering<S> reverse() { return (Ordering<S>) forwardOrder; } // Override the min/max methods to "hoist" delegation outside loops @Override public <E extends T> E min(E a, E b) { return forwardOrder.max(a, b); } @Override public <E extends T> E min(E a, E b, E c, E... rest) { return forwardOrder.max(a, b, c, rest); } @Override public <E extends T> E min(Iterator<E> iterator) { return forwardOrder.max(iterator); } @Override public <E extends T> E min(Iterable<E> iterable) { return forwardOrder.max(iterable); } @Override public <E extends T> E max(E a, E b) { return forwardOrder.min(a, b); } @Override public <E extends T> E max(E a, E b, E c, E... rest) { return forwardOrder.min(a, b, c, rest); } @Override public <E extends T> E max(Iterator<E> iterator) { return forwardOrder.min(iterator); } @Override public <E extends T> E max(Iterable<E> iterable) { return forwardOrder.min(iterable); } @Override public int hashCode() { return -forwardOrder.hashCode(); } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof ReverseOrdering) { ReverseOrdering<?> that = (ReverseOrdering<?>) object; return this.forwardOrder.equals(that.forwardOrder); } return false; } @Override public String toString() { return forwardOrder + ".reverse()"; } private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.primitives.Booleans; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; import java.util.Comparator; import javax.annotation.Nullable; /** * A utility for performing a chained comparison statement. For example: * <pre> {@code * * public int compareTo(Foo that) { * return ComparisonChain.start() * .compare(this.aString, that.aString) * .compare(this.anInt, that.anInt) * .compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast()) * .result(); * }}</pre> * * <p>The value of this expression will have the same sign as the <i>first * nonzero</i> comparison result in the chain, or will be zero if every * comparison result was zero. * * <p>Performance note: Even though the {@code ComparisonChain} caller always * invokes its {@code compare} methods unconditionally, the {@code * ComparisonChain} implementation stops calling its inputs' {@link * Comparable#compareTo compareTo} and {@link Comparator#compare compare} * methods as soon as one of them returns a nonzero result. This optimization is * typically important only in the presence of expensive {@code compareTo} and * {@code compare} implementations. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/CommonObjectUtilitiesExplained#compare/compareTo"> * {@code ComparisonChain}</a>. * * @author Mark Davis * @author Kevin Bourrillion * @since 2.0 */ @GwtCompatible public abstract class ComparisonChain { private ComparisonChain() {} /** * Begins a new chained comparison statement. See example in the class * documentation. */ public static ComparisonChain start() { return ACTIVE; } private static final ComparisonChain ACTIVE = new ComparisonChain() { @SuppressWarnings("unchecked") @Override public ComparisonChain compare( Comparable left, Comparable right) { return classify(left.compareTo(right)); } @Override public <T> ComparisonChain compare( @Nullable T left, @Nullable T right, Comparator<T> comparator) { return classify(comparator.compare(left, right)); } @Override public ComparisonChain compare(int left, int right) { return classify(Ints.compare(left, right)); } @Override public ComparisonChain compare(long left, long right) { return classify(Longs.compare(left, right)); } @Override public ComparisonChain compare(float left, float right) { return classify(Float.compare(left, right)); } @Override public ComparisonChain compare(double left, double right) { return classify(Double.compare(left, right)); } @Override public ComparisonChain compareTrueFirst(boolean left, boolean right) { return classify(Booleans.compare(right, left)); // reversed } @Override public ComparisonChain compareFalseFirst(boolean left, boolean right) { return classify(Booleans.compare(left, right)); } ComparisonChain classify(int result) { return (result < 0) ? LESS : (result > 0) ? GREATER : ACTIVE; } @Override public int result() { return 0; } }; private static final ComparisonChain LESS = new InactiveComparisonChain(-1); private static final ComparisonChain GREATER = new InactiveComparisonChain(1); private static final class InactiveComparisonChain extends ComparisonChain { final int result; InactiveComparisonChain(int result) { this.result = result; } @Override public ComparisonChain compare( @Nullable Comparable left, @Nullable Comparable right) { return this; } @Override public <T> ComparisonChain compare(@Nullable T left, @Nullable T right, @Nullable Comparator<T> comparator) { return this; } @Override public ComparisonChain compare(int left, int right) { return this; } @Override public ComparisonChain compare(long left, long right) { return this; } @Override public ComparisonChain compare(float left, float right) { return this; } @Override public ComparisonChain compare(double left, double right) { return this; } @Override public ComparisonChain compareTrueFirst(boolean left, boolean right) { return this; } @Override public ComparisonChain compareFalseFirst(boolean left, boolean right) { return this; } @Override public int result() { return result; } } /** * Compares two comparable objects as specified by {@link * Comparable#compareTo}, <i>if</i> the result of this comparison chain * has not already been determined. */ public abstract ComparisonChain compare( Comparable<?> left, Comparable<?> right); /** * Compares two objects using a comparator, <i>if</i> the result of this * comparison chain has not already been determined. */ public abstract <T> ComparisonChain compare( @Nullable T left, @Nullable T right, Comparator<T> comparator); /** * Compares two {@code int} values as specified by {@link Ints#compare}, * <i>if</i> the result of this comparison chain has not already been * determined. */ public abstract ComparisonChain compare(int left, int right); /** * Compares two {@code long} values as specified by {@link Longs#compare}, * <i>if</i> the result of this comparison chain has not already been * determined. */ public abstract ComparisonChain compare(long left, long right); /** * Compares two {@code float} values as specified by {@link * Float#compare}, <i>if</i> the result of this comparison chain has not * already been determined. */ public abstract ComparisonChain compare(float left, float right); /** * Compares two {@code double} values as specified by {@link * Double#compare}, <i>if</i> the result of this comparison chain has not * already been determined. */ public abstract ComparisonChain compare(double left, double right); /** * Compares two {@code boolean} values, considering {@code true} to be less * than {@code false}, <i>if</i> the result of this comparison chain has not * already been determined. * * @since 12.0 */ public abstract ComparisonChain compareTrueFirst(boolean left, boolean right); /** * Compares two {@code boolean} values, considering {@code false} to be less * than {@code true}, <i>if</i> the result of this comparison chain has not * already been determined. * * @since 12.0 (present as {@code compare} since 2.0) */ public abstract ComparisonChain compareFalseFirst(boolean left, boolean right); /** * Old name of {@link #compareFalseFirst}. * * @deprecated Use {@link #compareFalseFirst}; or, if the parameters passed * are being either negated or reversed, undo the negation or reversal and * use {@link #compareTrueFirst}. <b>This method is scheduled for deletion * in September 2013.</b> */ @Deprecated public final ComparisonChain compare(boolean left, boolean right) { return compareFalseFirst(left, right); } /** * Ends this comparison chain and returns its result: a value having the * same sign as the first nonzero comparison result in the chain, or zero if * every result was zero. */ public abstract int 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.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * The presence of this annotation on a type indicates that the type may be * used with the * <a href="http://code.google.com/webtoolkit/">Google Web Toolkit</a> (GWT). * When applied to a method, the return type of the method is GWT compatible. * It's useful to indicate that an instance created by factory methods has a GWT * serializable type. In the following example, * * <pre style="code"> * {@literal @}GwtCompatible * class Lists { * ... * {@literal @}GwtCompatible(serializable = true) * static &lt;E> List&lt;E> newArrayList(E... elements) { * ... * } * } * </pre> * <p>The return value of {@code Lists.newArrayList(E[])} has GWT * serializable type. It is also useful in specifying contracts of interface * methods. In the following example, * * <pre style="code"> * {@literal @}GwtCompatible * interface ListFactory { * ... * {@literal @}GwtCompatible(serializable = true) * &lt;E> List&lt;E> newArrayList(E... elements); * } * </pre> * <p>The {@code newArrayList(E[])} method of all implementations of {@code * ListFactory} is expected to return a value with a GWT serializable type. * * <p>Note that a {@code GwtCompatible} type may have some {@link * GwtIncompatible} methods. * * @author Charles Fry * @author Hayward Chan */ @Retention(RetentionPolicy.CLASS) @Target({ ElementType.TYPE, ElementType.METHOD }) @Documented @GwtCompatible public @interface GwtCompatible { /** * When {@code true}, the annotated type or the type of the method return * value is GWT serializable. * * @see <a href="http://code.google.com/webtoolkit/doc/latest/DevGuideServerCommunication.html#DevGuideSerializableTypes"> * Documentation about GWT serialization</a> */ boolean serializable() default false; /** * When {@code true}, the annotated type is emulated in GWT. The emulated * source (also known as super-source) is different from the implementation * used by the JVM. * * @see <a href="http://code.google.com/webtoolkit/doc/latest/DevGuideOrganizingProjects.html#DevGuideModules"> * Documentation about GWT emulated source</a> */ boolean emulated() default false; }
Java
/* * Copyright (C) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.annotations; /** * Annotates a program element that exists, or is more widely visible than * otherwise necessary, only for use in test code. * * @author Johannes Henkel */ @GwtCompatible public @interface VisibleForTesting { }
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. */ /** * Common annotation types. This package is a part of the open-source * <a href="http://guava-libraries.googlecode.com">Guava libraries</a>. */ package com.google.common.annotations;
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.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * The presence of this annotation on a method indicates that the method may * <em>not</em> be used with the * <a href="http://code.google.com/webtoolkit/">Google Web Toolkit</a> (GWT), * even though its type is annotated as {@link GwtCompatible} and accessible in * GWT. They can cause GWT compilation errors or simply unexpected exceptions * when used in GWT. * * <p>Note that this annotation should only be applied to methods, fields, or * inner classes of types which are annotated as {@link GwtCompatible}. * * @author Charles Fry */ @Retention(RetentionPolicy.CLASS) @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD }) @Documented @GwtCompatible public @interface GwtIncompatible { /** * Describes why the annotated element is incompatible with GWT. Since this is * generally due to a dependence on a type/method which GWT doesn't support, * it is sufficient to simply reference the unsupported type/method. E.g. * "Class.isInstance". */ String value(); }
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.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Signifies that a public API (public class, method or field) is subject to * incompatible changes, or even removal, in a future release. An API bearing * this annotation is exempt from any compatibility guarantees made by its * containing library. Note that the presence of this annotation implies nothing * about the quality or performance of the API in question, only the fact that * it is not "API-frozen." * * <p>It is generally safe for <i>applications</i> to depend on beta APIs, at * the cost of some extra work during upgrades. However it is generally * inadvisable for <i>libraries</i> (which get included on users' CLASSPATHs, * outside the library developers' control) to do so. * * * @author Kevin Bourrillion */ @Retention(RetentionPolicy.CLASS) @Target({ ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.TYPE}) @Documented @GwtCompatible public @interface Beta {}
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.hash; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.base.Preconditions; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; /** * Skeleton implementation of {@link HashFunction}. Provides default implementations which * invokes the appropriate method on {@link #newHasher()}, then return the result of * {@link Hasher#hash}. * * <p>Invocations of {@link #newHasher(int)} also delegate to {@linkplain #newHasher()}, ignoring * the expected input size parameter. * * @author Kevin Bourrillion */ abstract class AbstractStreamingHashFunction implements HashFunction { @Override public <T> HashCode hashObject(T instance, Funnel<? super T> funnel) { return newHasher().putObject(instance, funnel).hash(); } /** * @deprecated Use {@link AbstractStreamingHashFunction#hashUnencodedChars} instead. */ @Deprecated @Override public HashCode hashString(CharSequence input) { return hashUnencodedChars(input); } @Override public HashCode hashUnencodedChars(CharSequence input) { return newHasher().putUnencodedChars(input).hash(); } @Override public HashCode hashString(CharSequence input, Charset charset) { return newHasher().putString(input, charset).hash(); } @Override public HashCode hashInt(int input) { return newHasher().putInt(input).hash(); } @Override public HashCode hashLong(long input) { return newHasher().putLong(input).hash(); } @Override public HashCode hashBytes(byte[] input) { return newHasher().putBytes(input).hash(); } @Override public HashCode hashBytes(byte[] input, int off, int len) { return newHasher().putBytes(input, off, len).hash(); } @Override public Hasher newHasher(int expectedInputSize) { Preconditions.checkArgument(expectedInputSize >= 0); return newHasher(); } /** * A convenience base class for implementors of {@code Hasher}; handles accumulating data * until an entire "chunk" (of implementation-dependent length) is ready to be hashed. * * @author Kevin Bourrillion * @author Dimitris Andreou */ // TODO(kevinb): this class still needs some design-and-document-for-inheritance love protected static abstract class AbstractStreamingHasher extends AbstractHasher { /** Buffer via which we pass data to the hash algorithm (the implementor) */ private final ByteBuffer buffer; /** Number of bytes to be filled before process() invocation(s). */ private final int bufferSize; /** Number of bytes processed per process() invocation. */ private final int chunkSize; /** * Constructor for use by subclasses. This hasher instance will process chunks of the specified * size. * * @param chunkSize the number of bytes available per {@link #process(ByteBuffer)} invocation; * must be at least 4 */ protected AbstractStreamingHasher(int chunkSize) { this(chunkSize, chunkSize); } /** * Constructor for use by subclasses. This hasher instance will process chunks of the specified * size, using an internal buffer of {@code bufferSize} size, which must be a multiple of * {@code chunkSize}. * * @param chunkSize the number of bytes available per {@link #process(ByteBuffer)} invocation; * must be at least 4 * @param bufferSize the size of the internal buffer. Must be a multiple of chunkSize */ protected AbstractStreamingHasher(int chunkSize, int bufferSize) { // TODO(kevinb): check more preconditions (as bufferSize >= chunkSize) if this is ever public checkArgument(bufferSize % chunkSize == 0); // TODO(user): benchmark performance difference with longer buffer this.buffer = ByteBuffer .allocate(bufferSize + 7) // always space for a single primitive .order(ByteOrder.LITTLE_ENDIAN); this.bufferSize = bufferSize; this.chunkSize = chunkSize; } /** * Processes the available bytes of the buffer (at most {@code chunk} bytes). */ protected abstract void process(ByteBuffer bb); /** * This is invoked for the last bytes of the input, which are not enough to * fill a whole chunk. The passed {@code ByteBuffer} is guaranteed to be * non-empty. * * <p>This implementation simply pads with zeros and delegates to * {@link #process(ByteBuffer)}. */ protected void processRemaining(ByteBuffer bb) { bb.position(bb.limit()); // move at the end bb.limit(chunkSize + 7); // get ready to pad with longs while (bb.position() < chunkSize) { bb.putLong(0); } bb.limit(chunkSize); bb.flip(); process(bb); } @Override public final Hasher putBytes(byte[] bytes) { return putBytes(bytes, 0, bytes.length); } @Override public final Hasher putBytes(byte[] bytes, int off, int len) { return putBytes(ByteBuffer.wrap(bytes, off, len).order(ByteOrder.LITTLE_ENDIAN)); } private Hasher putBytes(ByteBuffer readBuffer) { // If we have room for all of it, this is easy if (readBuffer.remaining() <= buffer.remaining()) { buffer.put(readBuffer); munchIfFull(); return this; } // First add just enough to fill buffer size, and munch that int bytesToCopy = bufferSize - buffer.position(); for (int i = 0; i < bytesToCopy; i++) { buffer.put(readBuffer.get()); } munch(); // buffer becomes empty here, since chunkSize divides bufferSize // Now process directly from the rest of the input buffer while (readBuffer.remaining() >= chunkSize) { process(readBuffer); } // Finally stick the remainder back in our usual buffer buffer.put(readBuffer); return this; } /** * @deprecated Use {@link AbstractStreamingHasher#putUnencodedChars} instead. */ @Deprecated @Override public final Hasher putString(CharSequence charSequence) { return putUnencodedChars(charSequence); } @Override public final Hasher putUnencodedChars(CharSequence charSequence) { for (int i = 0; i < charSequence.length(); i++) { putChar(charSequence.charAt(i)); } return this; } @Override public final Hasher putByte(byte b) { buffer.put(b); munchIfFull(); return this; } @Override public final Hasher putShort(short s) { buffer.putShort(s); munchIfFull(); return this; } @Override public final Hasher putChar(char c) { buffer.putChar(c); munchIfFull(); return this; } @Override public final Hasher putInt(int i) { buffer.putInt(i); munchIfFull(); return this; } @Override public final Hasher putLong(long l) { buffer.putLong(l); munchIfFull(); return this; } @Override public final <T> Hasher putObject(T instance, Funnel<? super T> funnel) { funnel.funnel(instance, this); return this; } @Override public final HashCode hash() { munch(); buffer.flip(); if (buffer.remaining() > 0) { processRemaining(buffer); } return makeHash(); } abstract HashCode makeHash(); // Process pent-up data in chunks private void munchIfFull() { if (buffer.remaining() < 8) { // buffer is full; not enough room for a primitive. We have at least one full chunk. munch(); } } private void munch() { buffer.flip(); while (buffer.remaining() >= chunkSize) { // we could limit the buffer to ensure process() does not read more than // chunkSize number of bytes, but we trust the implementations process(buffer); } buffer.compact(); // preserve any remaining data that do not make a full chunk } } }
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.hash; import com.google.common.annotations.Beta; import java.nio.charset.Charset; /** * An object which can receive a stream of primitive values. * * @author Kevin Bourrillion * @since 12.0 (in 11.0 as {@code Sink}) */ @Beta public interface PrimitiveSink { /** * Puts a byte into this sink. * * @param b a byte * @return this instance */ PrimitiveSink putByte(byte b); /** * Puts an array of bytes into this sink. * * @param bytes a byte array * @return this instance */ PrimitiveSink putBytes(byte[] bytes); /** * Puts a chunk of an array of bytes into this sink. {@code bytes[off]} is the first byte written, * {@code bytes[off + len - 1]} is the last. * * @param bytes a byte array * @param off the start offset in the array * @param len the number of bytes to write * @return this instance * @throws IndexOutOfBoundsException if {@code off < 0} or {@code off + len > bytes.length} or * {@code len < 0} */ PrimitiveSink putBytes(byte[] bytes, int off, int len); /** * Puts a short into this sink. */ PrimitiveSink putShort(short s); /** * Puts an int into this sink. */ PrimitiveSink putInt(int i); /** * Puts a long into this sink. */ PrimitiveSink putLong(long l); /** * Puts a float into this sink. */ PrimitiveSink putFloat(float f); /** * Puts a double into this sink. */ PrimitiveSink putDouble(double d); /** * Puts a boolean into this sink. */ PrimitiveSink putBoolean(boolean b); /** * Puts a character into this sink. */ PrimitiveSink putChar(char c); /** * Puts a string into this sink. * * @deprecated Use {PrimitiveSink#putUnencodedChars} instead. This method is scheduled for * removal in Guava 16.0. */ @Deprecated PrimitiveSink putString(CharSequence charSequence); /** * Puts each 16-bit code unit from the {@link CharSequence} into this sink. * * @since 15.0 (since 11.0 as putString(CharSequence)) */ PrimitiveSink putUnencodedChars(CharSequence charSequence); /** * Puts a string into this sink using the given charset. */ PrimitiveSink putString(CharSequence charSequence, Charset charset); }
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.hash; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.primitives.Chars; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; import com.google.common.primitives.Shorts; import java.nio.ByteBuffer; import java.nio.ByteOrder; /** * Abstract {@link Hasher} that handles converting primitives to bytes using a scratch {@code * ByteBuffer} and streams all bytes to a sink to compute the hash. * * @author Colin Decker */ abstract class AbstractByteHasher extends AbstractHasher { private final ByteBuffer scratch = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN); /** * Updates this hasher with the given byte. */ protected abstract void update(byte b); /** * Updates this hasher with the given bytes. */ protected void update(byte[] b) { update(b, 0, b.length); } /** * Updates this hasher with {@code len} bytes starting at {@code off} in the given buffer. */ protected void update(byte[] b, int off, int len) { for (int i = off; i < off + len; i++) { update(b[i]); } } @Override public Hasher putByte(byte b) { update(b); return this; } @Override public Hasher putBytes(byte[] bytes) { checkNotNull(bytes); update(bytes); return this; } @Override public Hasher putBytes(byte[] bytes, int off, int len) { checkPositionIndexes(off, off + len, bytes.length); update(bytes, off, len); return this; } /** * Updates the sink with the given number of bytes from the buffer. */ private Hasher update(int bytes) { try { update(scratch.array(), 0, bytes); } finally { scratch.clear(); } return this; } @Override public Hasher putShort(short s) { scratch.putShort(s); return update(Shorts.BYTES); } @Override public Hasher putInt(int i) { scratch.putInt(i); return update(Ints.BYTES); } @Override public Hasher putLong(long l) { scratch.putLong(l); return update(Longs.BYTES); } @Override public Hasher putChar(char c) { scratch.putChar(c); return update(Chars.BYTES); } @Override public <T> Hasher putObject(T instance, Funnel<? super T> funnel) { funnel.funnel(instance, this); return this; } }
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.hash; 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.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; /** * {@link HashFunction} adapter for {@link MessageDigest} instances. * * @author Kevin Bourrillion * @author Dimitris Andreou */ final class MessageDigestHashFunction extends AbstractStreamingHashFunction implements Serializable { private final MessageDigest prototype; private final int bytes; private final boolean supportsClone; private final String toString; MessageDigestHashFunction(String algorithmName, String toString) { this.prototype = getMessageDigest(algorithmName); this.bytes = prototype.getDigestLength(); this.toString = checkNotNull(toString); this.supportsClone = supportsClone(); } MessageDigestHashFunction(String algorithmName, int bytes, String toString) { this.toString = checkNotNull(toString); this.prototype = getMessageDigest(algorithmName); int maxLength = prototype.getDigestLength(); checkArgument(bytes >= 4 && bytes <= maxLength, "bytes (%s) must be >= 4 and < %s", bytes, maxLength); this.bytes = bytes; this.supportsClone = supportsClone(); } private boolean supportsClone() { try { prototype.clone(); return true; } catch (CloneNotSupportedException e) { return false; } } @Override public int bits() { return bytes * Byte.SIZE; } @Override public String toString() { return toString; } private static MessageDigest getMessageDigest(String algorithmName) { try { return MessageDigest.getInstance(algorithmName); } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } } @Override public Hasher newHasher() { if (supportsClone) { try { return new MessageDigestHasher((MessageDigest) prototype.clone(), bytes); } catch (CloneNotSupportedException e) { // falls through } } return new MessageDigestHasher(getMessageDigest(prototype.getAlgorithm()), bytes); } private static final class SerializedForm implements Serializable { private final String algorithmName; private final int bytes; private final String toString; private SerializedForm(String algorithmName, int bytes, String toString) { this.algorithmName = algorithmName; this.bytes = bytes; this.toString = toString; } private Object readResolve() { return new MessageDigestHashFunction(algorithmName, bytes, toString); } private static final long serialVersionUID = 0; } Object writeReplace() { return new SerializedForm(prototype.getAlgorithm(), bytes, toString); } /** * Hasher that updates a message digest. */ private static final class MessageDigestHasher extends AbstractByteHasher { private final MessageDigest digest; private final int bytes; private boolean done; private MessageDigestHasher(MessageDigest digest, int bytes) { this.digest = digest; this.bytes = bytes; } @Override protected void update(byte b) { checkNotDone(); digest.update(b); } @Override protected void update(byte[] b) { checkNotDone(); digest.update(b); } @Override protected void update(byte[] b, int off, int len) { checkNotDone(); digest.update(b, off, len); } private void checkNotDone() { checkState(!done, "Cannot use Hasher after calling #hash() on it"); } @Override public HashCode hash() { done = true; return (bytes == digest.getDigestLength()) ? HashCodes.fromBytesNoCopy(digest.digest()) : HashCodes.fromBytesNoCopy(Arrays.copyOf(digest.digest(), bytes)); } } }
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. */ /* * MurmurHash3 was written by Austin Appleby, and is placed in the public * domain. The author hereby disclaims copyright to this source code. */ /* * Source: * http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp * (Modified to adapt to Guava coding conventions and to use the HashFunction interface) */ package com.google.common.hash; import static com.google.common.primitives.UnsignedBytes.toInt; import java.io.Serializable; import java.nio.ByteBuffer; import java.nio.ByteOrder; import javax.annotation.Nullable; /** * See http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp * MurmurHash3_x64_128 * * @author Austin Appleby * @author Dimitris Andreou */ final class Murmur3_128HashFunction extends AbstractStreamingHashFunction implements Serializable { // TODO(user): when the shortcuts are implemented, update BloomFilterStrategies private final int seed; Murmur3_128HashFunction(int seed) { this.seed = seed; } @Override public int bits() { return 128; } @Override public Hasher newHasher() { return new Murmur3_128Hasher(seed); } @Override public String toString() { return "Hashing.murmur3_128(" + seed + ")"; } @Override public boolean equals(@Nullable Object object) { if (object instanceof Murmur3_128HashFunction) { Murmur3_128HashFunction other = (Murmur3_128HashFunction) object; return seed == other.seed; } return false; } @Override public int hashCode() { return getClass().hashCode() ^ seed; } private static final class Murmur3_128Hasher extends AbstractStreamingHasher { private static final int CHUNK_SIZE = 16; private static final long C1 = 0x87c37b91114253d5L; private static final long C2 = 0x4cf5ad432745937fL; private long h1; private long h2; private int length; Murmur3_128Hasher(int seed) { super(CHUNK_SIZE); this.h1 = seed; this.h2 = seed; this.length = 0; } @Override protected void process(ByteBuffer bb) { long k1 = bb.getLong(); long k2 = bb.getLong(); bmix64(k1, k2); length += CHUNK_SIZE; } private void bmix64(long k1, long k2) { h1 ^= mixK1(k1); h1 = Long.rotateLeft(h1, 27); h1 += h2; h1 = h1 * 5 + 0x52dce729; h2 ^= mixK2(k2); h2 = Long.rotateLeft(h2, 31); h2 += h1; h2 = h2 * 5 + 0x38495ab5; } @Override protected void processRemaining(ByteBuffer bb) { long k1 = 0; long k2 = 0; length += bb.remaining(); switch (bb.remaining()) { case 15: k2 ^= (long) toInt(bb.get(14)) << 48; // fall through case 14: k2 ^= (long) toInt(bb.get(13)) << 40; // fall through case 13: k2 ^= (long) toInt(bb.get(12)) << 32; // fall through case 12: k2 ^= (long) toInt(bb.get(11)) << 24; // fall through case 11: k2 ^= (long) toInt(bb.get(10)) << 16; // fall through case 10: k2 ^= (long) toInt(bb.get(9)) << 8; // fall through case 9: k2 ^= (long) toInt(bb.get(8)); // fall through case 8: k1 ^= bb.getLong(); break; case 7: k1 ^= (long) toInt(bb.get(6)) << 48; // fall through case 6: k1 ^= (long) toInt(bb.get(5)) << 40; // fall through case 5: k1 ^= (long) toInt(bb.get(4)) << 32; // fall through case 4: k1 ^= (long) toInt(bb.get(3)) << 24; // fall through case 3: k1 ^= (long) toInt(bb.get(2)) << 16; // fall through case 2: k1 ^= (long) toInt(bb.get(1)) << 8; // fall through case 1: k1 ^= (long) toInt(bb.get(0)); break; default: throw new AssertionError("Should never get here."); } h1 ^= mixK1(k1); h2 ^= mixK2(k2); } @Override public HashCode makeHash() { h1 ^= length; h2 ^= length; h1 += h2; h2 += h1; h1 = fmix64(h1); h2 = fmix64(h2); h1 += h2; h2 += h1; return HashCodes.fromBytesNoCopy(ByteBuffer .wrap(new byte[CHUNK_SIZE]) .order(ByteOrder.LITTLE_ENDIAN) .putLong(h1) .putLong(h2) .array()); } private static long fmix64(long k) { k ^= k >>> 33; k *= 0xff51afd7ed558ccdL; k ^= k >>> 33; k *= 0xc4ceb9fe1a85ec53L; k ^= k >>> 33; return k; } private static long mixK1(long k1) { k1 *= C1; k1 = Long.rotateLeft(k1, 31); k1 *= C2; return k1; } private static long mixK2(long k2) { k2 *= C2; k2 = Long.rotateLeft(k2, 33); k2 *= C1; return k2; } } private static final long serialVersionUID = 0L; }
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. */ // TODO(user): when things stabilize, flesh this out /** * Hash functions and related structures. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/HashingExplained"> * hashing</a>. */ @ParametersAreNonnullByDefault package com.google.common.hash; 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.hash; import com.google.common.base.Preconditions; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.Charset; /** * Skeleton implementation of {@link HashFunction}, appropriate for non-streaming algorithms. * All the hash computation done using {@linkplain #newHasher()} are delegated to the {@linkplain * #hashBytes(byte[], int, int)} method. * * @author Dimitris Andreou */ abstract class AbstractNonStreamingHashFunction implements HashFunction { @Override public Hasher newHasher() { return new BufferingHasher(32); } @Override public Hasher newHasher(int expectedInputSize) { Preconditions.checkArgument(expectedInputSize >= 0); return new BufferingHasher(expectedInputSize); } @Override public <T> HashCode hashObject(T instance, Funnel<? super T> funnel) { return newHasher().putObject(instance, funnel).hash(); } /** * @deprecated Use {@link AbstractNonStreamingHashFunction#hashUnencodedChars} instead. */ @Deprecated @Override public HashCode hashString(CharSequence input) { return hashUnencodedChars(input); } @Override public HashCode hashUnencodedChars(CharSequence input) { int len = input.length(); Hasher hasher = newHasher(len * 2); for (int i = 0; i < len; i++) { hasher.putChar(input.charAt(i)); } return hasher.hash(); } @Override public HashCode hashString(CharSequence input, Charset charset) { return hashBytes(input.toString().getBytes(charset)); } @Override public HashCode hashInt(int input) { return newHasher(4).putInt(input).hash(); } @Override public HashCode hashLong(long input) { return newHasher(8).putLong(input).hash(); } @Override public HashCode hashBytes(byte[] input) { return hashBytes(input, 0, input.length); } /** * In-memory stream-based implementation of Hasher. */ private final class BufferingHasher extends AbstractHasher { final ExposedByteArrayOutputStream stream; static final int BOTTOM_BYTE = 0xFF; BufferingHasher(int expectedInputSize) { this.stream = new ExposedByteArrayOutputStream(expectedInputSize); } @Override public Hasher putByte(byte b) { stream.write(b); return this; } @Override public Hasher putBytes(byte[] bytes) { try { stream.write(bytes); } catch (IOException e) { throw new RuntimeException(e); } return this; } @Override public Hasher putBytes(byte[] bytes, int off, int len) { stream.write(bytes, off, len); return this; } @Override public Hasher putShort(short s) { stream.write(s & BOTTOM_BYTE); stream.write((s >>> 8) & BOTTOM_BYTE); return this; } @Override public Hasher putInt(int i) { stream.write(i & BOTTOM_BYTE); stream.write((i >>> 8) & BOTTOM_BYTE); stream.write((i >>> 16) & BOTTOM_BYTE); stream.write((i >>> 24) & BOTTOM_BYTE); return this; } @Override public Hasher putLong(long l) { for (int i = 0; i < 64; i += 8) { stream.write((byte) ((l >>> i) & BOTTOM_BYTE)); } return this; } @Override public Hasher putChar(char c) { stream.write(c & BOTTOM_BYTE); stream.write((c >>> 8) & BOTTOM_BYTE); return this; } @Override public <T> Hasher putObject(T instance, Funnel<? super T> funnel) { funnel.funnel(instance, this); return this; } @Override public HashCode hash() { return hashBytes(stream.byteArray(), 0, stream.length()); } } // Just to access the byte[] without introducing an unnecessary copy private static final class ExposedByteArrayOutputStream extends ByteArrayOutputStream { ExposedByteArrayOutputStream(int expectedInputSize) { super(expectedInputSize); } byte[] byteArray() { return buf; } int length() { return count; } } }
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.hash; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.math.LongMath; import com.google.common.primitives.Ints; import java.math.RoundingMode; import java.util.Arrays; /** * Collections of strategies of generating the k * log(M) bits required for an element to * be mapped to a BloomFilter of M bits and k hash functions. These * strategies are part of the serialized form of the Bloom filters that use them, thus they must be * preserved as is (no updates allowed, only introduction of new versions). * * Important: the order of the constants cannot change, and they cannot be deleted - we depend * on their ordinal for BloomFilter serialization. * * @author Dimitris Andreou */ enum BloomFilterStrategies implements BloomFilter.Strategy { /** * See "Less Hashing, Same Performance: Building a Better Bloom Filter" by Adam Kirsch and * Michael Mitzenmacher. The paper argues that this trick doesn't significantly deteriorate the * performance of a Bloom filter (yet only needs two 32bit hash functions). */ MURMUR128_MITZ_32() { @Override public <T> boolean put(T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits) { long hash64 = Hashing.murmur3_128().hashObject(object, funnel).asLong(); int hash1 = (int) hash64; int hash2 = (int) (hash64 >>> 32); boolean bitsChanged = false; for (int i = 1; i <= numHashFunctions; i++) { int nextHash = hash1 + i * hash2; if (nextHash < 0) { nextHash = ~nextHash; } bitsChanged |= bits.set(nextHash % bits.bitSize()); } return bitsChanged; } @Override public <T> boolean mightContain(T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits) { long hash64 = Hashing.murmur3_128().hashObject(object, funnel).asLong(); int hash1 = (int) hash64; int hash2 = (int) (hash64 >>> 32); for (int i = 1; i <= numHashFunctions; i++) { int nextHash = hash1 + i * hash2; if (nextHash < 0) { nextHash = ~nextHash; } if (!bits.get(nextHash % bits.bitSize())) { return false; } } return true; } }; // Note: We use this instead of java.util.BitSet because we need access to the long[] data field static class BitArray { final long[] data; int bitCount; BitArray(long bits) { this(new long[Ints.checkedCast(LongMath.divide(bits, 64, RoundingMode.CEILING))]); } // Used by serialization BitArray(long[] data) { checkArgument(data.length > 0, "data length is zero!"); this.data = data; int bitCount = 0; for (long value : data) { bitCount += Long.bitCount(value); } this.bitCount = bitCount; } /** Returns true if the bit changed value. */ boolean set(int index) { if (!get(index)) { data[index >> 6] |= (1L << index); bitCount++; return true; } return false; } boolean get(int index) { return (data[index >> 6] & (1L << index)) != 0; } /** Number of bits */ int bitSize() { return data.length * Long.SIZE; } /** Number of set bits (1s) */ int bitCount() { return bitCount; } BitArray copy() { return new BitArray(data.clone()); } /** Combines the two BitArrays using bitwise OR. */ void putAll(BitArray array) { checkArgument(data.length == array.data.length, "BitArrays must be of equal length (%s != %s)", data.length, array.data.length); bitCount = 0; for (int i = 0; i < data.length; i++) { data[i] |= array.data[i]; bitCount += Long.bitCount(data[i]); } } @Override public boolean equals(Object o) { if (o instanceof BitArray) { BitArray bitArray = (BitArray) o; return Arrays.equals(data, bitArray.data); } return false; } @Override public int hashCode() { return Arrays.hashCode(data); } } }
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.hash; 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.VisibleForTesting; import com.google.common.base.Objects; import com.google.common.base.Predicate; import com.google.common.hash.BloomFilterStrategies.BitArray; import java.io.Serializable; import javax.annotation.Nullable; /** * A Bloom filter for instances of {@code T}. A Bloom filter offers an approximate containment test * with one-sided error: if it claims that an element is contained in it, this might be in error, * but if it claims that an element is <i>not</i> contained in it, then this is definitely true. * * <p>If you are unfamiliar with Bloom filters, this nice * <a href="http://llimllib.github.com/bloomfilter-tutorial/">tutorial</a> may help you understand * how they work. * * <p>The false positive probability ({@code FPP}) of a bloom filter is defined as the probability * that {@linkplain #mightContain(Object)} will erroneously return {@code true} for an object that * has not actually been put in the {@code BloomFilter}. * * * @param <T> the type of instances that the {@code BloomFilter} accepts * @author Dimitris Andreou * @author Kevin Bourrillion * @since 11.0 */ @Beta public final class BloomFilter<T> implements Predicate<T>, Serializable { /** * A strategy to translate T instances, to {@code numHashFunctions} bit indexes. * * <p>Implementations should be collections of pure functions (i.e. stateless). */ interface Strategy extends java.io.Serializable { /** * Sets {@code numHashFunctions} bits of the given bit array, by hashing a user element. * * <p>Returns whether any bits changed as a result of this operation. */ <T> boolean put(T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits); /** * Queries {@code numHashFunctions} bits of the given bit array, by hashing a user element; * returns {@code true} if and only if all selected bits are set. */ <T> boolean mightContain( T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits); /** * Identifier used to encode this strategy, when marshalled as part of a BloomFilter. * Only values in the [-128, 127] range are valid for the compact serial form. * Non-negative values are reserved for enums defined in BloomFilterStrategies; * negative values are reserved for any custom, stateful strategy we may define * (e.g. any kind of strategy that would depend on user input). */ int ordinal(); } /** The bit set of the BloomFilter (not necessarily power of 2!)*/ private final BitArray bits; /** Number of hashes per element */ private final int numHashFunctions; /** The funnel to translate Ts to bytes */ private final Funnel<T> funnel; /** * The strategy we employ to map an element T to {@code numHashFunctions} bit indexes. */ private final Strategy strategy; /** * Creates a BloomFilter. */ private BloomFilter(BitArray bits, int numHashFunctions, Funnel<T> funnel, Strategy strategy) { checkArgument(numHashFunctions > 0, "numHashFunctions (%s) must be > 0", numHashFunctions); checkArgument(numHashFunctions <= 255, "numHashFunctions (%s) must be <= 255", numHashFunctions); this.bits = checkNotNull(bits); this.numHashFunctions = numHashFunctions; this.funnel = checkNotNull(funnel); this.strategy = checkNotNull(strategy); } /** * Creates a new {@code BloomFilter} that's a copy of this instance. The new instance is equal to * this instance but shares no mutable state. * * @since 12.0 */ public BloomFilter<T> copy() { return new BloomFilter<T>(bits.copy(), numHashFunctions, funnel, strategy); } /** * Returns {@code true} if the element <i>might</i> have been put in this Bloom filter, * {@code false} if this is <i>definitely</i> not the case. */ public boolean mightContain(T object) { return strategy.mightContain(object, funnel, numHashFunctions, bits); } /** * Equivalent to {@link #mightContain}; provided only to satisfy the {@link Predicate} interface. * When using a reference of type {@code BloomFilter}, always invoke {@link #mightContain} * directly instead. */ @Override public boolean apply(T input) { return mightContain(input); } /** * Puts an element into this {@code BloomFilter}. Ensures that subsequent invocations of * {@link #mightContain(Object)} with the same element will always return {@code true}. * * @return true if the bloom filter's bits changed as a result of this operation. If the bits * changed, this is <i>definitely</i> the first time {@code object} has been added to the * filter. If the bits haven't changed, this <i>might</i> be the first time {@code object} * has been added to the filter. Note that {@code put(t)} always returns the * <i>opposite</i> result to what {@code mightContain(t)} would have returned at the time * it is called." * @since 12.0 (present in 11.0 with {@code void} return type}) */ public boolean put(T object) { return strategy.put(object, funnel, numHashFunctions, bits); } /** * Returns the probability that {@linkplain #mightContain(Object)} will erroneously return * {@code true} for an object that has not actually been put in the {@code BloomFilter}. * * <p>Ideally, this number should be close to the {@code fpp} parameter * passed in {@linkplain #create(Funnel, int, double)}, or smaller. If it is * significantly higher, it is usually the case that too many elements (more than * expected) have been put in the {@code BloomFilter}, degenerating it. * * @since 14.0 (since 11.0 as expectedFalsePositiveProbability()) */ public double expectedFpp() { // You down with FPP? (Yeah you know me!) Who's down with FPP? (Every last homie!) return Math.pow((double) bits.bitCount() / bitSize(), numHashFunctions); } /** * Returns the number of bits in the underlying bit array. */ @VisibleForTesting long bitSize() { return bits.bitSize(); } /** * Determines whether a given bloom filter is compatible with this bloom filter. For two * bloom filters to be compatible, they must: * * <ul> * <li>not be the same instance * <li>have the same number of hash functions * <li>have the same bit size * <li>have the same strategy * <li>have equal funnels * <ul> * * @param that The bloom filter to check for compatibility. * @since 15.0 */ public boolean isCompatible(BloomFilter<T> that) { checkNotNull(that); return (this != that) && (this.numHashFunctions == that.numHashFunctions) && (this.bitSize() == that.bitSize()) && (this.strategy.equals(that.strategy)) && (this.funnel.equals(that.funnel)); } /** * Combines this bloom filter with another bloom filter by performing a bitwise OR of the * underlying data. The mutations happen to <b>this</b> instance. Callers must ensure the * bloom filters are appropriately sized to avoid saturating them. * * @param that The bloom filter to combine this bloom filter with. It is not mutated. * @throws IllegalArgumentException if {@code isCompatible(that) == false} * * @since 15.0 */ public void putAll(BloomFilter<T> that) { checkNotNull(that); checkArgument(this != that, "Cannot combine a BloomFilter with itself."); checkArgument(this.numHashFunctions == that.numHashFunctions, "BloomFilters must have the same number of hash functions (%s != %s)", this.numHashFunctions, that.numHashFunctions); checkArgument(this.bitSize() == that.bitSize(), "BloomFilters must have the same size underlying bit arrays (%s != %s)", this.bitSize(), that.bitSize()); checkArgument(this.strategy.equals(that.strategy), "BloomFilters must have equal strategies (%s != %s)", this.strategy, that.strategy); checkArgument(this.funnel.equals(that.funnel), "BloomFilters must have equal funnels (%s != %s)", this.funnel, that.funnel); this.bits.putAll(that.bits); } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof BloomFilter) { BloomFilter<?> that = (BloomFilter<?>) object; return this.numHashFunctions == that.numHashFunctions && this.funnel.equals(that.funnel) && this.bits.equals(that.bits) && this.strategy.equals(that.strategy); } return false; } @Override public int hashCode() { return Objects.hashCode(numHashFunctions, funnel, strategy, bits); } /** * Creates a {@link BloomFilter BloomFilter<T>} with the expected number of * insertions and expected false positive probability. * * <p>Note that overflowing a {@code BloomFilter} with significantly more elements * than specified, will result in its saturation, and a sharp deterioration of its * false positive probability. * * <p>The constructed {@code BloomFilter<T>} will be serializable if the provided * {@code Funnel<T>} is. * * <p>It is recommended that the funnel be implemented as a Java enum. This has the * benefit of ensuring proper serialization and deserialization, which is important * since {@link #equals} also relies on object identity of funnels. * * @param funnel the funnel of T's that the constructed {@code BloomFilter<T>} will use * @param expectedInsertions the number of expected insertions to the constructed * {@code BloomFilter<T>}; must be positive * @param fpp the desired false positive probability (must be positive and less than 1.0) * @return a {@code BloomFilter} */ public static <T> BloomFilter<T> create( Funnel<T> funnel, int expectedInsertions /* n */, double fpp) { checkNotNull(funnel); checkArgument(expectedInsertions >= 0, "Expected insertions (%s) must be >= 0", expectedInsertions); checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp); checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp); if (expectedInsertions == 0) { expectedInsertions = 1; } /* * TODO(user): Put a warning in the javadoc about tiny fpp values, * since the resulting size is proportional to -log(p), but there is not * much of a point after all, e.g. optimalM(1000, 0.0000000000000001) = 76680 * which is less than 10kb. Who cares! */ long numBits = optimalNumOfBits(expectedInsertions, fpp); int numHashFunctions = optimalNumOfHashFunctions(expectedInsertions, numBits); try { return new BloomFilter<T>(new BitArray(numBits), numHashFunctions, funnel, BloomFilterStrategies.MURMUR128_MITZ_32); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Could not create BloomFilter of " + numBits + " bits", e); } } /** * Creates a {@link BloomFilter BloomFilter<T>} with the expected number of * insertions and a default expected false positive probability of 3%. * * <p>Note that overflowing a {@code BloomFilter} with significantly more elements * than specified, will result in its saturation, and a sharp deterioration of its * false positive probability. * * <p>The constructed {@code BloomFilter<T>} will be serializable if the provided * {@code Funnel<T>} is. * * @param funnel the funnel of T's that the constructed {@code BloomFilter<T>} will use * @param expectedInsertions the number of expected insertions to the constructed * {@code BloomFilter<T>}; must be positive * @return a {@code BloomFilter} */ public static <T> BloomFilter<T> create(Funnel<T> funnel, int expectedInsertions /* n */) { return create(funnel, expectedInsertions, 0.03); // FYI, for 3%, we always get 5 hash functions } /* * Cheat sheet: * * m: total bits * n: expected insertions * b: m/n, bits per insertion * p: expected false positive probability * * 1) Optimal k = b * ln2 * 2) p = (1 - e ^ (-kn/m))^k * 3) For optimal k: p = 2 ^ (-k) ~= 0.6185^b * 4) For optimal k: m = -nlnp / ((ln2) ^ 2) */ /** * Computes the optimal k (number of hashes per element inserted in Bloom filter), given the * expected insertions and total number of bits in the Bloom filter. * * See http://en.wikipedia.org/wiki/File:Bloom_filter_fp_probability.svg for the formula. * * @param n expected insertions (must be positive) * @param m total number of bits in Bloom filter (must be positive) */ @VisibleForTesting static int optimalNumOfHashFunctions(long n, long m) { return Math.max(1, (int) Math.round(m / n * Math.log(2))); } /** * Computes m (total bits of Bloom filter) which is expected to achieve, for the specified * expected insertions, the required false positive probability. * * See http://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives for the formula. * * @param n expected insertions (must be positive) * @param p false positive rate (must be 0 < p < 1) */ @VisibleForTesting static long optimalNumOfBits(long n, double p) { if (p == 0) { p = Double.MIN_VALUE; } return (long) (-n * Math.log(p) / (Math.log(2) * Math.log(2))); } private Object writeReplace() { return new SerialForm<T>(this); } private static class SerialForm<T> implements Serializable { final long[] data; final int numHashFunctions; final Funnel<T> funnel; final Strategy strategy; SerialForm(BloomFilter<T> bf) { this.data = bf.bits.data; this.numHashFunctions = bf.numHashFunctions; this.funnel = bf.funnel; this.strategy = bf.strategy; } Object readResolve() { return new BloomFilter<T>(new BitArray(data), numHashFunctions, funnel, strategy); } private static final long serialVersionUID = 1; } }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.hash; import com.google.common.annotations.Beta; import com.google.common.primitives.Ints; import java.nio.charset.Charset; /** * A hash function is a collision-averse pure function that maps an arbitrary block of * data to a number called a <i>hash code</i>. * * <h3>Definition</h3> * * <p>Unpacking this definition: * * <ul> * <li><b>block of data:</b> the input for a hash function is always, in concept, an * ordered byte array. This hashing API accepts an arbitrary sequence of byte and * multibyte values (via {@link Hasher}), but this is merely a convenience; these are * always translated into raw byte sequences under the covers. * * <li><b>hash code:</b> each hash function always yields hash codes of the same fixed bit * length (given by {@link #bits}). For example, {@link Hashing#sha1} produces a * 160-bit number, while {@link Hashing#murmur3_32()} yields only 32 bits. Because a * {@code long} value is clearly insufficient to hold all hash code values, this API * represents a hash code as an instance of {@link HashCode}. * * <li><b>pure function:</b> the value produced must depend only on the input bytes, in * the order they appear. Input data is never modified. {@link HashFunction} instances * should always be stateless, and therefore thread-safe. * * <li><b>collision-averse:</b> while it can't be helped that a hash function will * sometimes produce the same hash code for distinct inputs (a "collision"), every * hash function strives to <i>some</i> degree to make this unlikely. (Without this * condition, a function that always returns zero could be called a hash function. It * is not.) * </ul> * * <p>Summarizing the last two points: "equal yield equal <i>always</i>; unequal yield * unequal <i>often</i>." This is the most important characteristic of all hash functions. * * <h3>Desirable properties</h3> * * <p>A high-quality hash function strives for some subset of the following virtues: * * <ul> * <li><b>collision-resistant:</b> while the definition above requires making at least * <i>some</i> token attempt, one measure of the quality of a hash function is <i>how * well</i> it succeeds at this goal. Important note: it may be easy to achieve the * theoretical minimum collision rate when using completely <i>random</i> sample * input. The true test of a hash function is how it performs on representative * real-world data, which tends to contain many hidden patterns and clumps. The goal * of a good hash function is to stamp these patterns out as thoroughly as possible. * * <li><b>bit-dispersing:</b> masking out any <i>single bit</i> from a hash code should * yield only the expected <i>twofold</i> increase to all collision rates. Informally, * the "information" in the hash code should be as evenly "spread out" through the * hash code's bits as possible. The result is that, for example, when choosing a * bucket in a hash table of size 2^8, <i>any</i> eight bits could be consistently * used. * * <li><b>cryptographic:</b> certain hash functions such as {@link Hashing#sha512} are * designed to make it as infeasible as possible to reverse-engineer the input that * produced a given hash code, or even to discover <i>any</i> two distinct inputs that * yield the same result. These are called <i>cryptographic hash functions</i>. But, * whenever it is learned that either of these feats has become computationally * feasible, the function is deemed "broken" and should no longer be used for secure * purposes. (This is the likely eventual fate of <i>all</i> cryptographic hashes.) * * <li><b>fast:</b> perhaps self-explanatory, but often the most important consideration. * We have published <a href="#noWeHaventYet">microbenchmark results</a> for many * common hash functions. * </ul> * * <h3>Providing input to a hash function</h3> * * <p>The primary way to provide the data that your hash function should act on is via a * {@link Hasher}. Obtain a new hasher from the hash function using {@link #newHasher}, * "push" the relevant data into it using methods like {@link Hasher#putBytes(byte[])}, * and finally ask for the {@code HashCode} when finished using {@link Hasher#hash}. (See * an {@linkplain #newHasher example} of this.) * * <p>If all you want to hash is a single byte array, string or {@code long} value, there * are convenient shortcut methods defined directly on {@link HashFunction} to make this * easier. * * <p>Hasher accepts primitive data types, but can also accept any Object of type {@code * T} provided that you implement a {@link Funnel Funnel<T>} to specify how to "feed" data * from that object into the function. (See {@linkplain Hasher#putObject an example} of * this.) * * <p><b>Compatibility note:</b> Throughout this API, multibyte values are always * interpreted in <i>little-endian</i> order. That is, hashing the byte array {@code * {0x01, 0x02, 0x03, 0x04}} is equivalent to hashing the {@code int} value {@code * 0x04030201}. If this isn't what you need, methods such as {@link Integer#reverseBytes} * and {@link Ints#toByteArray} will help. * * <h3>Relationship to {@link Object#hashCode}</h3> * * <p>Java's baked-in concept of hash codes is constrained to 32 bits, and provides no * separation between hash algorithms and the data they act on, so alternate hash * algorithms can't be easily substituted. Also, implementations of {@code hashCode} tend * to be poor-quality, in part because they end up depending on <i>other</i> existing * poor-quality {@code hashCode} implementations, including those in many JDK classes. * * <p>{@code Object.hashCode} implementations tend to be very fast, but have weak * collision prevention and <i>no</i> expectation of bit dispersion. This leaves them * perfectly suitable for use in hash tables, because extra collisions cause only a slight * performance hit, while poor bit dispersion is easily corrected using a secondary hash * function (which all reasonable hash table implementations in Java use). For the many * uses of hash functions beyond data structures, however, {@code Object.hashCode} almost * always falls short -- hence this library. * * @author Kevin Bourrillion * @since 11.0 */ @Beta public interface HashFunction { /** * Begins a new hash code computation by returning an initialized, stateful {@code * Hasher} instance that is ready to receive data. Example: <pre> {@code * * HashFunction hf = Hashing.md5(); * HashCode hc = hf.newHasher() * .putLong(id) * .putBoolean(isActive) * .hash();}</pre> */ Hasher newHasher(); /** * Begins a new hash code computation as {@link #newHasher()}, but provides a hint of the * expected size of the input (in bytes). This is only important for non-streaming hash * functions (hash functions that need to buffer their whole input before processing any * of it). */ Hasher newHasher(int expectedInputSize); /** * Shortcut for {@code newHasher().putInt(input).hash()}; returns the hash code for the given * {@code int} value, interpreted in little-endian byte order. The implementation <i>might</i> * perform better than its longhand equivalent, but should not perform worse. * * @since 12.0 */ HashCode hashInt(int input); /** * Shortcut for {@code newHasher().putLong(input).hash()}; returns the hash code for the * given {@code long} value, interpreted in little-endian byte order. The implementation * <i>might</i> perform better than its longhand equivalent, but should not perform worse. */ HashCode hashLong(long input); /** * Shortcut for {@code newHasher().putBytes(input).hash()}. The implementation * <i>might</i> perform better than its longhand equivalent, but should not perform * worse. */ HashCode hashBytes(byte[] input); /** * Shortcut for {@code newHasher().putBytes(input, off, len).hash()}. The implementation * <i>might</i> perform better than its longhand equivalent, but should not perform * worse. * * @throws IndexOutOfBoundsException if {@code off < 0} or {@code off + len > bytes.length} * or {@code len < 0} */ HashCode hashBytes(byte[] input, int off, int len); /** * Shortcut for {@code newHasher().putUnencodedChars(input).hash()}. The implementation * <i>might</i> perform better than its longhand equivalent, but should not perform worse. * Note that no character encoding is performed; the low byte and high byte of each {@code char} * are hashed directly (in that order). * * @since 15.0 (since 11.0 as hashString(CharSequence)). */ HashCode hashUnencodedChars(CharSequence input); /** * Shortcut for {@code newHasher().putUnencodedChars(input).hash()}. The implementation * <i>might</i> perform better than its longhand equivalent, but should not perform worse. * Note that no character encoding is performed; the low byte and high byte of each {@code char} * are hashed directly (in that order). * * @deprecated Use {@link HashFunction#hashUnencodedChars} instead. This method is scheduled for * removal in Guava 16.0. */ @Deprecated HashCode hashString(CharSequence input); /** * Shortcut for {@code newHasher().putString(input, charset).hash()}. Characters are encoded * using the given {@link Charset}. The implementation <i>might</i> perform better than its * longhand equivalent, but should not perform worse. */ HashCode hashString(CharSequence input, Charset charset); /** * Shortcut for {@code newHasher().putObject(instance, funnel).hash()}. The implementation * <i>might</i> perform better than its longhand equivalent, but should not perform worse. * * @since 14.0 */ <T> HashCode hashObject(T instance, Funnel<? super T> funnel); /** * Returns the number of bits (a multiple of 32) that each hash code produced by this * hash function has. */ int bits(); }
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.hash; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Supplier; import java.io.Serializable; import java.util.zip.Checksum; /** * {@link HashFunction} adapter for {@link Checksum} instances. * * @author Colin Decker */ final class ChecksumHashFunction extends AbstractStreamingHashFunction implements Serializable { private final Supplier<? extends Checksum> checksumSupplier; private final int bits; private final String toString; ChecksumHashFunction(Supplier<? extends Checksum> checksumSupplier, int bits, String toString) { this.checksumSupplier = checkNotNull(checksumSupplier); checkArgument(bits == 32 || bits == 64, "bits (%s) must be either 32 or 64", bits); this.bits = bits; this.toString = checkNotNull(toString); } @Override public int bits() { return bits; } @Override public Hasher newHasher() { return new ChecksumHasher(checksumSupplier.get()); } @Override public String toString() { return toString; } /** * Hasher that updates a checksum. */ private final class ChecksumHasher extends AbstractByteHasher { private final Checksum checksum; private ChecksumHasher(Checksum checksum) { this.checksum = checkNotNull(checksum); } @Override protected void update(byte b) { checksum.update(b); } @Override protected void update(byte[] bytes, int off, int len) { checksum.update(bytes, off, len); } @Override public HashCode hash() { long value = checksum.getValue(); if (bits == 32) { /* * The long returned from a 32-bit Checksum will have all 0s for its second word, so the * cast won't lose any information and is necessary to return a HashCode of the correct * size. */ return HashCodes.fromInt((int) value); } else { return HashCodes.fromLong(value); } } } private static final long serialVersionUID = 0L; }
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.hash; import static com.google.common.base.Preconditions.checkNotNull; import java.nio.charset.Charset; /** * An abstract composition of multiple hash functions. {@linkplain #newHasher()} delegates to the * {@code Hasher} objects of the delegate hash functions, and in the end, they are used by * {@linkplain #makeHash(Hasher[])} that constructs the final {@code HashCode}. * * @author Dimitris Andreou */ abstract class AbstractCompositeHashFunction extends AbstractStreamingHashFunction { final HashFunction[] functions; AbstractCompositeHashFunction(HashFunction... functions) { for (HashFunction function : functions) { checkNotNull(function); } this.functions = functions; } /** * Constructs a {@code HashCode} from the {@code Hasher} objects of the functions. Each of them * has consumed the entire input and they are ready to output a {@code HashCode}. The order of * the hashers are the same order as the functions given to the constructor. */ // this could be cleaner if it passed HashCode[], but that would create yet another array... /* protected */ abstract HashCode makeHash(Hasher[] hashers); @Override public Hasher newHasher() { final Hasher[] hashers = new Hasher[functions.length]; for (int i = 0; i < hashers.length; i++) { hashers[i] = functions[i].newHasher(); } return new Hasher() { @Override public Hasher putByte(byte b) { for (Hasher hasher : hashers) { hasher.putByte(b); } return this; } @Override public Hasher putBytes(byte[] bytes) { for (Hasher hasher : hashers) { hasher.putBytes(bytes); } return this; } @Override public Hasher putBytes(byte[] bytes, int off, int len) { for (Hasher hasher : hashers) { hasher.putBytes(bytes, off, len); } return this; } @Override public Hasher putShort(short s) { for (Hasher hasher : hashers) { hasher.putShort(s); } return this; } @Override public Hasher putInt(int i) { for (Hasher hasher : hashers) { hasher.putInt(i); } return this; } @Override public Hasher putLong(long l) { for (Hasher hasher : hashers) { hasher.putLong(l); } return this; } @Override public Hasher putFloat(float f) { for (Hasher hasher : hashers) { hasher.putFloat(f); } return this; } @Override public Hasher putDouble(double d) { for (Hasher hasher : hashers) { hasher.putDouble(d); } return this; } @Override public Hasher putBoolean(boolean b) { for (Hasher hasher : hashers) { hasher.putBoolean(b); } return this; } @Override public Hasher putChar(char c) { for (Hasher hasher : hashers) { hasher.putChar(c); } return this; } /** * @deprecated Use {@link Hasher#putUnencodedChars} instead. */ @Deprecated @Override public Hasher putString(CharSequence chars) { return putUnencodedChars(chars); } @Override public Hasher putUnencodedChars(CharSequence chars) { for (Hasher hasher : hashers) { hasher.putUnencodedChars(chars); } return this; } @Override public Hasher putString(CharSequence chars, Charset charset) { for (Hasher hasher : hashers) { hasher.putString(chars, charset); } return this; } @Override public <T> Hasher putObject(T instance, Funnel<? super T> funnel) { for (Hasher hasher : hashers) { hasher.putObject(instance, funnel); } return this; } @Override public HashCode hash() { return makeHash(hashers); } }; } private static final long serialVersionUID = 0L; }
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.hash; import com.google.common.annotations.Beta; import java.io.Serializable; /** * An object which can send data from an object of type {@code T} into a {@code PrimitiveSink}. * Implementations for common types can be found in {@link Funnels}. * * <p>Note that serialization of {@linkplain BloomFilter bloom filters} requires the proper * serialization of funnels. When possible, it is recommended that funnels be implemented as a * single-element enum to maintain serialization guarantees. See Effective Java (2nd Edition), * Item 3: "Enforce the singleton property with a private constructor or an enum type". For example: * <pre> {@code * public enum PersonFunnel implements Funnel<Person> { * INSTANCE; * public void funnel(Person person, PrimitiveSink into) { * into.putString(person.getFirstName()) * .putString(person.getLastName()) * .putInt(person.getAge()); * } * }}</pre> * * @author Dimitris Andreou * @since 11.0 */ @Beta public interface Funnel<T> extends Serializable { /** * Sends a stream of data from the {@code from} object into the sink {@code into}. There * is no requirement that this data be complete enough to fully reconstitute the object * later. * * @since 12.0 (in Guava 11.0, {@code PrimitiveSink} was named {@code Sink}) */ void funnel(T from, PrimitiveSink into); }
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. */ /* * SipHash-c-d was designed by Jean-Philippe Aumasson and Daniel J. Bernstein and is described in * "SipHash: a fast short-input PRF" (available at https://131002.net/siphash/siphash.pdf). */ package com.google.common.hash; import static com.google.common.base.Preconditions.checkArgument; import java.io.Serializable; import java.nio.ByteBuffer; import javax.annotation.Nullable; /** * {@link HashFunction} implementation of SipHash-c-d. * * @author Kurt Alfred Kluever * @author Jean-Philippe Aumasson * @author Daniel J. Bernstein */ final class SipHashFunction extends AbstractStreamingHashFunction implements Serializable { // The number of compression rounds. private final int c; // The number of finalization rounds. private final int d; // Two 64-bit keys (represent a single 128-bit key). private final long k0; private final long k1; /** * @param c the number of compression rounds (must be positive) * @param d the number of finalization rounds (must be positive) * @param k0 the first half of the key * @param k1 the second half of the key */ SipHashFunction(int c, int d, long k0, long k1) { checkArgument(c > 0, "The number of SipRound iterations (c=%s) during Compression must be positive.", c); checkArgument(d > 0, "The number of SipRound iterations (d=%s) during Finalization must be positive.", d); this.c = c; this.d = d; this.k0 = k0; this.k1 = k1; } @Override public int bits() { return 64; } @Override public Hasher newHasher() { return new SipHasher(c, d, k0, k1); } // TODO(user): Implement and benchmark the hashFoo() shortcuts. @Override public String toString() { return "Hashing.sipHash" + c + "" + d + "(" + k0 + ", " + k1 + ")"; } @Override public boolean equals(@Nullable Object object) { if (object instanceof SipHashFunction) { SipHashFunction other = (SipHashFunction) object; return (c == other.c) && (d == other.d) && (k0 == other.k0) && (k1 == other.k1); } return false; } @Override public int hashCode() { return (int) (getClass().hashCode() ^ c ^ d ^ k0 ^ k1); } private static final class SipHasher extends AbstractStreamingHasher { private static final int CHUNK_SIZE = 8; // The number of compression rounds. private final int c; // The number of finalization rounds. private final int d; // Four 64-bit words of internal state. // The initial state corresponds to the ASCII string "somepseudorandomlygeneratedbytes", // big-endian encoded. There is nothing special about this value; the only requirement // was some asymmetry so that the initial v0 and v1 differ from v2 and v3. private long v0 = 0x736f6d6570736575L; private long v1 = 0x646f72616e646f6dL; private long v2 = 0x6c7967656e657261L; private long v3 = 0x7465646279746573L; // The number of bytes in the input. private long b = 0; // The final 64-bit chunk includes the last 0 through 7 bytes of m followed by null bytes // and ending with a byte encoding the positive integer b mod 256. private long finalM = 0; SipHasher(int c, int d, long k0, long k1) { super(CHUNK_SIZE); this.c = c; this.d = d; this.v0 ^= k0; this.v1 ^= k1; this.v2 ^= k0; this.v3 ^= k1; } @Override protected void process(ByteBuffer buffer) { b += CHUNK_SIZE; processM(buffer.getLong()); } @Override protected void processRemaining(ByteBuffer buffer) { b += buffer.remaining(); for (int i = 0; buffer.hasRemaining(); i += 8) { finalM ^= (buffer.get() & 0xFFL) << i; } } @Override public HashCode makeHash() { // End with a byte encoding the positive integer b mod 256. finalM ^= b << 56; processM(finalM); // Finalization v2 ^= 0xFFL; sipRound(d); return HashCodes.fromLong(v0 ^ v1 ^ v2 ^ v3); } private void processM(long m) { v3 ^= m; sipRound(c); v0 ^= m; } private void sipRound(int iterations) { for (int i = 0; i < iterations; i++) { v0 += v1; v2 += v3; v1 = Long.rotateLeft(v1, 13); v3 = Long.rotateLeft(v3, 16); v1 ^= v0; v3 ^= v2; v0 = Long.rotateLeft(v0, 32); v2 += v1; v0 += v3; v1 = Long.rotateLeft(v1, 17); v3 = Long.rotateLeft(v3, 21); v1 ^= v2; v3 ^= v0; v2 = Long.rotateLeft(v2, 32); } } } private static final long serialVersionUID = 0L; }
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.hash; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import java.io.OutputStream; import java.io.Serializable; import java.nio.charset.Charset; import javax.annotation.Nullable; /** * Funnels for common types. All implementations are serializable. * * @author Dimitris Andreou * @since 11.0 */ @Beta public final class Funnels { private Funnels() {} /** * Returns a funnel that extracts the bytes from a {@code byte} array. */ public static Funnel<byte[]> byteArrayFunnel() { return ByteArrayFunnel.INSTANCE; } private enum ByteArrayFunnel implements Funnel<byte[]> { INSTANCE; public void funnel(byte[] from, PrimitiveSink into) { into.putBytes(from); } @Override public String toString() { return "Funnels.byteArrayFunnel()"; } } /** * Returns a funnel that extracts the characters from a {@code CharSequence}, a character at a * time, without performing any encoding. If you need to use a specific encoding, use * {@link Funnels#stringFunnel(Charset)} instead. * * @since 15.0 (since 11.0 as {@code Funnels.stringFunnel()}. */ public static Funnel<CharSequence> unencodedCharsFunnel() { return UnencodedCharsFunnel.INSTANCE; } /** * Returns a funnel that extracts the characters from a {@code CharSequence}. * * @deprecated Use {@link Funnels#unencodedCharsFunnel} instead. This method is scheduled for * removal in Guava 16.0. */ @Deprecated public static Funnel<CharSequence> stringFunnel() { return unencodedCharsFunnel(); } private enum UnencodedCharsFunnel implements Funnel<CharSequence> { INSTANCE; public void funnel(CharSequence from, PrimitiveSink into) { into.putUnencodedChars(from); } @Override public String toString() { return "Funnels.unencodedCharsFunnel()"; } } /** * Returns a funnel that encodes the characters of a {@code CharSequence} with the specified * {@code Charset}. * * @since 15.0 */ public static Funnel<CharSequence> stringFunnel(Charset charset) { return new StringCharsetFunnel(charset); } private static class StringCharsetFunnel implements Funnel<CharSequence>, Serializable { private final Charset charset; StringCharsetFunnel(Charset charset) { this.charset = Preconditions.checkNotNull(charset); } public void funnel(CharSequence from, PrimitiveSink into) { into.putString(from, charset); } @Override public String toString() { return "Funnels.stringFunnel(" + charset.name() + ")"; } @Override public boolean equals(@Nullable Object o) { if (o instanceof StringCharsetFunnel) { StringCharsetFunnel funnel = (StringCharsetFunnel) o; return this.charset.equals(funnel.charset); } return false; } @Override public int hashCode() { return StringCharsetFunnel.class.hashCode() ^ charset.hashCode(); } Object writeReplace() { return new SerializedForm(charset); } private static class SerializedForm implements Serializable { private final String charsetCanonicalName; SerializedForm(Charset charset) { this.charsetCanonicalName = charset.name(); } private Object readResolve() { return stringFunnel(Charset.forName(charsetCanonicalName)); } private static final long serialVersionUID = 0; } } /** * Returns a funnel for integers. * * @since 13.0 */ public static Funnel<Integer> integerFunnel() { return IntegerFunnel.INSTANCE; } private enum IntegerFunnel implements Funnel<Integer> { INSTANCE; public void funnel(Integer from, PrimitiveSink into) { into.putInt(from); } @Override public String toString() { return "Funnels.integerFunnel()"; } } /** * Returns a funnel that processes an {@code Iterable} by funneling its elements in iteration * order with the specified funnel. No separators are added between the elements. * * @since 15.0 */ public static <E> Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel) { return new SequentialFunnel<E>(elementFunnel); } private static class SequentialFunnel<E> implements Funnel<Iterable<? extends E>>, Serializable { private final Funnel<E> elementFunnel; SequentialFunnel(Funnel<E> elementFunnel) { this.elementFunnel = Preconditions.checkNotNull(elementFunnel); } public void funnel(Iterable<? extends E> from, PrimitiveSink into) { for (E e : from) { elementFunnel.funnel(e, into); } } @Override public String toString() { return "Funnels.sequentialFunnel(" + elementFunnel + ")"; } @Override public boolean equals(@Nullable Object o) { if (o instanceof SequentialFunnel) { SequentialFunnel<?> funnel = (SequentialFunnel<?>) o; return elementFunnel.equals(funnel.elementFunnel); } return false; } @Override public int hashCode() { return SequentialFunnel.class.hashCode() ^ elementFunnel.hashCode(); } } /** * Returns a funnel for longs. * * @since 13.0 */ public static Funnel<Long> longFunnel() { return LongFunnel.INSTANCE; } private enum LongFunnel implements Funnel<Long> { INSTANCE; public void funnel(Long from, PrimitiveSink into) { into.putLong(from); } @Override public String toString() { return "Funnels.longFunnel()"; } } /** * Wraps a {@code PrimitiveSink} as an {@link OutputStream}, so it is easy to * {@link Funnel#funnel funnel} an object to a {@code PrimitiveSink} * if there is already a way to write the contents of the object to an {@code OutputStream}. * * <p>The {@code close} and {@code flush} methods of the returned {@code OutputStream} * do nothing, and no method throws {@code IOException}. * * @since 13.0 */ public static OutputStream asOutputStream(PrimitiveSink sink) { return new SinkAsStream(sink); } private static class SinkAsStream extends OutputStream { final PrimitiveSink sink; SinkAsStream(PrimitiveSink sink) { this.sink = Preconditions.checkNotNull(sink); } @Override public void write(int b) { sink.putByte((byte) b); } @Override public void write(byte[] bytes) { sink.putBytes(bytes); } @Override public void write(byte[] bytes, int off, int len) { sink.putBytes(bytes, off, len); } @Override public String toString() { return "Funnels.asOutputStream(" + sink + ")"; } } }
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.hash; 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.primitives.UnsignedInts; import java.io.Serializable; /** * Static factories for creating {@link HashCode} instances; most users should never have to use * this. All returned instances are {@link Serializable}. * * @author Dimitris Andreou * @since 12.0 */ @Beta public final class HashCodes { private HashCodes() {} /** * Creates a 32-bit {@code HashCode}, of which the bytes will form the passed int, interpreted * in little endian order. */ public static HashCode fromInt(int hash) { return new IntHashCode(hash); } private static final class IntHashCode extends HashCode implements Serializable { final int hash; IntHashCode(int hash) { this.hash = hash; } @Override public int bits() { return 32; } @Override public byte[] asBytes() { return new byte[] { (byte) hash, (byte) (hash >> 8), (byte) (hash >> 16), (byte) (hash >> 24)}; } @Override public int asInt() { return hash; } @Override public long asLong() { throw new IllegalStateException("this HashCode only has 32 bits; cannot create a long"); } @Override public long padToLong() { return UnsignedInts.toLong(hash); } private static final long serialVersionUID = 0; } /** * Creates a 64-bit {@code HashCode}, of which the bytes will form the passed long, interpreted * in little endian order. */ public static HashCode fromLong(long hash) { return new LongHashCode(hash); } private static final class LongHashCode extends HashCode implements Serializable { final long hash; LongHashCode(long hash) { this.hash = hash; } @Override public int bits() { return 64; } @Override public byte[] asBytes() { return new byte[] { (byte) hash, (byte) (hash >> 8), (byte) (hash >> 16), (byte) (hash >> 24), (byte) (hash >> 32), (byte) (hash >> 40), (byte) (hash >> 48), (byte) (hash >> 56)}; } @Override public int asInt() { return (int) hash; } @Override public long asLong() { return hash; } @Override public long padToLong() { return hash; } private static final long serialVersionUID = 0; } /** * Creates a {@code HashCode} from a byte array. The array is defensively copied to preserve * the immutability contract of {@code HashCode}. The array cannot be empty. */ public static HashCode fromBytes(byte[] bytes) { checkArgument(bytes.length >= 1, "A HashCode must contain at least 1 byte."); return fromBytesNoCopy(bytes.clone()); } /** * Creates a {@code HashCode} from a byte array. The array is <i>not</i> copied defensively, * so it must be handed-off so as to preserve the immutability contract of {@code HashCode}. */ static HashCode fromBytesNoCopy(byte[] bytes) { return new BytesHashCode(bytes); } private static final class BytesHashCode extends HashCode implements Serializable { final byte[] bytes; BytesHashCode(byte[] bytes) { this.bytes = checkNotNull(bytes); } @Override public int bits() { return bytes.length * 8; } @Override public byte[] asBytes() { return bytes.clone(); } @Override public int asInt() { checkState(bytes.length >= 4, "HashCode#asInt() requires >= 4 bytes (it only has %s bytes).", bytes.length); return (bytes[0] & 0xFF) | ((bytes[1] & 0xFF) << 8) | ((bytes[2] & 0xFF) << 16) | ((bytes[3] & 0xFF) << 24); } @Override public long asLong() { checkState(bytes.length >= 8, "HashCode#asLong() requires >= 8 bytes (it only has %s bytes).", bytes.length); return padToLong(); } @Override public long padToLong() { long retVal = (bytes[0] & 0xFF); for (int i = 1; i < Math.min(bytes.length, 8); i++) { retVal |= (bytes[i] & 0xFFL) << (i * 8); } return retVal; } @Override public int hashCode() { if (bytes.length >= 4) { return asInt(); } else { int val = (bytes[0] & 0xFF); for (int i = 1; i < Math.min(bytes.length, 4); i++) { val |= ((bytes[i] & 0xFF) << (i * 8)); } return val; } } 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.hash; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Supplier; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.util.Iterator; import java.util.zip.Adler32; import java.util.zip.CRC32; import java.util.zip.Checksum; import javax.annotation.Nullable; /** * Static methods to obtain {@link HashFunction} instances, and other static hashing-related * utilities. * * <p>A comparison of the various hash functions can be found * <a href="http://goo.gl/jS7HH">here</a>. * * @author Kevin Bourrillion * @author Dimitris Andreou * @author Kurt Alfred Kluever * @since 11.0 */ @Beta public final class Hashing { /** * Returns a general-purpose, <b>temporary-use</b>, non-cryptographic hash function. The algorithm * the returned function implements is unspecified and subject to change without notice. * * <p><b>Warning:</b> a new random seed for these functions is chosen each time the {@code * Hashing} class is loaded. <b>Do not use this method</b> if hash codes may escape the current * process in any way, for example being sent over RPC, or saved to disk. * * <p>Repeated calls to this method on the same loaded {@code Hashing} class, using the same value * for {@code minimumBits}, will return identically-behaving {@link HashFunction} instances. * * @param minimumBits a positive integer (can be arbitrarily large) * @return a hash function, described above, that produces hash codes of length {@code * minimumBits} or greater */ public static HashFunction goodFastHash(int minimumBits) { int bits = checkPositiveAndMakeMultipleOf32(minimumBits); if (bits == 32) { return GOOD_FAST_HASH_FUNCTION_32; } if (bits <= 128) { return GOOD_FAST_HASH_FUNCTION_128; } // Otherwise, join together some 128-bit murmur3s int hashFunctionsNeeded = (bits + 127) / 128; HashFunction[] hashFunctions = new HashFunction[hashFunctionsNeeded]; hashFunctions[0] = GOOD_FAST_HASH_FUNCTION_128; int seed = GOOD_FAST_HASH_SEED; for (int i = 1; i < hashFunctionsNeeded; i++) { seed += 1500450271; // a prime; shouldn't matter hashFunctions[i] = murmur3_128(seed); } return new ConcatenatedHashFunction(hashFunctions); } /** * Used to randomize {@link #goodFastHash} instances, so that programs which persist anything * dependent on the hash codes they produce will fail sooner. */ private static final int GOOD_FAST_HASH_SEED = (int) System.currentTimeMillis(); /** Returned by {@link #goodFastHash} when {@code minimumBits <= 32}. */ private static final HashFunction GOOD_FAST_HASH_FUNCTION_32 = murmur3_32(GOOD_FAST_HASH_SEED); /** Returned by {@link #goodFastHash} when {@code 32 < minimumBits <= 128}. */ private static final HashFunction GOOD_FAST_HASH_FUNCTION_128 = murmur3_128(GOOD_FAST_HASH_SEED); /** * Returns a hash function implementing the * <a href="http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp"> * 32-bit murmur3 algorithm, x86 variant</a> (little-endian variant), * using the given seed value. * * <p>The exact C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A). */ public static HashFunction murmur3_32(int seed) { return new Murmur3_32HashFunction(seed); } /** * Returns a hash function implementing the * <a href="http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp"> * 32-bit murmur3 algorithm, x86 variant</a> (little-endian variant), * using a seed value of zero. * * <p>The exact C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A). */ public static HashFunction murmur3_32() { return MURMUR3_32; } private static final HashFunction MURMUR3_32 = new Murmur3_32HashFunction(0); /** * Returns a hash function implementing the * <a href="http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp"> * 128-bit murmur3 algorithm, x64 variant</a> (little-endian variant), * using the given seed value. * * <p>The exact C++ equivalent is the MurmurHash3_x64_128 function (Murmur3F). */ public static HashFunction murmur3_128(int seed) { return new Murmur3_128HashFunction(seed); } /** * Returns a hash function implementing the * <a href="http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp"> * 128-bit murmur3 algorithm, x64 variant</a> (little-endian variant), * using a seed value of zero. * * <p>The exact C++ equivalent is the MurmurHash3_x64_128 function (Murmur3F). */ public static HashFunction murmur3_128() { return MURMUR3_128; } private static final HashFunction MURMUR3_128 = new Murmur3_128HashFunction(0); /** * Returns a hash function implementing the * <a href="https://131002.net/siphash/">64-bit SipHash-2-4 algorithm</a> * using a seed value of {@code k = 00 01 02 ...}. * * @since 15.0 */ public static HashFunction sipHash24() { return SIP_HASH_24; } private static final HashFunction SIP_HASH_24 = new SipHashFunction(2, 4, 0x0706050403020100L, 0x0f0e0d0c0b0a0908L); /** * Returns a hash function implementing the * <a href="https://131002.net/siphash/">64-bit SipHash-2-4 algorithm</a> * using the given seed. * * @since 15.0 */ public static HashFunction sipHash24(long k0, long k1) { return new SipHashFunction(2, 4, k0, k1); } /** * Returns a hash function implementing the MD5 hash algorithm (128 hash bits) by delegating to * the MD5 {@link MessageDigest}. */ public static HashFunction md5() { return MD5; } private static final HashFunction MD5 = new MessageDigestHashFunction("MD5", "Hashing.md5()"); /** * Returns a hash function implementing the SHA-1 algorithm (160 hash bits) by delegating to the * SHA-1 {@link MessageDigest}. */ public static HashFunction sha1() { return SHA_1; } private static final HashFunction SHA_1 = new MessageDigestHashFunction("SHA-1", "Hashing.sha1()"); /** * Returns a hash function implementing the SHA-256 algorithm (256 hash bits) by delegating to * the SHA-256 {@link MessageDigest}. */ public static HashFunction sha256() { return SHA_256; } private static final HashFunction SHA_256 = new MessageDigestHashFunction("SHA-256", "Hashing.sha256()"); /** * Returns a hash function implementing the SHA-512 algorithm (512 hash bits) by delegating to the * SHA-512 {@link MessageDigest}. */ public static HashFunction sha512() { return SHA_512; } private static final HashFunction SHA_512 = new MessageDigestHashFunction("SHA-512", "Hashing.sha512()"); /** * Returns a hash function implementing the CRC-32 checksum algorithm (32 hash bits) by delegating * to the {@link CRC32} {@link Checksum}. * * <p>To get the {@code long} value equivalent to {@link Checksum#getValue()} for a * {@code HashCode} produced by this function, use {@link HashCode#padToLong()}. * * @since 14.0 */ public static HashFunction crc32() { return CRC_32; } private static final HashFunction CRC_32 = checksumHashFunction(ChecksumType.CRC_32, "Hashing.crc32()"); /** * Returns a hash function implementing the Adler-32 checksum algorithm (32 hash bits) by * delegating to the {@link Adler32} {@link Checksum}. * * <p>To get the {@code long} value equivalent to {@link Checksum#getValue()} for a * {@code HashCode} produced by this function, use {@link HashCode#padToLong()}. * * @since 14.0 */ public static HashFunction adler32() { return ADLER_32; } private static final HashFunction ADLER_32 = checksumHashFunction(ChecksumType.ADLER_32, "Hashing.adler32()"); private static HashFunction checksumHashFunction(ChecksumType type, String toString) { return new ChecksumHashFunction(type, type.bits, toString); } enum ChecksumType implements Supplier<Checksum> { CRC_32(32) { @Override public Checksum get() { return new CRC32(); } }, ADLER_32(32) { @Override public Checksum get() { return new Adler32(); } }; private final int bits; ChecksumType(int bits) { this.bits = bits; } @Override public abstract Checksum get(); } // Lazy initialization holder class idiom. // TODO(user): Investigate whether we need to still use this idiom now that we have a fallback // option for our use of Unsafe. /** * Assigns to {@code hashCode} a "bucket" in the range {@code [0, buckets)}, in a uniform * manner that minimizes the need for remapping as {@code buckets} grows. That is, * {@code consistentHash(h, n)} equals: * * <ul> * <li>{@code n - 1}, with approximate probability {@code 1/n} * <li>{@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n}) * </ul> * * <p>See the <a href="http://en.wikipedia.org/wiki/Consistent_hashing">wikipedia * article on consistent hashing</a> for more information. */ public static int consistentHash(HashCode hashCode, int buckets) { return consistentHash(hashCode.padToLong(), buckets); } /** * Assigns to {@code input} a "bucket" in the range {@code [0, buckets)}, in a uniform * manner that minimizes the need for remapping as {@code buckets} grows. That is, * {@code consistentHash(h, n)} equals: * * <ul> * <li>{@code n - 1}, with approximate probability {@code 1/n} * <li>{@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n}) * </ul> * * <p>See the <a href="http://en.wikipedia.org/wiki/Consistent_hashing">wikipedia * article on consistent hashing</a> for more information. */ public static int consistentHash(long input, int buckets) { checkArgument(buckets > 0, "buckets must be positive: %s", buckets); LinearCongruentialGenerator generator = new LinearCongruentialGenerator(input); int candidate = 0; int next; // Jump from bucket to bucket until we go out of range while (true) { next = (int) ((candidate + 1) / generator.nextDouble()); if (next >= 0 && next < buckets) { candidate = next; } else { return candidate; } } } /** * Returns a hash code, having the same bit length as each of the input hash codes, * that combines the information of these hash codes in an ordered fashion. That * is, whenever two equal hash codes are produced by two calls to this method, it * is <i>as likely as possible</i> that each was computed from the <i>same</i> * input hash codes in the <i>same</i> order. * * @throws IllegalArgumentException if {@code hashCodes} is empty, or the hash codes * do not all have the same bit length */ public static HashCode combineOrdered(Iterable<HashCode> hashCodes) { Iterator<HashCode> iterator = hashCodes.iterator(); checkArgument(iterator.hasNext(), "Must be at least 1 hash code to combine."); int bits = iterator.next().bits(); byte[] resultBytes = new byte[bits / 8]; for (HashCode hashCode : hashCodes) { byte[] nextBytes = hashCode.asBytes(); checkArgument(nextBytes.length == resultBytes.length, "All hashcodes must have the same bit length."); for (int i = 0; i < nextBytes.length; i++) { resultBytes[i] = (byte) (resultBytes[i] * 37 ^ nextBytes[i]); } } return HashCodes.fromBytesNoCopy(resultBytes); } /** * Returns a hash code, having the same bit length as each of the input hash codes, * that combines the information of these hash codes in an unordered fashion. That * is, whenever two equal hash codes are produced by two calls to this method, it * is <i>as likely as possible</i> that each was computed from the <i>same</i> * input hash codes in <i>some</i> order. * * @throws IllegalArgumentException if {@code hashCodes} is empty, or the hash codes * do not all have the same bit length */ public static HashCode combineUnordered(Iterable<HashCode> hashCodes) { Iterator<HashCode> iterator = hashCodes.iterator(); checkArgument(iterator.hasNext(), "Must be at least 1 hash code to combine."); byte[] resultBytes = new byte[iterator.next().bits() / 8]; for (HashCode hashCode : hashCodes) { byte[] nextBytes = hashCode.asBytes(); checkArgument(nextBytes.length == resultBytes.length, "All hashcodes must have the same bit length."); for (int i = 0; i < nextBytes.length; i++) { resultBytes[i] += nextBytes[i]; } } return HashCodes.fromBytesNoCopy(resultBytes); } /** * Checks that the passed argument is positive, and ceils it to a multiple of 32. */ static int checkPositiveAndMakeMultipleOf32(int bits) { checkArgument(bits > 0, "Number of bits must be positive"); return (bits + 31) & ~31; } // TODO(kevinb): Maybe expose this class via a static Hashing method? @VisibleForTesting static final class ConcatenatedHashFunction extends AbstractCompositeHashFunction { private final int bits; ConcatenatedHashFunction(HashFunction... functions) { super(functions); int bitSum = 0; for (HashFunction function : functions) { bitSum += function.bits(); } this.bits = bitSum; } @Override HashCode makeHash(Hasher[] hashers) { // TODO(user): Get rid of the ByteBuffer here? byte[] bytes = new byte[bits / 8]; ByteBuffer buffer = ByteBuffer.wrap(bytes); for (Hasher hasher : hashers) { buffer.put(hasher.hash().asBytes()); } return HashCodes.fromBytesNoCopy(bytes); } @Override public int bits() { return bits; } @Override public boolean equals(@Nullable Object object) { if (object instanceof ConcatenatedHashFunction) { ConcatenatedHashFunction other = (ConcatenatedHashFunction) object; if (bits != other.bits || functions.length != other.functions.length) { return false; } for (int i = 0; i < functions.length; i++) { if (!functions[i].equals(other.functions[i])) { return false; } } return true; } return false; } @Override public int hashCode() { int hash = bits; for (HashFunction function : functions) { hash ^= function.hashCode(); } return hash; } } /** * Linear CongruentialGenerator to use for consistent hashing. * See http://en.wikipedia.org/wiki/Linear_congruential_generator */ private static final class LinearCongruentialGenerator { private long state; public LinearCongruentialGenerator(long seed) { this.state = seed; } public double nextDouble() { state = 2862933555777941757L * state + 1; return ((double) ((int) (state >>> 33) + 1)) / (0x1.0p31); } } private Hashing() {} }
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.hash; import java.nio.charset.Charset; /** * An abstract hasher, implementing {@link #putBoolean(boolean)}, {@link #putDouble(double)}, * {@link #putFloat(float)}, {@link #putUnencodedChars(CharSequence)}, and * {@link #putString(CharSequence, Charset)} as prescribed by {@link Hasher}. * * @author Dimitris Andreou */ abstract class AbstractHasher implements Hasher { @Override public final Hasher putBoolean(boolean b) { return putByte(b ? (byte) 1 : (byte) 0); } @Override public final Hasher putDouble(double d) { return putLong(Double.doubleToRawLongBits(d)); } @Override public final Hasher putFloat(float f) { return putInt(Float.floatToRawIntBits(f)); } /** * @deprecated Use {@link AbstractHasher#putUnencodedChars} instead. */ @Deprecated @Override public Hasher putString(CharSequence charSequence) { return putUnencodedChars(charSequence); } @Override public Hasher putUnencodedChars(CharSequence charSequence) { for (int i = 0, len = charSequence.length(); i < len; i++) { putChar(charSequence.charAt(i)); } return this; } @Override public Hasher putString(CharSequence charSequence, Charset charset) { return putBytes(charSequence.toString().getBytes(charset)); } }
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.hash; import com.google.common.annotations.Beta; import java.nio.charset.Charset; /** * A {@link PrimitiveSink} that can compute a hash code after reading the input. Each hasher should * translate all multibyte values ({@link #putInt(int)}, {@link #putLong(long)}, etc) to bytes * in little-endian order. * * <p><b>Warning:</b> The result of calling any methods after calling {@link #hash} is undefined. * * <p><b>Warning:</b> Using a specific character encoding when hashing a {@link CharSequence} with * {@link #putString(CharSequence, Charset)} is generally only useful for cross-language * compatibility (otherwise prefer {@link #putUnencodedChars}). However, the character encodings * must be identical across languages. Also beware that {@link Charset} definitions may occasionally * change between Java releases. * * <p><b>Warning:</b> Chunks of data that are put into the {@link Hasher} are not delimited. * The resulting {@link HashCode} is dependent only on the bytes inserted, and the order in which * they were inserted, not how those bytes were chunked into discrete put() operations. For example, * the following three expressions all generate colliding hash codes: <pre> {@code * * newHasher().putByte(b1).putByte(b2).putByte(b3).hash() * newHasher().putByte(b1).putBytes(new byte[] { b2, b3 }).hash() * newHasher().putBytes(new byte[] { b1, b2, b3 }).hash()}</pre> * * <p>If you wish to avoid this, you should either prepend or append the size of each chunk. Keep in * mind that when dealing with char sequences, the encoded form of two concatenated char sequences * is not equivalent to the concatenation of their encoded form. Therefore, * {@link #putString(CharSequence, Charset)} should only be used consistently with <i>complete</i> * sequences and not broken into chunks. * * @author Kevin Bourrillion * @since 11.0 */ @Beta public interface Hasher extends PrimitiveSink { @Override Hasher putByte(byte b); @Override Hasher putBytes(byte[] bytes); @Override Hasher putBytes(byte[] bytes, int off, int len); @Override Hasher putShort(short s); @Override Hasher putInt(int i); @Override Hasher putLong(long l); /** * Equivalent to {@code putInt(Float.floatToRawIntBits(f))}. */ @Override Hasher putFloat(float f); /** * Equivalent to {@code putLong(Double.doubleToRawLongBits(d))}. */ @Override Hasher putDouble(double d); /** * Equivalent to {@code putByte(b ? (byte) 1 : (byte) 0)}. */ @Override Hasher putBoolean(boolean b); @Override Hasher putChar(char c); /** * Equivalent to processing each {@code char} value in the {@code CharSequence}, in order. * The input must not be updated while this method is in progress. * * @since 15.0 (since 11.0 as putString(CharSequence)). */ @Override Hasher putUnencodedChars(CharSequence charSequence); /** * Equivalent to processing each {@code char} value in the {@code CharSequence}, in order. * The input must not be updated while this method is in progress. * * @deprecated Use {@link Hasher#putUnencodedChars} instead. This method is scheduled for * removal in Guava 16.0. */ @Deprecated @Override Hasher putString(CharSequence charSequence); /** * Equivalent to {@code putBytes(charSequence.toString().getBytes(charset))}. */ @Override Hasher putString(CharSequence charSequence, Charset charset); /** * A simple convenience for {@code funnel.funnel(object, this)}. */ <T> Hasher putObject(T instance, Funnel<? super T> funnel); /** * Computes a hash code based on the data that have been provided to this hasher. The result is * unspecified if this method is called more than once on the same instance. */ HashCode hash(); }
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. */ /* * MurmurHash3 was written by Austin Appleby, and is placed in the public * domain. The author hereby disclaims copyright to this source code. */ /* * Source: * http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp * (Modified to adapt to Guava coding conventions and to use the HashFunction interface) */ package com.google.common.hash; import static com.google.common.primitives.UnsignedBytes.toInt; import com.google.common.primitives.Chars; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; import java.io.Serializable; import java.nio.ByteBuffer; import javax.annotation.Nullable; /** * See http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp * MurmurHash3_x86_32 * * @author Austin Appleby * @author Dimitris Andreou * @author Kurt Alfred Kluever */ final class Murmur3_32HashFunction extends AbstractStreamingHashFunction implements Serializable { private static final int C1 = 0xcc9e2d51; private static final int C2 = 0x1b873593; private final int seed; Murmur3_32HashFunction(int seed) { this.seed = seed; } @Override public int bits() { return 32; } @Override public Hasher newHasher() { return new Murmur3_32Hasher(seed); } @Override public String toString() { return "Hashing.murmur3_32(" + seed + ")"; } @Override public boolean equals(@Nullable Object object) { if (object instanceof Murmur3_32HashFunction) { Murmur3_32HashFunction other = (Murmur3_32HashFunction) object; return seed == other.seed; } return false; } @Override public int hashCode() { return getClass().hashCode() ^ seed; } @Override public HashCode hashInt(int input) { int k1 = mixK1(input); int h1 = mixH1(seed, k1); return fmix(h1, Ints.BYTES); } @Override public HashCode hashLong(long input) { int low = (int) input; int high = (int) (input >>> 32); int k1 = mixK1(low); int h1 = mixH1(seed, k1); k1 = mixK1(high); h1 = mixH1(h1, k1); return fmix(h1, Longs.BYTES); } // TODO(user): Maybe implement #hashBytes instead? @Override public HashCode hashString(CharSequence input) { int h1 = seed; // step through the CharSequence 2 chars at a time for (int i = 1; i < input.length(); i += 2) { int k1 = input.charAt(i - 1) | (input.charAt(i) << 16); k1 = mixK1(k1); h1 = mixH1(h1, k1); } // deal with any remaining characters if ((input.length() & 1) == 1) { int k1 = input.charAt(input.length() - 1); k1 = mixK1(k1); h1 ^= k1; } return fmix(h1, Chars.BYTES * input.length()); } private static int mixK1(int k1) { k1 *= C1; k1 = Integer.rotateLeft(k1, 15); k1 *= C2; return k1; } private static int mixH1(int h1, int k1) { h1 ^= k1; h1 = Integer.rotateLeft(h1, 13); h1 = h1 * 5 + 0xe6546b64; return h1; } // Finalization mix - force all bits of a hash block to avalanche private static HashCode fmix(int h1, int length) { h1 ^= length; h1 ^= h1 >>> 16; h1 *= 0x85ebca6b; h1 ^= h1 >>> 13; h1 *= 0xc2b2ae35; h1 ^= h1 >>> 16; return HashCodes.fromInt(h1); } private static final class Murmur3_32Hasher extends AbstractStreamingHasher { private static final int CHUNK_SIZE = 4; private int h1; private int length; Murmur3_32Hasher(int seed) { super(CHUNK_SIZE); this.h1 = seed; this.length = 0; } @Override protected void process(ByteBuffer bb) { int k1 = Murmur3_32HashFunction.mixK1(bb.getInt()); h1 = Murmur3_32HashFunction.mixH1(h1, k1); length += CHUNK_SIZE; } @Override protected void processRemaining(ByteBuffer bb) { length += bb.remaining(); int k1 = 0; for (int i = 0; bb.hasRemaining(); i += 8) { k1 ^= toInt(bb.get()) << i; } h1 ^= Murmur3_32HashFunction.mixK1(k1); } @Override public HashCode makeHash() { return Murmur3_32HashFunction.fmix(h1, length); } } private static final long serialVersionUID = 0L; }
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.hash; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import com.google.common.primitives.Ints; import java.security.MessageDigest; import javax.annotation.Nullable; /** * An immutable hash code of arbitrary bit length. * * @author Dimitris Andreou * @since 11.0 */ @Beta public abstract class HashCode { HashCode() {} /** * Returns the first four bytes of {@linkplain #asBytes() this hashcode's bytes}, converted to * an {@code int} value in little-endian order. * * @throws IllegalStateException if {@code bits() < 32} */ public abstract int asInt(); /** * Returns the first eight bytes of {@linkplain #asBytes() this hashcode's bytes}, converted to * a {@code long} value in little-endian order. * * @throws IllegalStateException if {@code bits() < 64} */ public abstract long asLong(); /** * If this hashcode has enough bits, returns {@code asLong()}, otherwise returns a {@code long} * value with {@code asBytes()} as the least-significant bytes and {@code 0x00} as the remaining * most-significant bytes. * * @since 14.0 (since 11.0 as {@code Hashing.padToLong(HashCode)}) */ public abstract long padToLong(); /** * Returns the value of this hash code as a byte array. The caller may modify the byte array; * changes to it will <i>not</i> be reflected in this {@code HashCode} object or any other arrays * returned by this method. */ // TODO(user): consider ByteString here, when that is available public abstract byte[] asBytes(); /** * Copies bytes from this hash code into {@code dest}. * * @param dest the byte array into which the hash code will be written * @param offset the start offset in the data * @param maxLength the maximum number of bytes to write * @return the number of bytes written to {@code dest} * @throws IndexOutOfBoundsException if there is not enough room in {@code dest} */ public int writeBytesTo(byte[] dest, int offset, int maxLength) { byte[] hash = asBytes(); maxLength = Ints.min(maxLength, hash.length); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); System.arraycopy(hash, 0, dest, offset, maxLength); return maxLength; } /** * Returns the number of bits in this hash code; a positive multiple of 8. */ public abstract int bits(); @Override public boolean equals(@Nullable Object object) { if (object instanceof HashCode) { HashCode that = (HashCode) object; // Undocumented: this is a non-short-circuiting equals(), in case this is a cryptographic // hash code, in which case we don't want to leak timing information return MessageDigest.isEqual(this.asBytes(), that.asBytes()); } return false; } /** * Returns a "Java hash code" for this {@code HashCode} instance; this is well-defined * (so, for example, you can safely put {@code HashCode} instances into a {@code * HashSet}) but is otherwise probably not what you want to use. */ @Override public int hashCode() { /* * As long as the hash function that produced this isn't of horrible quality, this * won't be of horrible quality either. */ return asInt(); } /** * Returns a string containing each byte of {@link #asBytes}, in order, as a two-digit unsigned * hexadecimal number in lower case. * * <p>Note that if the output is considered to be a single hexadecimal number, this hash code's * bytes are the <i>big-endian</i> representation of that number. This may be surprising since * everything else in the hashing API uniformly treats multibyte values as little-endian. But * this format conveniently matches that of utilities such as the UNIX {@code md5sum} command. */ @Override public String toString() { byte[] bytes = asBytes(); StringBuilder sb = new StringBuilder(2 * bytes.length); for (byte b : bytes) { sb.append(hexDigits[(b >> 4) & 0xf]).append(hexDigits[b & 0xf]); } return sb.toString(); } private static final char[] hexDigits = "0123456789abcdef".toCharArray(); }
Java
/* * Copyright (C) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; 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.collect.ObjectArrays; import com.google.common.collect.Sets; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * A TimeLimiter that runs method calls in the background using an * {@link ExecutorService}. If the time limit expires for a given method call, * the thread running the call will be interrupted. * * @author Kevin Bourrillion * @since 1.0 */ @Beta public final class SimpleTimeLimiter implements TimeLimiter { private final ExecutorService executor; /** * Constructs a TimeLimiter instance using the given executor service to * execute proxied method calls. * <p> * <b>Warning:</b> using a bounded executor * may be counterproductive! If the thread pool fills up, any time callers * spend waiting for a thread may count toward their time limit, and in * this case the call may even time out before the target method is ever * invoked. * * @param executor the ExecutorService that will execute the method calls on * the target objects; for example, a {@link * Executors#newCachedThreadPool()}. */ public SimpleTimeLimiter(ExecutorService executor) { this.executor = checkNotNull(executor); } /** * Constructs a TimeLimiter instance using a {@link * Executors#newCachedThreadPool()} to execute proxied method calls. * * <p><b>Warning:</b> using a bounded executor may be counterproductive! If * the thread pool fills up, any time callers spend waiting for a thread may * count toward their time limit, and in this case the call may even time out * before the target method is ever invoked. */ public SimpleTimeLimiter() { this(Executors.newCachedThreadPool()); } @Override public <T> T newProxy(final T target, Class<T> interfaceType, final long timeoutDuration, final TimeUnit timeoutUnit) { checkNotNull(target); checkNotNull(interfaceType); checkNotNull(timeoutUnit); checkArgument(timeoutDuration > 0, "bad timeout: " + timeoutDuration); checkArgument(interfaceType.isInterface(), "interfaceType must be an interface type"); final Set<Method> interruptibleMethods = findInterruptibleMethods(interfaceType); InvocationHandler handler = new InvocationHandler() { @Override public Object invoke(Object obj, final Method method, final Object[] args) throws Throwable { Callable<Object> callable = new Callable<Object>() { @Override public Object call() throws Exception { try { return method.invoke(target, args); } catch (InvocationTargetException e) { throwCause(e, false); throw new AssertionError("can't get here"); } } }; return callWithTimeout(callable, timeoutDuration, timeoutUnit, interruptibleMethods.contains(method)); } }; return newProxy(interfaceType, handler); } // TODO: should this actually throw only ExecutionException? @Override public <T> T callWithTimeout(Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit, boolean amInterruptible) throws Exception { checkNotNull(callable); checkNotNull(timeoutUnit); checkArgument(timeoutDuration > 0, "timeout must be positive: %s", timeoutDuration); Future<T> future = executor.submit(callable); try { if (amInterruptible) { try { return future.get(timeoutDuration, timeoutUnit); } catch (InterruptedException e) { future.cancel(true); throw e; } } else { return Uninterruptibles.getUninterruptibly(future, timeoutDuration, timeoutUnit); } } catch (ExecutionException e) { throw throwCause(e, true); } catch (TimeoutException e) { future.cancel(true); throw new UncheckedTimeoutException(e); } } private static Exception throwCause(Exception e, boolean combineStackTraces) throws Exception { Throwable cause = e.getCause(); if (cause == null) { throw e; } if (combineStackTraces) { StackTraceElement[] combined = ObjectArrays.concat(cause.getStackTrace(), e.getStackTrace(), StackTraceElement.class); cause.setStackTrace(combined); } if (cause instanceof Exception) { throw (Exception) cause; } if (cause instanceof Error) { throw (Error) cause; } // The cause is a weird kind of Throwable, so throw the outer exception. throw e; } private static Set<Method> findInterruptibleMethods(Class<?> interfaceType) { Set<Method> set = Sets.newHashSet(); for (Method m : interfaceType.getMethods()) { if (declaresInterruptedEx(m)) { set.add(m); } } return set; } private static boolean declaresInterruptedEx(Method method) { for (Class<?> exType : method.getExceptionTypes()) { // debate: == or isAssignableFrom? if (exType == InterruptedException.class) { return true; } } return false; } // TODO: replace with version in common.reflect if and when it's open-sourced private static <T> T newProxy( Class<T> interfaceType, InvocationHandler handler) { Object object = Proxy.newProxyInstance(interfaceType.getClassLoader(), new Class<?>[] { interfaceType }, handler); return interfaceType.cast(object); } }
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.util.concurrent; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import javax.annotation.Nullable; /** * A callback for accepting the results of a {@link java.util.concurrent.Future} * computation asynchronously. * * <p>To attach to a {@link ListenableFuture} use {@link Futures#addCallback}. * * @author Anthony Zana * @since 10.0 */ public interface FutureCallback<V> { /** * Invoked with the result of the {@code Future} computation when it is * successful. */ void onSuccess(@Nullable V result); /** * Invoked when a {@code Future} computation fails or is canceled. * * <p>If the future's {@link Future#get() get} method throws an {@link * ExecutionException}, then the cause is passed to this method. Any other * thrown object is passed unaltered. */ void onFailure(Throwable t); }
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.util.concurrent; import com.google.common.annotations.Beta; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; /** * An object with an operational state, plus asynchronous {@link #start()} and {@link #stop()} * lifecycle methods to transition between states. Example services include webservers, RPC servers * and timers. * * <p>The normal lifecycle of a service is: * <ul> * <li>{@linkplain State#NEW NEW} -&gt; * <li>{@linkplain State#STARTING STARTING} -&gt; * <li>{@linkplain State#RUNNING RUNNING} -&gt; * <li>{@linkplain State#STOPPING STOPPING} -&gt; * <li>{@linkplain State#TERMINATED TERMINATED} * </ul> * * <p>There are deviations from this if there are failures or if {@link Service#stop} is called * before the {@link Service} reaches the {@linkplain State#RUNNING RUNNING} state. The set of legal * transitions form a <a href="http://en.wikipedia.org/wiki/Directed_acyclic_graph">DAG</a>, * therefore every method of the listener will be called at most once. N.B. The {@link State#FAILED} * and {@link State#TERMINATED} states are terminal states, once a service enters either of these * states it cannot ever leave them. * * <p>Implementors of this interface are strongly encouraged to extend one of the abstract classes * in this package which implement this interface and make the threading and state management * easier. * * @author Jesse Wilson * @author Luke Sandberg * @since 9.0 (in 1.0 as {@code com.google.common.base.Service}) */ @Beta public interface Service { /** * If the service state is {@link State#NEW}, this initiates service startup and returns * immediately. If the service has already been started, this method returns immediately without * taking action. A stopped service may not be restarted. * * @return a future for the startup result, regardless of whether this call initiated startup. * Calling {@link ListenableFuture#get} will block until the service has finished * starting, and returns one of {@link State#RUNNING}, {@link State#STOPPING} or * {@link State#TERMINATED}. If the service fails to start, {@link ListenableFuture#get} * will throw an {@link ExecutionException}, and the service's state will be * {@link State#FAILED}. If it has already finished starting, {@link ListenableFuture#get} * returns immediately. Cancelling this future has no effect on the service. */ ListenableFuture<State> start(); /** * Initiates service startup (if necessary), returning once the service has finished starting. * Unlike calling {@code start().get()}, this method throws no checked exceptions, and it cannot * be {@linkplain Thread#interrupt interrupted}. * * @throws UncheckedExecutionException if startup failed * @return the state of the service when startup finished. */ State startAndWait(); /** * Returns {@code true} if this service is {@linkplain State#RUNNING running}. */ boolean isRunning(); /** * Returns the lifecycle state of the service. */ State state(); /** * If the service is {@linkplain State#STARTING starting} or {@linkplain State#RUNNING running}, * this initiates service shutdown and returns immediately. If the service is * {@linkplain State#NEW new}, it is {@linkplain State#TERMINATED terminated} without having been * started nor stopped. If the service has already been stopped, this method returns immediately * without taking action. * * @return a future for the shutdown result, regardless of whether this call initiated shutdown. * Calling {@link ListenableFuture#get} will block until the service has finished shutting * down, and either returns {@link State#TERMINATED} or throws an * {@link ExecutionException}. If it has already finished stopping, * {@link ListenableFuture#get} returns immediately. Cancelling this future has no effect * on the service. */ ListenableFuture<State> stop(); /** * Initiates service shutdown (if necessary), returning once the service has finished stopping. If * this is {@link State#STARTING}, startup will be cancelled. If this is {@link State#NEW}, it is * {@link State#TERMINATED terminated} without having been started nor stopped. Unlike calling * {@code stop().get()}, this method throws no checked exceptions. * * @throws UncheckedExecutionException if the service has failed or fails during shutdown * @return the state of the service when shutdown finished. */ State stopAndWait(); /** * Returns the {@link Throwable} that caused this service to fail. * * @throws IllegalStateException if this service's state isn't {@linkplain State#FAILED FAILED}. * * @since 14.0 */ Throwable failureCause(); /** * Registers a {@link Listener} to be {@linkplain Executor#execute executed} on the given * executor. The listener will have the corresponding transition method called whenever the * service changes state. The listener will not have previous state changes replayed, so it is * suggested that listeners are added before the service starts. * * <p>There is no guaranteed ordering of execution of listeners, but any listener added through * this method is guaranteed to be called whenever there is a state change. * * <p>Exceptions thrown by a listener will be propagated up to the executor. Any exception thrown * during {@code Executor.execute} (e.g., a {@code RejectedExecutionException} or an exception * thrown by {@linkplain MoreExecutors#sameThreadExecutor inline execution}) will be caught and * logged. * * @param listener the listener to run when the service changes state is complete * @param executor the executor in which the listeners callback methods will be run. For fast, * lightweight listeners that would be safe to execute in any thread, consider * {@link MoreExecutors#sameThreadExecutor}. * @since 13.0 */ void addListener(Listener listener, Executor executor); /** * The lifecycle states of a service. * * @since 9.0 (in 1.0 as {@code com.google.common.base.Service.State}) */ @Beta // should come out of Beta when Service does enum State { /** * A service in this state is inactive. It does minimal work and consumes * minimal resources. */ NEW, /** * A service in this state is transitioning to {@link #RUNNING}. */ STARTING, /** * A service in this state is operational. */ RUNNING, /** * A service in this state is transitioning to {@link #TERMINATED}. */ STOPPING, /** * A service in this state has completed execution normally. It does minimal work and consumes * minimal resources. */ TERMINATED, /** * A service in this state has encountered a problem and may not be operational. It cannot be * started nor stopped. */ FAILED } /** * A listener for the various state changes that a {@link Service} goes through in its lifecycle. * * <p>All methods are no-ops by default, implementors should override the ones they care about. * * @author Luke Sandberg * @since 15.0 (present as an interface in 13.0) */ @Beta // should come out of Beta when Service does abstract class Listener { /** * Called when the service transitions from {@linkplain State#NEW NEW} to * {@linkplain State#STARTING STARTING}. This occurs when {@link Service#start} or * {@link Service#startAndWait} is called the first time. */ public void starting() {} /** * Called when the service transitions from {@linkplain State#STARTING STARTING} to * {@linkplain State#RUNNING RUNNING}. This occurs when a service has successfully started. */ public void running() {} /** * Called when the service transitions to the {@linkplain State#STOPPING STOPPING} state. The * only valid values for {@code from} are {@linkplain State#STARTING STARTING} or * {@linkplain State#RUNNING RUNNING}. This occurs when {@link Service#stop} is called. * * @param from The previous state that is being transitioned from. */ public void stopping(State from) {} /** * Called when the service transitions to the {@linkplain State#TERMINATED TERMINATED} state. * The {@linkplain State#TERMINATED TERMINATED} state is a terminal state in the transition * diagram. Therefore, if this method is called, no other methods will be called on the * {@link Listener}. * * @param from The previous state that is being transitioned from. The only valid values for * this are {@linkplain State#NEW NEW}, {@linkplain State#RUNNING RUNNING} or * {@linkplain State#STOPPING STOPPING}. */ public void terminated(State from) {} /** * Called when the service transitions to the {@linkplain State#FAILED FAILED} state. The * {@linkplain State#FAILED FAILED} state is a terminal state in the transition diagram. * Therefore, if this method is called, no other methods will be called on the {@link Listener}. * * @param from The previous state that is being transitioned from. Failure can occur in any * state with the exception of {@linkplain State#NEW NEW} or * {@linkplain State#TERMINATED TERMINATED}. * @param failure The exception that caused the failure. */ public void failed(State from, Throwable failure) {} } }
Java
/* * 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/publicdomain/zero/1.0/ */ /* * Source: * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/extra/AtomicDoubleArray.java?revision=1.5 * (Modified to adapt to guava coding conventions and * to use AtomicLongArray instead of sun.misc.Unsafe) */ package com.google.common.util.concurrent; import static java.lang.Double.doubleToRawLongBits; import static java.lang.Double.longBitsToDouble; import java.util.concurrent.atomic.AtomicLongArray; /** * A {@code double} array in which elements may be updated atomically. * See the {@link java.util.concurrent.atomic} package specification * for description of the properties of atomic variables. * * <p><a name="bitEquals">This class compares primitive {@code double} * values in methods such as {@link #compareAndSet} by comparing their * bitwise representation using {@link Double#doubleToRawLongBits}, * which differs from both the primitive double {@code ==} operator * and from {@link Double#equals}, as if implemented by: * <pre> {@code * static boolean bitEquals(double x, double y) { * long xBits = Double.doubleToRawLongBits(x); * long yBits = Double.doubleToRawLongBits(y); * return xBits == yBits; * }}</pre> * * @author Doug Lea * @author Martin Buchholz * @since 11.0 */ public class AtomicDoubleArray implements java.io.Serializable { private static final long serialVersionUID = 0L; // Making this non-final is the lesser evil according to Effective // Java 2nd Edition Item 76: Write readObject methods defensively. private transient AtomicLongArray longs; /** * Creates a new {@code AtomicDoubleArray} of the given length, * with all elements initially zero. * * @param length the length of the array */ public AtomicDoubleArray(int length) { this.longs = new AtomicLongArray(length); } /** * Creates a new {@code AtomicDoubleArray} with the same length * as, and all elements copied from, the given array. * * @param array the array to copy elements from * @throws NullPointerException if array is null */ public AtomicDoubleArray(double[] array) { final int len = array.length; long[] longArray = new long[len]; for (int i = 0; i < len; i++) { longArray[i] = doubleToRawLongBits(array[i]); } this.longs = new AtomicLongArray(longArray); } /** * Returns the length of the array. * * @return the length of the array */ public final int length() { return longs.length(); } /** * Gets the current value at position {@code i}. * * @param i the index * @return the current value */ public final double get(int i) { return longBitsToDouble(longs.get(i)); } /** * Sets the element at position {@code i} to the given value. * * @param i the index * @param newValue the new value */ public final void set(int i, double newValue) { long next = doubleToRawLongBits(newValue); longs.set(i, next); } /** * Eventually sets the element at position {@code i} to the given value. * * @param i the index * @param newValue the new value */ public final void lazySet(int i, double newValue) { set(i, newValue); // TODO(user): replace with code below when jdk5 support is dropped. // long next = doubleToRawLongBits(newValue); // longs.lazySet(i, next); } /** * Atomically sets the element at position {@code i} to the given value * and returns the old value. * * @param i the index * @param newValue the new value * @return the previous value */ public final double getAndSet(int i, double newValue) { long next = doubleToRawLongBits(newValue); return longBitsToDouble(longs.getAndSet(i, next)); } /** * Atomically sets the element at position {@code i} to the given * updated value * if the current value is <a href="#bitEquals">bitwise equal</a> * to the expected value. * * @param i the index * @param expect the expected value * @param update the new value * @return true if successful. False return indicates that * the actual value was not equal to the expected value. */ public final boolean compareAndSet(int i, double expect, double update) { return longs.compareAndSet(i, doubleToRawLongBits(expect), doubleToRawLongBits(update)); } /** * Atomically sets the element at position {@code i} to the given * updated value * if the current value is <a href="#bitEquals">bitwise equal</a> * to the expected value. * * <p>May <a * href="http://download.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/package-summary.html#Spurious"> * fail spuriously</a> * and does not provide ordering guarantees, so is only rarely an * appropriate alternative to {@code compareAndSet}. * * @param i the index * @param expect the expected value * @param update the new value * @return true if successful */ public final boolean weakCompareAndSet(int i, double expect, double update) { return longs.weakCompareAndSet(i, doubleToRawLongBits(expect), doubleToRawLongBits(update)); } /** * Atomically adds the given value to the element at index {@code i}. * * @param i the index * @param delta the value to add * @return the previous value */ public final double getAndAdd(int i, double delta) { while (true) { long current = longs.get(i); double currentVal = longBitsToDouble(current); double nextVal = currentVal + delta; long next = doubleToRawLongBits(nextVal); if (longs.compareAndSet(i, current, next)) { return currentVal; } } } /** * Atomically adds the given value to the element at index {@code i}. * * @param i the index * @param delta the value to add * @return the updated value */ public double addAndGet(int i, double delta) { while (true) { long current = longs.get(i); double currentVal = longBitsToDouble(current); double nextVal = currentVal + delta; long next = doubleToRawLongBits(nextVal); if (longs.compareAndSet(i, current, next)) { return nextVal; } } } /** * Returns the String representation of the current values of array. * @return the String representation of the current values of array */ public String toString() { int iMax = length() - 1; if (iMax == -1) { return "[]"; } // Double.toString(Math.PI).length() == 17 StringBuilder b = new StringBuilder((17 + 2) * (iMax + 1)); b.append('['); for (int i = 0;; i++) { b.append(longBitsToDouble(longs.get(i))); if (i == iMax) { return b.append(']').toString(); } b.append(',').append(' '); } } /** * Saves the state to a stream (that is, serializes it). * * @serialData The length of the array is emitted (int), followed by all * of its elements (each a {@code double}) in the proper order. */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { s.defaultWriteObject(); // Write out array length int length = length(); s.writeInt(length); // Write out all elements in the proper order. for (int i = 0; i < length; i++) { s.writeDouble(get(i)); } } /** * Reconstitutes the instance from a stream (that is, deserializes it). */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); // Read in array length and allocate array int length = s.readInt(); this.longs = new AtomicLongArray(length); // Read in all elements in the proper order. for (int i = 0; i < length; i++) { set(i, s.readDouble()); } } }
Java
/* * Copyright (C) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.annotations.Beta; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; /** * Produces proxies that impose a time limit on method * calls to the proxied object. For example, to return the value of * {@code target.someMethod()}, but substitute {@code DEFAULT_VALUE} if this * method call takes over 50 ms, you can use this code: * <pre> * TimeLimiter limiter = . . .; * TargetType proxy = limiter.newProxy( * target, TargetType.class, 50, TimeUnit.MILLISECONDS); * try { * return proxy.someMethod(); * } catch (UncheckedTimeoutException e) { * return DEFAULT_VALUE; * } * </pre> * <p>Please see {@code SimpleTimeLimiterTest} for more usage examples. * * @author Kevin Bourrillion * @since 1.0 */ @Beta public interface TimeLimiter { /** * Returns an instance of {@code interfaceType} that delegates all method * calls to the {@code target} object, enforcing the specified time limit on * each call. This time-limited delegation is also performed for calls to * {@link Object#equals}, {@link Object#hashCode}, and * {@link Object#toString}. * <p> * If the target method call finishes before the limit is reached, the return * value or exception is propagated to the caller exactly as-is. If, on the * other hand, the time limit is reached, the proxy will attempt to abort the * call to the target, and will throw an {@link UncheckedTimeoutException} to * the caller. * <p> * It is important to note that the primary purpose of the proxy object is to * return control to the caller when the timeout elapses; aborting the target * method call is of secondary concern. The particular nature and strength * of the guarantees made by the proxy is implementation-dependent. However, * it is important that each of the methods on the target object behaves * appropriately when its thread is interrupted. * * @param target the object to proxy * @param interfaceType the interface you wish the returned proxy to * implement * @param timeoutDuration with timeoutUnit, the maximum length of time that * callers are willing to wait on each method call to the proxy * @param timeoutUnit with timeoutDuration, the maximum length of time that * callers are willing to wait on each method call to the proxy * @return a time-limiting proxy * @throws IllegalArgumentException if {@code interfaceType} is a regular * class, enum, or annotation type, rather than an interface */ <T> T newProxy(T target, Class<T> interfaceType, long timeoutDuration, TimeUnit timeoutUnit); /** * Invokes a specified Callable, timing out after the specified time limit. * If the target method call finished before the limit is reached, the return * value or exception is propagated to the caller exactly as-is. If, on the * other hand, the time limit is reached, we attempt to abort the call to the * target, and throw an {@link UncheckedTimeoutException} to the caller. * <p> * <b>Warning:</b> The future of this method is in doubt. It may be nuked, or * changed significantly. * * @param callable the Callable to execute * @param timeoutDuration with timeoutUnit, the maximum length of time to wait * @param timeoutUnit with timeoutDuration, the maximum length of time to wait * @param interruptible whether to respond to thread interruption by aborting * the operation and throwing InterruptedException; if false, the * operation is allowed to complete or time out, and the current thread's * interrupt status is re-asserted. * @return the result returned by the Callable * @throws InterruptedException if {@code interruptible} is true and our * thread is interrupted during execution * @throws UncheckedTimeoutException if the time limit is reached * @throws Exception */ <T> T callWithTimeout(Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit, boolean interruptible) throws Exception; }
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.util.concurrent; import com.google.common.base.Preconditions; import java.util.concurrent.Executor; /** * A {@link ListenableFuture} which forwards all its method calls to another * future. Subclasses should override one or more methods to modify the behavior * of the backing future as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p>Most subclasses can just use {@link SimpleForwardingListenableFuture}. * * @param <V> The result type returned by this Future's {@code get} method * * @author Shardul Deo * @since 4.0 */ public abstract class ForwardingListenableFuture<V> extends ForwardingFuture<V> implements ListenableFuture<V> { /** Constructor for use by subclasses. */ protected ForwardingListenableFuture() {} @Override protected abstract ListenableFuture<V> delegate(); @Override public void addListener(Runnable listener, Executor exec) { delegate().addListener(listener, exec); } /* * TODO(cpovirk): Use standard Javadoc form for SimpleForwarding* class and * constructor */ /** * A simplified version of {@link ForwardingListenableFuture} where subclasses * can pass in an already constructed {@link ListenableFuture} * as the delegate. * * @since 9.0 */ public abstract static class SimpleForwardingListenableFuture<V> extends ForwardingListenableFuture<V> { private final ListenableFuture<V> delegate; protected SimpleForwardingListenableFuture(ListenableFuture<V> delegate) { this.delegate = Preconditions.checkNotNull(delegate); } @Override protected final ListenableFuture<V> delegate() { return delegate; } } }
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.util.concurrent; import com.google.common.collect.ForwardingObject; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * An executor service which forwards all its method calls to another executor * service. Subclasses should override one or more methods to modify the * behavior of the backing executor service as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * @author Kurt Alfred Kluever * @since 10.0 */ public abstract class ForwardingExecutorService extends ForwardingObject implements ExecutorService { /** Constructor for use by subclasses. */ protected ForwardingExecutorService() {} @Override protected abstract ExecutorService delegate(); @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return delegate().awaitTermination(timeout, unit); } @Override public <T> List<Future<T>> invokeAll( Collection<? extends Callable<T>> tasks) throws InterruptedException { return delegate().invokeAll(tasks); } @Override public <T> List<Future<T>> invokeAll( Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { return delegate().invokeAll(tasks, timeout, unit); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { return delegate().invokeAny(tasks); } @Override public <T> T invokeAny( Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return delegate().invokeAny(tasks, timeout, unit); } @Override public boolean isShutdown() { return delegate().isShutdown(); } @Override public boolean isTerminated() { return delegate().isTerminated(); } @Override public void shutdown() { delegate().shutdown(); } @Override public List<Runnable> shutdownNow() { return delegate().shutdownNow(); } @Override public void execute(Runnable command) { delegate().execute(command); } public <T> Future<T> submit(Callable<T> task) { return delegate().submit(task); } @Override public Future<?> submit(Runnable task) { return delegate().submit(task); } @Override public <T> Future<T> submit(Runnable task, T result) { return delegate().submit(task, result); } }
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.util.concurrent; import static com.google.common.base.Objects.firstNonNull; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.collect.Iterables; import com.google.common.collect.MapMaker; import com.google.common.math.IntMath; import com.google.common.primitives.Ints; import java.math.RoundingMode; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * A striped {@code Lock/Semaphore/ReadWriteLock}. This offers the underlying lock striping * similar to that of {@code ConcurrentHashMap} in a reusable form, and extends it for * semaphores and read-write locks. Conceptually, lock striping is the technique of dividing a lock * into many <i>stripes</i>, increasing the granularity of a single lock and allowing independent * operations to lock different stripes and proceed concurrently, instead of creating contention * for a single lock. * * <p>The guarantee provided by this class is that equal keys lead to the same lock (or semaphore), * i.e. {@code if (key1.equals(key2))} then {@code striped.get(key1) == striped.get(key2)} * (assuming {@link Object#hashCode()} is correctly implemented for the keys). Note * that if {@code key1} is <strong>not</strong> equal to {@code key2}, it is <strong>not</strong> * guaranteed that {@code striped.get(key1) != striped.get(key2)}; the elements might nevertheless * be mapped to the same lock. The lower the number of stripes, the higher the probability of this * happening. * * <p>There are three flavors of this class: {@code Striped<Lock>}, {@code Striped<Semaphore>}, * and {@code Striped<ReadWriteLock>}. For each type, two implementations are offered: * {@linkplain #lock(int) strong} and {@linkplain #lazyWeakLock(int) weak} * {@code Striped<Lock>}, {@linkplain #semaphore(int, int) strong} and {@linkplain * #lazyWeakSemaphore(int, int) weak} {@code Striped<Semaphore>}, and {@linkplain * #readWriteLock(int) strong} and {@linkplain #lazyWeakReadWriteLock(int) weak} * {@code Striped<ReadWriteLock>}. <i>Strong</i> means that all stripes (locks/semaphores) are * initialized eagerly, and are not reclaimed unless {@code Striped} itself is reclaimable. * <i>Weak</i> means that locks/semaphores are created lazily, and they are allowed to be reclaimed * if nobody is holding on to them. This is useful, for example, if one wants to create a {@code * Striped<Lock>} of many locks, but worries that in most cases only a small portion of these * would be in use. * * <p>Prior to this class, one might be tempted to use {@code Map<K, Lock>}, where {@code K} * represents the task. This maximizes concurrency by having each unique key mapped to a unique * lock, but also maximizes memory footprint. On the other extreme, one could use a single lock * for all tasks, which minimizes memory footprint but also minimizes concurrency. Instead of * choosing either of these extremes, {@code Striped} allows the user to trade between required * concurrency and memory footprint. For example, if a set of tasks are CPU-bound, one could easily * create a very compact {@code Striped<Lock>} of {@code availableProcessors() * 4} stripes, * instead of possibly thousands of locks which could be created in a {@code Map<K, Lock>} * structure. * * @author Dimitris Andreou * @since 13.0 */ @Beta public abstract class Striped<L> { private Striped() {} /** * Returns the stripe that corresponds to the passed key. It is always guaranteed that if * {@code key1.equals(key2)}, then {@code get(key1) == get(key2)}. * * @param key an arbitrary, non-null key * @return the stripe that the passed key corresponds to */ public abstract L get(Object key); /** * Returns the stripe at the specified index. Valid indexes are 0, inclusively, to * {@code size()}, exclusively. * * @param index the index of the stripe to return; must be in {@code [0...size())} * @return the stripe at the specified index */ public abstract L getAt(int index); /** * Returns the index to which the given key is mapped, so that getAt(indexFor(key)) == get(key). */ abstract int indexFor(Object key); /** * Returns the total number of stripes in this instance. */ public abstract int size(); /** * Returns the stripes that correspond to the passed objects, in ascending (as per * {@link #getAt(int)}) order. Thus, threads that use the stripes in the order returned * by this method are guaranteed to not deadlock each other. * * <p>It should be noted that using a {@code Striped<L>} with relatively few stripes, and * {@code bulkGet(keys)} with a relative large number of keys can cause an excessive number * of shared stripes (much like the birthday paradox, where much fewer than anticipated birthdays * are needed for a pair of them to match). Please consider carefully the implications of the * number of stripes, the intended concurrency level, and the typical number of keys used in a * {@code bulkGet(keys)} operation. See <a href="http://www.mathpages.com/home/kmath199.htm">Balls * in Bins model</a> for mathematical formulas that can be used to estimate the probability of * collisions. * * @param keys arbitrary non-null keys * @return the stripes corresponding to the objects (one per each object, derived by delegating * to {@link #get(Object)}; may contain duplicates), in an increasing index order. */ public Iterable<L> bulkGet(Iterable<?> keys) { // Initially using the array to store the keys, then reusing it to store the respective L's final Object[] array = Iterables.toArray(keys, Object.class); int[] stripes = new int[array.length]; for (int i = 0; i < array.length; i++) { stripes[i] = indexFor(array[i]); } Arrays.sort(stripes); for (int i = 0; i < array.length; i++) { array[i] = getAt(stripes[i]); } /* * Note that the returned Iterable holds references to the returned stripes, to avoid * error-prone code like: * * Striped<Lock> stripedLock = Striped.lazyWeakXXX(...)' * Iterable<Lock> locks = stripedLock.bulkGet(keys); * for (Lock lock : locks) { * lock.lock(); * } * operation(); * for (Lock lock : locks) { * lock.unlock(); * } * * If we only held the int[] stripes, translating it on the fly to L's, the original locks * might be garbage collected after locking them, ending up in a huge mess. */ @SuppressWarnings("unchecked") // we carefully replaced all keys with their respective L's List<L> asList = (List<L>) Arrays.asList(array); return Collections.unmodifiableList(asList); } // Static factories /** * Creates a {@code Striped<Lock>} with eagerly initialized, strongly referenced locks. * Every lock is reentrant. * * @param stripes the minimum number of stripes (locks) required * @return a new {@code Striped<Lock>} */ public static Striped<Lock> lock(int stripes) { return new CompactStriped<Lock>(stripes, new Supplier<Lock>() { public Lock get() { return new PaddedLock(); } }); } /** * Creates a {@code Striped<Lock>} with lazily initialized, weakly referenced locks. * Every lock is reentrant. * * @param stripes the minimum number of stripes (locks) required * @return a new {@code Striped<Lock>} */ public static Striped<Lock> lazyWeakLock(int stripes) { return new LazyStriped<Lock>(stripes, new Supplier<Lock>() { public Lock get() { return new ReentrantLock(false); } }); } /** * Creates a {@code Striped<Semaphore>} with eagerly initialized, strongly referenced semaphores, * with the specified number of permits. * * @param stripes the minimum number of stripes (semaphores) required * @param permits the number of permits in each semaphore * @return a new {@code Striped<Semaphore>} */ public static Striped<Semaphore> semaphore(int stripes, final int permits) { return new CompactStriped<Semaphore>(stripes, new Supplier<Semaphore>() { public Semaphore get() { return new PaddedSemaphore(permits); } }); } /** * Creates a {@code Striped<Semaphore>} with lazily initialized, weakly referenced semaphores, * with the specified number of permits. * * @param stripes the minimum number of stripes (semaphores) required * @param permits the number of permits in each semaphore * @return a new {@code Striped<Semaphore>} */ public static Striped<Semaphore> lazyWeakSemaphore(int stripes, final int permits) { return new LazyStriped<Semaphore>(stripes, new Supplier<Semaphore>() { public Semaphore get() { return new Semaphore(permits, false); } }); } /** * Creates a {@code Striped<ReadWriteLock>} with eagerly initialized, strongly referenced * read-write locks. Every lock is reentrant. * * @param stripes the minimum number of stripes (locks) required * @return a new {@code Striped<ReadWriteLock>} */ public static Striped<ReadWriteLock> readWriteLock(int stripes) { return new CompactStriped<ReadWriteLock>(stripes, READ_WRITE_LOCK_SUPPLIER); } /** * Creates a {@code Striped<ReadWriteLock>} with lazily initialized, weakly referenced * read-write locks. Every lock is reentrant. * * @param stripes the minimum number of stripes (locks) required * @return a new {@code Striped<ReadWriteLock>} */ public static Striped<ReadWriteLock> lazyWeakReadWriteLock(int stripes) { return new LazyStriped<ReadWriteLock>(stripes, READ_WRITE_LOCK_SUPPLIER); } // ReentrantReadWriteLock is large enough to make padding probably unnecessary private static final Supplier<ReadWriteLock> READ_WRITE_LOCK_SUPPLIER = new Supplier<ReadWriteLock>() { public ReadWriteLock get() { return new ReentrantReadWriteLock(); } }; private abstract static class PowerOfTwoStriped<L> extends Striped<L> { /** Capacity (power of two) minus one, for fast mod evaluation */ final int mask; PowerOfTwoStriped(int stripes) { Preconditions.checkArgument(stripes > 0, "Stripes must be positive"); this.mask = stripes > Ints.MAX_POWER_OF_TWO ? ALL_SET : ceilToPowerOfTwo(stripes) - 1; } @Override final int indexFor(Object key) { int hash = smear(key.hashCode()); return hash & mask; } @Override public final L get(Object key) { return getAt(indexFor(key)); } } /** * Implementation of Striped where 2^k stripes are represented as an array of the same length, * eagerly initialized. */ private static class CompactStriped<L> extends PowerOfTwoStriped<L> { /** Size is a power of two. */ private final Object[] array; private CompactStriped(int stripes, Supplier<L> supplier) { super(stripes); Preconditions.checkArgument(stripes <= Ints.MAX_POWER_OF_TWO, "Stripes must be <= 2^30)"); this.array = new Object[mask + 1]; for (int i = 0; i < array.length; i++) { array[i] = supplier.get(); } } @SuppressWarnings("unchecked") // we only put L's in the array @Override public L getAt(int index) { return (L) array[index]; } @Override public int size() { return array.length; } } /** * Implementation of Striped where up to 2^k stripes can be represented, using a Cache * where the key domain is [0..2^k). To map a user key into a stripe, we take a k-bit slice of the * user key's (smeared) hashCode(). The stripes are lazily initialized and are weakly referenced. */ private static class LazyStriped<L> extends PowerOfTwoStriped<L> { final ConcurrentMap<Integer, L> locks; final Supplier<L> supplier; final int size; LazyStriped(int stripes, Supplier<L> supplier) { super(stripes); this.size = (mask == ALL_SET) ? Integer.MAX_VALUE : mask + 1; this.supplier = supplier; this.locks = new MapMaker().weakValues().makeMap(); } @Override public L getAt(int index) { if (size != Integer.MAX_VALUE) { Preconditions.checkElementIndex(index, size()); } // else no check necessary, all index values are valid L existing = locks.get(index); if (existing != null) { return existing; } L created = supplier.get(); existing = locks.putIfAbsent(index, created); return firstNonNull(existing, created); } @Override public int size() { return size; } } /** * A bit mask were all bits are set. */ private static final int ALL_SET = ~0; private static int ceilToPowerOfTwo(int x) { return 1 << IntMath.log2(x, RoundingMode.CEILING); } /* * This method was 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 * * As of 2010/06/11, this method is identical to the (package private) hash * method in OpenJDK 7's java.util.HashMap class. */ // Copied from java/com/google/common/collect/Hashing.java private static int smear(int hashCode) { hashCode ^= (hashCode >>> 20) ^ (hashCode >>> 12); return hashCode ^ (hashCode >>> 7) ^ (hashCode >>> 4); } private static class PaddedLock extends ReentrantLock { /* * Padding from 40 into 64 bytes, same size as cache line. Might be beneficial to add * a fourth long here, to minimize chance of interference between consecutive locks, * but I couldn't observe any benefit from that. */ @SuppressWarnings("unused") long q1, q2, q3; PaddedLock() { super(false); } } private static class PaddedSemaphore extends Semaphore { // See PaddedReentrantLock comment @SuppressWarnings("unused") long q1, q2, q3; PaddedSemaphore(int permits) { super(permits, 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.util.concurrent; import static java.util.concurrent.TimeUnit.NANOSECONDS; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Utilities for treating interruptible operations as uninterruptible. * In all cases, if a thread is interrupted during such a call, the call * continues to block until the result is available or the timeout elapses, * and only then re-interrupts the thread. * * @author Anthony Zana * @since 10.0 */ @Beta public final class Uninterruptibles { // Implementation Note: As of 3-7-11, the logic for each blocking/timeout // methods is identical, save for method being invoked. /** * Invokes {@code latch.}{@link CountDownLatch#await() await()} * uninterruptibly. */ public static void awaitUninterruptibly(CountDownLatch latch) { boolean interrupted = false; try { while (true) { try { latch.await(); return; } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Invokes * {@code latch.}{@link CountDownLatch#await(long, TimeUnit) * await(timeout, unit)} uninterruptibly. */ public static boolean awaitUninterruptibly(CountDownLatch latch, long timeout, TimeUnit unit) { boolean interrupted = false; try { long remainingNanos = unit.toNanos(timeout); long end = System.nanoTime() + remainingNanos; while (true) { try { // CountDownLatch treats negative timeouts just like zero. return latch.await(remainingNanos, NANOSECONDS); } catch (InterruptedException e) { interrupted = true; remainingNanos = end - System.nanoTime(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Invokes {@code toJoin.}{@link Thread#join() join()} uninterruptibly. */ public static void joinUninterruptibly(Thread toJoin) { boolean interrupted = false; try { while (true) { try { toJoin.join(); return; } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Invokes {@code future.}{@link Future#get() get()} uninterruptibly. * To get uninterruptibility and remove checked exceptions, see * {@link Futures#getUnchecked}. * * <p>If instead, you wish to treat {@link InterruptedException} uniformly * with other exceptions, see {@link Futures#get(Future, Class) Futures.get} * or {@link Futures#makeChecked}. * * @throws ExecutionException if the computation threw an exception * @throws CancellationException if the computation was cancelled */ public static <V> V getUninterruptibly(Future<V> future) throws ExecutionException { boolean interrupted = false; try { while (true) { try { return future.get(); } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Invokes * {@code future.}{@link Future#get(long, TimeUnit) get(timeout, unit)} * uninterruptibly. * * <p>If instead, you wish to treat {@link InterruptedException} uniformly * with other exceptions, see {@link Futures#get(Future, Class) Futures.get} * or {@link Futures#makeChecked}. * * @throws ExecutionException if the computation threw an exception * @throws CancellationException if the computation was cancelled * @throws TimeoutException if the wait timed out */ public static <V> V getUninterruptibly( Future<V> future, long timeout, TimeUnit unit) throws ExecutionException, TimeoutException { boolean interrupted = false; try { long remainingNanos = unit.toNanos(timeout); long end = System.nanoTime() + remainingNanos; while (true) { try { // Future treats negative timeouts just like zero. return future.get(remainingNanos, NANOSECONDS); } catch (InterruptedException e) { interrupted = true; remainingNanos = end - System.nanoTime(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Invokes * {@code unit.}{@link TimeUnit#timedJoin(Thread, long) * timedJoin(toJoin, timeout)} uninterruptibly. */ public static void joinUninterruptibly(Thread toJoin, long timeout, TimeUnit unit) { Preconditions.checkNotNull(toJoin); boolean interrupted = false; try { long remainingNanos = unit.toNanos(timeout); long end = System.nanoTime() + remainingNanos; while (true) { try { // TimeUnit.timedJoin() treats negative timeouts just like zero. NANOSECONDS.timedJoin(toJoin, remainingNanos); return; } catch (InterruptedException e) { interrupted = true; remainingNanos = end - System.nanoTime(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Invokes {@code queue.}{@link BlockingQueue#take() take()} uninterruptibly. */ public static <E> E takeUninterruptibly(BlockingQueue<E> queue) { boolean interrupted = false; try { while (true) { try { return queue.take(); } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Invokes {@code queue.}{@link BlockingQueue#put(Object) put(element)} * uninterruptibly. * * @throws ClassCastException if the class of the specified element prevents * it from being added to the given queue * @throws IllegalArgumentException if some property of the specified element * prevents it from being added to the given queue */ public static <E> void putUninterruptibly(BlockingQueue<E> queue, E element) { boolean interrupted = false; try { while (true) { try { queue.put(element); return; } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } // TODO(user): Support Sleeper somehow (wrapper or interface method)? /** * Invokes {@code unit.}{@link TimeUnit#sleep(long) sleep(sleepFor)} * uninterruptibly. */ public static void sleepUninterruptibly(long sleepFor, TimeUnit unit) { boolean interrupted = false; try { long remainingNanos = unit.toNanos(sleepFor); long end = System.nanoTime() + remainingNanos; while (true) { try { // TimeUnit.sleep() treats negative timeouts just like zero. NANOSECONDS.sleep(remainingNanos); return; } catch (InterruptedException e) { interrupted = true; remainingNanos = end - System.nanoTime(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } // TODO(user): Add support for waitUninterruptibly. private Uninterruptibles() {} }
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.util.concurrent; import static com.google.common.base.Preconditions.checkNotNull; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.AbstractQueuedSynchronizer; import javax.annotation.Nullable; /** * An abstract implementation of the {@link ListenableFuture} interface. This * class is preferable to {@link java.util.concurrent.FutureTask} for two * reasons: It implements {@code ListenableFuture}, and it does not implement * {@code Runnable}. (If you want a {@code Runnable} implementation of {@code * ListenableFuture}, create a {@link ListenableFutureTask}, or submit your * tasks to a {@link ListeningExecutorService}.) * * <p>This class implements all methods in {@code ListenableFuture}. * Subclasses should provide a way to set the result of the computation through * the protected methods {@link #set(Object)} and * {@link #setException(Throwable)}. Subclasses may also override {@link * #interruptTask()}, which will be invoked automatically if a call to {@link * #cancel(boolean) cancel(true)} succeeds in canceling the future. * * <p>{@code AbstractFuture} uses an {@link AbstractQueuedSynchronizer} to deal * with concurrency issues and guarantee thread safety. * * <p>The state changing methods all return a boolean indicating success or * failure in changing the future's state. Valid states are running, * completed, failed, or cancelled. * * <p>This class uses an {@link ExecutionList} to guarantee that all registered * listeners will be executed, either when the future finishes or, for listeners * that are added after the future completes, immediately. * {@code Runnable}-{@code Executor} pairs are stored in the execution list but * are not necessarily executed in the order in which they were added. (If a * listener is added after the Future is complete, it will be executed * immediately, even if earlier listeners have not been executed. Additionally, * executors need not guarantee FIFO execution, or different listeners may run * in different executors.) * * @author Sven Mawson * @since 1.0 */ public abstract class AbstractFuture<V> implements ListenableFuture<V> { /** Synchronization control for AbstractFutures. */ private final Sync<V> sync = new Sync<V>(); // The execution list to hold our executors. private final ExecutionList executionList = new ExecutionList(); /** * Constructor for use by subclasses. */ protected AbstractFuture() {} /* * Improve the documentation of when InterruptedException is thrown. Our * behavior matches the JDK's, but the JDK's documentation is misleading. */ /** * {@inheritDoc} * * <p>The default {@link AbstractFuture} implementation throws {@code * InterruptedException} if the current thread is interrupted before or during * the call, even if the value is already available. * * @throws InterruptedException if the current thread was interrupted before * or during the call (optional but recommended). * @throws CancellationException {@inheritDoc} */ @Override public V get(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException, ExecutionException { return sync.get(unit.toNanos(timeout)); } /* * Improve the documentation of when InterruptedException is thrown. Our * behavior matches the JDK's, but the JDK's documentation is misleading. */ /** * {@inheritDoc} * * <p>The default {@link AbstractFuture} implementation throws {@code * InterruptedException} if the current thread is interrupted before or during * the call, even if the value is already available. * * @throws InterruptedException if the current thread was interrupted before * or during the call (optional but recommended). * @throws CancellationException {@inheritDoc} */ @Override public V get() throws InterruptedException, ExecutionException { return sync.get(); } @Override public boolean isDone() { return sync.isDone(); } @Override public boolean isCancelled() { return sync.isCancelled(); } @Override public boolean cancel(boolean mayInterruptIfRunning) { if (!sync.cancel(mayInterruptIfRunning)) { return false; } executionList.execute(); if (mayInterruptIfRunning) { interruptTask(); } return true; } /** * Subclasses can override this method to implement interruption of the * future's computation. The method is invoked automatically by a successful * call to {@link #cancel(boolean) cancel(true)}. * * <p>The default implementation does nothing. * * @since 10.0 */ protected void interruptTask() { } /** * Returns true if this future was cancelled with {@code * mayInterruptIfRunning} set to {@code true}. * * @since 14.0 */ protected final boolean wasInterrupted() { return sync.wasInterrupted(); } /** * {@inheritDoc} * * @since 10.0 */ @Override public void addListener(Runnable listener, Executor exec) { executionList.add(listener, exec); } /** * Subclasses should invoke this method to set the result of the computation * to {@code value}. This will set the state of the future to * {@link AbstractFuture.Sync#COMPLETED} and invoke the listeners if the * state was successfully changed. * * @param value the value that was the result of the task. * @return true if the state was successfully changed. */ protected boolean set(@Nullable V value) { boolean result = sync.set(value); if (result) { executionList.execute(); } return result; } /** * Subclasses should invoke this method to set the result of the computation * to an error, {@code throwable}. This will set the state of the future to * {@link AbstractFuture.Sync#COMPLETED} and invoke the listeners if the * state was successfully changed. * * @param throwable the exception that the task failed with. * @return true if the state was successfully changed. */ protected boolean setException(Throwable throwable) { boolean result = sync.setException(checkNotNull(throwable)); if (result) { executionList.execute(); } return result; } /** * <p>Following the contract of {@link AbstractQueuedSynchronizer} we create a * private subclass to hold the synchronizer. This synchronizer is used to * implement the blocking and waiting calls as well as to handle state changes * in a thread-safe manner. The current state of the future is held in the * Sync state, and the lock is released whenever the state changes to * {@link #COMPLETED}, {@link #CANCELLED}, or {@link #INTERRUPTED} * * <p>To avoid races between threads doing release and acquire, we transition * to the final state in two steps. One thread will successfully CAS from * RUNNING to COMPLETING, that thread will then set the result of the * computation, and only then transition to COMPLETED, CANCELLED, or * INTERRUPTED. * * <p>We don't use the integer argument passed between acquire methods so we * pass around a -1 everywhere. */ static final class Sync<V> extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 0L; /* Valid states. */ static final int RUNNING = 0; static final int COMPLETING = 1; static final int COMPLETED = 2; static final int CANCELLED = 4; static final int INTERRUPTED = 8; private V value; private Throwable exception; /* * Acquisition succeeds if the future is done, otherwise it fails. */ @Override protected int tryAcquireShared(int ignored) { if (isDone()) { return 1; } return -1; } /* * We always allow a release to go through, this means the state has been * successfully changed and the result is available. */ @Override protected boolean tryReleaseShared(int finalState) { setState(finalState); return true; } /** * Blocks until the task is complete or the timeout expires. Throws a * {@link TimeoutException} if the timer expires, otherwise behaves like * {@link #get()}. */ V get(long nanos) throws TimeoutException, CancellationException, ExecutionException, InterruptedException { // Attempt to acquire the shared lock with a timeout. if (!tryAcquireSharedNanos(-1, nanos)) { throw new TimeoutException("Timeout waiting for task."); } return getValue(); } /** * Blocks until {@link #complete(Object, Throwable, int)} has been * successfully called. Throws a {@link CancellationException} if the task * was cancelled, or a {@link ExecutionException} if the task completed with * an error. */ V get() throws CancellationException, ExecutionException, InterruptedException { // Acquire the shared lock allowing interruption. acquireSharedInterruptibly(-1); return getValue(); } /** * Implementation of the actual value retrieval. Will return the value * on success, an exception on failure, a cancellation on cancellation, or * an illegal state if the synchronizer is in an invalid state. */ private V getValue() throws CancellationException, ExecutionException { int state = getState(); switch (state) { case COMPLETED: if (exception != null) { throw new ExecutionException(exception); } else { return value; } case CANCELLED: case INTERRUPTED: throw cancellationExceptionWithCause( "Task was cancelled.", exception); default: throw new IllegalStateException( "Error, synchronizer in invalid state: " + state); } } /** * Checks if the state is {@link #COMPLETED}, {@link #CANCELLED}, or {@link * INTERRUPTED}. */ boolean isDone() { return (getState() & (COMPLETED | CANCELLED | INTERRUPTED)) != 0; } /** * Checks if the state is {@link #CANCELLED} or {@link #INTERRUPTED}. */ boolean isCancelled() { return (getState() & (CANCELLED | INTERRUPTED)) != 0; } /** * Checks if the state is {@link #INTERRUPTED}. */ boolean wasInterrupted() { return getState() == INTERRUPTED; } /** * Transition to the COMPLETED state and set the value. */ boolean set(@Nullable V v) { return complete(v, null, COMPLETED); } /** * Transition to the COMPLETED state and set the exception. */ boolean setException(Throwable t) { return complete(null, t, COMPLETED); } /** * Transition to the CANCELLED or INTERRUPTED state. */ boolean cancel(boolean interrupt) { return complete(null, null, interrupt ? INTERRUPTED : CANCELLED); } /** * Implementation of completing a task. Either {@code v} or {@code t} will * be set but not both. The {@code finalState} is the state to change to * from {@link #RUNNING}. If the state is not in the RUNNING state we * return {@code false} after waiting for the state to be set to a valid * final state ({@link #COMPLETED}, {@link #CANCELLED}, or {@link * #INTERRUPTED}). * * @param v the value to set as the result of the computation. * @param t the exception to set as the result of the computation. * @param finalState the state to transition to. */ private boolean complete(@Nullable V v, @Nullable Throwable t, int finalState) { boolean doCompletion = compareAndSetState(RUNNING, COMPLETING); if (doCompletion) { // If this thread successfully transitioned to COMPLETING, set the value // and exception and then release to the final state. this.value = v; // Don't actually construct a CancellationException until necessary. this.exception = ((finalState & (CANCELLED | INTERRUPTED)) != 0) ? new CancellationException("Future.cancel() was called.") : t; releaseShared(finalState); } else if (getState() == COMPLETING) { // If some other thread is currently completing the future, block until // they are done so we can guarantee completion. acquireShared(-1); } return doCompletion; } } static final CancellationException cancellationExceptionWithCause( @Nullable String message, @Nullable Throwable cause) { CancellationException exception = new CancellationException(message); exception.initCause(cause); return exception; } }
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.util.concurrent; import com.google.common.annotations.Beta; import com.google.common.collect.ForwardingObject; import java.util.concurrent.Executor; /** * A {@link Service} that forwards all method calls to another service. * * @deprecated Instead of using a {@link ForwardingService}, consider using the * {@link Service.Listener} functionality to hook into the {@link Service} * lifecycle, or if you really do need to provide access to some Service * methods, consider just providing the few that you actually need (e.g. just * {@link #startAndWait()}) and not implementing Service. * * @author Chris Nokleberg * @since 1.0 */ @Beta @Deprecated public abstract class ForwardingService extends ForwardingObject implements Service { /** Constructor for use by subclasses. */ protected ForwardingService() {} @Override protected abstract Service delegate(); @Override public ListenableFuture<State> start() { return delegate().start(); } @Override public State state() { return delegate().state(); } @Override public ListenableFuture<State> stop() { return delegate().stop(); } @Override public State startAndWait() { return delegate().startAndWait(); } @Override public State stopAndWait() { return delegate().stopAndWait(); } @Override public boolean isRunning() { return delegate().isRunning(); } /** * @since 13.0 */ @Override public void addListener(Listener listener, Executor executor) { delegate().addListener(listener, executor); } /** * @since 14.0 */ @Override public Throwable failureCause() { return delegate().failureCause(); } /** * A sensible default implementation of {@link #startAndWait()}, in terms of * {@link #start}. If you override {@link #start}, you may wish to override * {@link #startAndWait()} to forward to this implementation. * @since 9.0 */ protected State standardStartAndWait() { return Futures.getUnchecked(start()); } /** * A sensible default implementation of {@link #stopAndWait()}, in terms of * {@link #stop}. If you override {@link #stop}, you may wish to override * {@link #stopAndWait()} to forward to this implementation. * @since 9.0 */ protected State standardStopAndWait() { return Futures.getUnchecked(stop()); } }
Java