code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * 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.util.Collection; import java.util.Comparator; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import javax.annotation.Nullable; /** * Implementation of {@code Multimap} whose keys and values are ordered by * their natural ordering or by supplied comparators. In all cases, this * implementation uses {@link Comparable#compareTo} or {@link * Comparator#compare} instead of {@link Object#equals} to determine * equivalence of instances. * * <p><b>Warning:</b> The comparators or comparables used must be <i>consistent * with equals</i> as explained by the {@link Comparable} class specification. * Otherwise, the resulting multiset will violate the general contract of {@link * SetMultimap}, which it is specified in terms of {@link Object#equals}. * * <p>The collections returned by {@code keySet} and {@code asMap} iterate * through the keys according to the key comparator ordering or the natural * ordering of the keys. Similarly, {@code get}, {@code removeAll}, and {@code * replaceValues} return collections that iterate through the values according * to the value comparator ordering or the natural ordering of the values. The * collections generated by {@code entries}, {@code keys}, and {@code values} * iterate across the keys according to the above key ordering, and for each * key they iterate across the values according to the value ordering. * * <p>The multimap does not store duplicate key-value pairs. Adding a new * key-value pair equal to an existing key-value pair has no effect. * * <p>Null keys and values are permitted (provided, of course, that the * respective comparators support them). All optional multimap methods are * supported, and all returned views are modifiable. * * <p>This class is not threadsafe when any concurrent operations update the * multimap. Concurrent read operations will work correctly. To allow concurrent * update operations, wrap your multimap with a call to {@link * Multimaps#synchronizedSortedSetMultimap}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap"> * {@code Multimap}</a>. * * @author Jared Levy * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public class TreeMultimap<K, V> extends AbstractSortedKeySortedSetMultimap<K, V> { private transient Comparator<? super K> keyComparator; private transient Comparator<? super V> valueComparator; /** * Creates an empty {@code TreeMultimap} ordered by the natural ordering of * its keys and values. */ public static <K extends Comparable, V extends Comparable> TreeMultimap<K, V> create() { return new TreeMultimap<K, V>(Ordering.natural(), Ordering.natural()); } /** * Creates an empty {@code TreeMultimap} instance using explicit comparators. * Neither comparator may be null; use {@link Ordering#natural()} to specify * natural order. * * @param keyComparator the comparator that determines the key ordering * @param valueComparator the comparator that determines the value ordering */ public static <K, V> TreeMultimap<K, V> create( Comparator<? super K> keyComparator, Comparator<? super V> valueComparator) { return new TreeMultimap<K, V>(checkNotNull(keyComparator), checkNotNull(valueComparator)); } /** * Constructs a {@code TreeMultimap}, ordered by the natural ordering of its * keys and values, with the same mappings as the specified multimap. * * @param multimap the multimap whose contents are copied to this multimap */ public static <K extends Comparable, V extends Comparable> TreeMultimap<K, V> create(Multimap<? extends K, ? extends V> multimap) { return new TreeMultimap<K, V>(Ordering.natural(), Ordering.natural(), multimap); } TreeMultimap(Comparator<? super K> keyComparator, Comparator<? super V> valueComparator) { super(new TreeMap<K, Collection<V>>(keyComparator)); this.keyComparator = keyComparator; this.valueComparator = valueComparator; } private TreeMultimap(Comparator<? super K> keyComparator, Comparator<? super V> valueComparator, Multimap<? extends K, ? extends V> multimap) { this(keyComparator, valueComparator); putAll(multimap); } /** * {@inheritDoc} * * <p>Creates an empty {@code TreeSet} for a collection of values for one key. * * @return a new {@code TreeSet} containing a collection of values for one * key */ @Override SortedSet<V> createCollection() { return new TreeSet<V>(valueComparator); } @Override Collection<V> createCollection(@Nullable K key) { if (key == null) { keyComparator().compare(key, key); } return super.createCollection(key); } /** * Returns the comparator that orders the multimap keys. */ public Comparator<? super K> keyComparator() { return keyComparator; } @Override public Comparator<? super V> valueComparator() { return valueComparator; } /* * The following @GwtIncompatible methods override the methods in * AbstractSortedKeySortedSetMultimap, so GWT will fall back to the ASKSSM implementations, * which return SortedSets and SortedMaps. */ }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/TreeMultimap.java
Java
asf20
6,128
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.Collections.singletonList; import java.util.List; /** * GWT emulated version of {@link SingletonImmutableList}. * * @author Hayward Chan */ final class SingletonImmutableList<E> extends ForwardingImmutableList<E> { final transient List<E> delegate; // This reference is used both by the custom field serializer, and by the // GWT compiler to infer the elements of the lists that needs to be // serialized. E element; SingletonImmutableList(E element) { this.delegate = singletonList(checkNotNull(element)); this.element = element; } @Override List<E> delegateList() { return delegate; } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/SingletonImmutableList.java
Java
asf20
1,355
/* * 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.collect.CollectPreconditions.checkRemove; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Predicate; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Queue; import java.util.RandomAccess; import java.util.Set; import javax.annotation.Nullable; /** * This class contains static utility methods that operate on or return objects * of type {@code Iterable}. Except as noted, each method has a corresponding * {@link Iterator}-based method in the {@link Iterators} class. * * <p><i>Performance notes:</i> Unless otherwise noted, all of the iterables * produced in this class are <i>lazy</i>, which means that their iterators * only advance the backing iteration when absolutely necessary. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Iterables"> * {@code Iterables}</a>. * * @author Kevin Bourrillion * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class Iterables { private Iterables() {} /** Returns an unmodifiable view of {@code iterable}. */ public static <T> Iterable<T> unmodifiableIterable( final Iterable<T> iterable) { checkNotNull(iterable); if (iterable instanceof UnmodifiableIterable || iterable instanceof ImmutableCollection) { return iterable; } return new UnmodifiableIterable<T>(iterable); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <E> Iterable<E> unmodifiableIterable( ImmutableCollection<E> iterable) { return checkNotNull(iterable); } private static final class UnmodifiableIterable<T> extends FluentIterable<T> { private final Iterable<T> iterable; private UnmodifiableIterable(Iterable<T> iterable) { this.iterable = iterable; } @Override public Iterator<T> iterator() { return Iterators.unmodifiableIterator(iterable.iterator()); } @Override public String toString() { return iterable.toString(); } // no equals and hashCode; it would break the contract! } /** * Returns the number of elements in {@code iterable}. */ public static int size(Iterable<?> iterable) { return (iterable instanceof Collection) ? ((Collection<?>) iterable).size() : Iterators.size(iterable.iterator()); } /** * Returns {@code true} if {@code iterable} contains any object for which {@code equals(element)} * is true. */ public static boolean contains(Iterable<?> iterable, @Nullable Object element) { if (iterable instanceof Collection) { Collection<?> collection = (Collection<?>) iterable; return Collections2.safeContains(collection, element); } return Iterators.contains(iterable.iterator(), element); } /** * Removes, from an iterable, every element that belongs to the provided * collection. * * <p>This method calls {@link Collection#removeAll} if {@code iterable} is a * collection, and {@link Iterators#removeAll} otherwise. * * @param removeFrom the iterable to (potentially) remove elements from * @param elementsToRemove the elements to remove * @return {@code true} if any element was removed from {@code iterable} */ public static boolean removeAll( Iterable<?> removeFrom, Collection<?> elementsToRemove) { return (removeFrom instanceof Collection) ? ((Collection<?>) removeFrom).removeAll(checkNotNull(elementsToRemove)) : Iterators.removeAll(removeFrom.iterator(), elementsToRemove); } /** * Removes, from an iterable, every element that does not belong to the * provided collection. * * <p>This method calls {@link Collection#retainAll} if {@code iterable} is a * collection, and {@link Iterators#retainAll} otherwise. * * @param removeFrom the iterable to (potentially) remove elements from * @param elementsToRetain the elements to retain * @return {@code true} if any element was removed from {@code iterable} */ public static boolean retainAll( Iterable<?> removeFrom, Collection<?> elementsToRetain) { return (removeFrom instanceof Collection) ? ((Collection<?>) removeFrom).retainAll(checkNotNull(elementsToRetain)) : Iterators.retainAll(removeFrom.iterator(), elementsToRetain); } /** * Removes, from an iterable, every element that satisfies the provided * predicate. * * @param removeFrom the iterable to (potentially) remove elements from * @param predicate a predicate that determines whether an element should * be removed * @return {@code true} if any elements were removed from the iterable * * @throws UnsupportedOperationException if the iterable does not support * {@code remove()}. * @since 2.0 */ public static <T> boolean removeIf( Iterable<T> removeFrom, Predicate<? super T> predicate) { if (removeFrom instanceof RandomAccess && removeFrom instanceof List) { return removeIfFromRandomAccessList( (List<T>) removeFrom, checkNotNull(predicate)); } return Iterators.removeIf(removeFrom.iterator(), predicate); } private static <T> boolean removeIfFromRandomAccessList( List<T> list, Predicate<? super T> predicate) { // Note: Not all random access lists support set() so we need to deal with // those that don't and attempt the slower remove() based solution. int from = 0; int to = 0; for (; from < list.size(); from++) { T element = list.get(from); if (!predicate.apply(element)) { if (from > to) { try { list.set(to, element); } catch (UnsupportedOperationException e) { slowRemoveIfForRemainingElements(list, predicate, to, from); return true; } } to++; } } // Clear the tail of any remaining items list.subList(to, list.size()).clear(); return from != to; } private static <T> void slowRemoveIfForRemainingElements(List<T> list, Predicate<? super T> predicate, int to, int from) { // Here we know that: // * (to < from) and that both are valid indices. // * Everything with (index < to) should be kept. // * Everything with (to <= index < from) should be removed. // * The element with (index == from) should be kept. // * Everything with (index > from) has not been checked yet. // Check from the end of the list backwards (minimize expected cost of // moving elements when remove() is called). Stop before 'from' because // we already know that should be kept. for (int n = list.size() - 1; n > from; n--) { if (predicate.apply(list.get(n))) { list.remove(n); } } // And now remove everything in the range [to, from) (going backwards). for (int n = from - 1; n >= to; n--) { list.remove(n); } } /** * Removes and returns the first matching element, or returns {@code null} if there is none. */ @Nullable static <T> T removeFirstMatching(Iterable<T> removeFrom, Predicate<? super T> predicate) { checkNotNull(predicate); Iterator<T> iterator = removeFrom.iterator(); while (iterator.hasNext()) { T next = iterator.next(); if (predicate.apply(next)) { iterator.remove(); return next; } } return null; } /** * Determines whether two iterables contain equal elements in the same order. * More specifically, this method returns {@code true} if {@code iterable1} * and {@code iterable2} contain the same number of elements and every element * of {@code iterable1} is equal to the corresponding element of * {@code iterable2}. */ public static boolean elementsEqual( Iterable<?> iterable1, Iterable<?> iterable2) { if (iterable1 instanceof Collection && iterable2 instanceof Collection) { Collection<?> collection1 = (Collection<?>) iterable1; Collection<?> collection2 = (Collection<?>) iterable2; if (collection1.size() != collection2.size()) { return false; } } return Iterators.elementsEqual(iterable1.iterator(), iterable2.iterator()); } /** * Returns a string representation of {@code iterable}, with the format {@code * [e1, e2, ..., en]} (that is, identical to {@link java.util.Arrays * Arrays}{@code .toString(Iterables.toArray(iterable))}). Note that for * <i>most</i> implementations of {@link Collection}, {@code * collection.toString()} also gives the same result, but that behavior is not * generally guaranteed. */ public static String toString(Iterable<?> iterable) { return Iterators.toString(iterable.iterator()); } /** * Returns the single element contained in {@code iterable}. * * @throws NoSuchElementException if the iterable is empty * @throws IllegalArgumentException if the iterable contains multiple * elements */ public static <T> T getOnlyElement(Iterable<T> iterable) { return Iterators.getOnlyElement(iterable.iterator()); } /** * Returns the single element contained in {@code iterable}, or {@code * defaultValue} if the iterable is empty. * * @throws IllegalArgumentException if the iterator contains multiple * elements */ @Nullable public static <T> T getOnlyElement( Iterable<? extends T> iterable, @Nullable T defaultValue) { return Iterators.getOnlyElement(iterable.iterator(), defaultValue); } /** * Copies an iterable's elements into an array. * * @param iterable the iterable to copy * @return a newly-allocated array into which all the elements of the iterable * have been copied */ static Object[] toArray(Iterable<?> iterable) { return toCollection(iterable).toArray(); } /** * Converts an iterable into a collection. If the iterable is already a * collection, it is returned. Otherwise, an {@link java.util.ArrayList} is * created with the contents of the iterable in the same iteration order. */ private static <E> Collection<E> toCollection(Iterable<E> iterable) { return (iterable instanceof Collection) ? (Collection<E>) iterable : Lists.newArrayList(iterable.iterator()); } /** * Adds all elements in {@code iterable} to {@code collection}. * * @return {@code true} if {@code collection} was modified as a result of this * operation. */ public static <T> boolean addAll( Collection<T> addTo, Iterable<? extends T> elementsToAdd) { if (elementsToAdd instanceof Collection) { Collection<? extends T> c = Collections2.cast(elementsToAdd); return addTo.addAll(c); } return Iterators.addAll(addTo, checkNotNull(elementsToAdd).iterator()); } /** * Returns the number of elements in the specified iterable that equal the * specified object. This implementation avoids a full iteration when the * iterable is a {@link Multiset} or {@link Set}. * * @see Collections#frequency */ public static int frequency(Iterable<?> iterable, @Nullable Object element) { if ((iterable instanceof Multiset)) { return ((Multiset<?>) iterable).count(element); } else if ((iterable instanceof Set)) { return ((Set<?>) iterable).contains(element) ? 1 : 0; } return Iterators.frequency(iterable.iterator(), element); } /** * Returns an iterable whose iterators cycle indefinitely over the elements of * {@code iterable}. * * <p>That iterator supports {@code remove()} if {@code iterable.iterator()} * does. After {@code remove()} is called, subsequent cycles omit the removed * element, which is no longer in {@code iterable}. The iterator's * {@code hasNext()} method returns {@code true} until {@code iterable} is * empty. * * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an * infinite loop. You should use an explicit {@code break} or be certain that * you will eventually remove all the elements. * * <p>To cycle over the iterable {@code n} times, use the following: * {@code Iterables.concat(Collections.nCopies(n, iterable))} */ public static <T> Iterable<T> cycle(final Iterable<T> iterable) { checkNotNull(iterable); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.cycle(iterable); } @Override public String toString() { return iterable.toString() + " (cycled)"; } }; } /** * Returns an iterable whose iterators cycle indefinitely over the provided * elements. * * <p>After {@code remove} is invoked on a generated iterator, the removed * element will no longer appear in either that iterator or any other iterator * created from the same source iterable. That is, this method behaves exactly * as {@code Iterables.cycle(Lists.newArrayList(elements))}. The iterator's * {@code hasNext} method returns {@code true} until all of the original * elements have been removed. * * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an * infinite loop. You should use an explicit {@code break} or be certain that * you will eventually remove all the elements. * * <p>To cycle over the elements {@code n} times, use the following: * {@code Iterables.concat(Collections.nCopies(n, Arrays.asList(elements)))} */ public static <T> Iterable<T> cycle(T... elements) { return cycle(Lists.newArrayList(elements)); } /** * Combines two iterables into a single iterable. The returned iterable has an * iterator that traverses the elements in {@code a}, followed by the elements * in {@code b}. The source iterators are not polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the * corresponding input iterator supports it. */ public static <T> Iterable<T> concat( Iterable<? extends T> a, Iterable<? extends T> b) { return concat(ImmutableList.of(a, b)); } /** * Combines three iterables into a single iterable. The returned iterable has * an iterator that traverses the elements in {@code a}, followed by the * elements in {@code b}, followed by the elements in {@code c}. The source * iterators are not polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the * corresponding input iterator supports it. */ public static <T> Iterable<T> concat(Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c) { return concat(ImmutableList.of(a, b, c)); } /** * Combines four iterables into a single iterable. The returned iterable has * an iterator that traverses the elements in {@code a}, followed by the * elements in {@code b}, followed by the elements in {@code c}, followed by * the elements in {@code d}. The source iterators are not polled until * necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the * corresponding input iterator supports it. */ public static <T> Iterable<T> concat(Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c, Iterable<? extends T> d) { return concat(ImmutableList.of(a, b, c, d)); } /** * Combines multiple iterables into a single iterable. The returned iterable * has an iterator that traverses the elements of each iterable in * {@code inputs}. The input iterators are not polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the * corresponding input iterator supports it. * * @throws NullPointerException if any of the provided iterables is null */ public static <T> Iterable<T> concat(Iterable<? extends T>... inputs) { return concat(ImmutableList.copyOf(inputs)); } /** * Combines multiple iterables into a single iterable. The returned iterable * has an iterator that traverses the elements of each iterable in * {@code inputs}. The input iterators are not polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the * corresponding input iterator supports it. The methods of the returned * iterable may throw {@code NullPointerException} if any of the input * iterators is null. */ public static <T> Iterable<T> concat( final Iterable<? extends Iterable<? extends T>> inputs) { checkNotNull(inputs); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.concat(iterators(inputs)); } }; } /** * Returns an iterator over the iterators of the given iterables. */ private static <T> Iterator<Iterator<? extends T>> iterators( Iterable<? extends Iterable<? extends T>> iterables) { return new TransformedIterator<Iterable<? extends T>, Iterator<? extends T>>( iterables.iterator()) { @Override Iterator<? extends T> transform(Iterable<? extends T> from) { return from.iterator(); } }; } /** * Divides an iterable into unmodifiable sublists of the given size (the final * iterable may be smaller). For example, partitioning an iterable containing * {@code [a, b, c, d, e]} with a partition size of 3 yields {@code * [[a, b, c], [d, e]]} -- an outer iterable containing two inner lists of * three and two elements, all in the original order. * * <p>Iterators returned by the returned iterable do not support the {@link * Iterator#remove()} method. The returned lists implement {@link * RandomAccess}, whether or not the input list does. * * <p><b>Note:</b> if {@code iterable} is a {@link List}, use {@link * Lists#partition(List, int)} instead. * * @param iterable the iterable to return a partitioned view of * @param size the desired size of each partition (the last may be smaller) * @return an iterable of unmodifiable lists containing the elements of {@code * iterable} divided into partitions * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T> Iterable<List<T>> partition( final Iterable<T> iterable, final int size) { checkNotNull(iterable); checkArgument(size > 0); return new FluentIterable<List<T>>() { @Override public Iterator<List<T>> iterator() { return Iterators.partition(iterable.iterator(), size); } }; } /** * Divides an iterable into unmodifiable sublists of the given size, padding * the final iterable with null values if necessary. For example, partitioning * an iterable containing {@code [a, b, c, d, e]} with a partition size of 3 * yields {@code [[a, b, c], [d, e, null]]} -- an outer iterable containing * two inner lists of three elements each, all in the original order. * * <p>Iterators returned by the returned iterable do not support the {@link * Iterator#remove()} method. * * @param iterable the iterable to return a partitioned view of * @param size the desired size of each partition * @return an iterable of unmodifiable lists containing the elements of {@code * iterable} divided into partitions (the final iterable may have * trailing null elements) * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T> Iterable<List<T>> paddedPartition( final Iterable<T> iterable, final int size) { checkNotNull(iterable); checkArgument(size > 0); return new FluentIterable<List<T>>() { @Override public Iterator<List<T>> iterator() { return Iterators.paddedPartition(iterable.iterator(), size); } }; } /** * Returns the elements of {@code unfiltered} that satisfy a predicate. The * resulting iterable's iterator does not support {@code remove()}. */ public static <T> Iterable<T> filter( final Iterable<T> unfiltered, final Predicate<? super T> predicate) { checkNotNull(unfiltered); checkNotNull(predicate); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.filter(unfiltered.iterator(), predicate); } }; } /** * Returns {@code true} if any element in {@code iterable} satisfies the predicate. */ public static <T> boolean any( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.any(iterable.iterator(), predicate); } /** * Returns {@code true} if every element in {@code iterable} satisfies the * predicate. If {@code iterable} is empty, {@code true} is returned. */ public static <T> boolean all( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.all(iterable.iterator(), predicate); } /** * Returns the first element in {@code iterable} that satisfies the given * predicate; use this method only when such an element is known to exist. If * it is possible that <i>no</i> element will match, use {@link #tryFind} or * {@link #find(Iterable, Predicate, Object)} instead. * * @throws NoSuchElementException if no element in {@code iterable} matches * the given predicate */ public static <T> T find(Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.find(iterable.iterator(), predicate); } /** * Returns the first element in {@code iterable} that satisfies the given * predicate, or {@code defaultValue} if none found. Note that this can * usually be handled more naturally using {@code * tryFind(iterable, predicate).or(defaultValue)}. * * @since 7.0 */ @Nullable public static <T> T find(Iterable<? extends T> iterable, Predicate<? super T> predicate, @Nullable T defaultValue) { return Iterators.find(iterable.iterator(), predicate, defaultValue); } /** * Returns an {@link Optional} containing the first element in {@code * iterable} that satisfies the given predicate, if such an element exists. * * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code * null}. If {@code null} is matched in {@code iterable}, a * NullPointerException will be thrown. * * @since 11.0 */ public static <T> Optional<T> tryFind(Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.tryFind(iterable.iterator(), predicate); } /** * Returns the index in {@code iterable} of the first element that satisfies * the provided {@code predicate}, or {@code -1} if the Iterable has no such * elements. * * <p>More formally, returns the lowest index {@code i} such that * {@code predicate.apply(Iterables.get(iterable, i))} returns {@code true}, * or {@code -1} if there is no such index. * * @since 2.0 */ public static <T> int indexOf( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.indexOf(iterable.iterator(), predicate); } /** * Returns an iterable that applies {@code function} to each element of {@code * fromIterable}. * * <p>The returned iterable's iterator supports {@code remove()} if the * provided iterator does. After a successful {@code remove()} call, * {@code fromIterable} no longer contains the corresponding element. * * <p>If the input {@code Iterable} is known to be a {@code List} or other * {@code Collection}, consider {@link Lists#transform} and {@link * Collections2#transform}. */ public static <F, T> Iterable<T> transform(final Iterable<F> fromIterable, final Function<? super F, ? extends T> function) { checkNotNull(fromIterable); checkNotNull(function); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.transform(fromIterable.iterator(), function); } }; } /** * Returns the element at the specified position in an iterable. * * @param position position of the element to return * @return the element at the specified position in {@code iterable} * @throws IndexOutOfBoundsException if {@code position} is negative or * greater than or equal to the size of {@code iterable} */ public static <T> T get(Iterable<T> iterable, int position) { checkNotNull(iterable); return (iterable instanceof List) ? ((List<T>) iterable).get(position) : Iterators.get(iterable.iterator(), position); } /** * Returns the element at the specified position in an iterable or a default * value otherwise. * * @param position position of the element to return * @param defaultValue the default value to return if {@code position} is * greater than or equal to the size of the iterable * @return the element at the specified position in {@code iterable} or * {@code defaultValue} if {@code iterable} contains fewer than * {@code position + 1} elements. * @throws IndexOutOfBoundsException if {@code position} is negative * @since 4.0 */ @Nullable public static <T> T get(Iterable<? extends T> iterable, int position, @Nullable T defaultValue) { checkNotNull(iterable); Iterators.checkNonnegative(position); if (iterable instanceof List) { List<? extends T> list = Lists.cast(iterable); return (position < list.size()) ? list.get(position) : defaultValue; } else { Iterator<? extends T> iterator = iterable.iterator(); Iterators.advance(iterator, position); return Iterators.getNext(iterator, defaultValue); } } /** * Returns the first element in {@code iterable} or {@code defaultValue} if * the iterable is empty. The {@link Iterators} analog to this method is * {@link Iterators#getNext}. * * <p>If no default value is desired (and the caller instead wants a * {@link NoSuchElementException} to be thrown), it is recommended that * {@code iterable.iterator().next()} is used instead. * * @param defaultValue the default value to return if the iterable is empty * @return the first element of {@code iterable} or the default value * @since 7.0 */ @Nullable public static <T> T getFirst(Iterable<? extends T> iterable, @Nullable T defaultValue) { return Iterators.getNext(iterable.iterator(), defaultValue); } /** * Returns the last element of {@code iterable}. * * @return the last element of {@code iterable} * @throws NoSuchElementException if the iterable is empty */ public static <T> T getLast(Iterable<T> iterable) { // TODO(kevinb): Support a concurrently modified collection? if (iterable instanceof List) { List<T> list = (List<T>) iterable; if (list.isEmpty()) { throw new NoSuchElementException(); } return getLastInNonemptyList(list); } return Iterators.getLast(iterable.iterator()); } /** * Returns the last element of {@code iterable} or {@code defaultValue} if * the iterable is empty. * * @param defaultValue the value to return if {@code iterable} is empty * @return the last element of {@code iterable} or the default value * @since 3.0 */ @Nullable public static <T> T getLast(Iterable<? extends T> iterable, @Nullable T defaultValue) { if (iterable instanceof Collection) { Collection<? extends T> c = Collections2.cast(iterable); if (c.isEmpty()) { return defaultValue; } else if (iterable instanceof List) { return getLastInNonemptyList(Lists.cast(iterable)); } } return Iterators.getLast(iterable.iterator(), defaultValue); } private static <T> T getLastInNonemptyList(List<T> list) { return list.get(list.size() - 1); } /** * Returns a view of {@code iterable} that skips its first * {@code numberToSkip} elements. If {@code iterable} contains fewer than * {@code numberToSkip} elements, the returned iterable skips all of its * elements. * * <p>Modifications to the underlying {@link Iterable} before a call to * {@code iterator()} are reflected in the returned iterator. That is, the * iterator skips the first {@code numberToSkip} elements that exist when the * {@code Iterator} is created, not when {@code skip()} is called. * * <p>The returned iterable's iterator supports {@code remove()} if the * iterator of the underlying iterable supports it. Note that it is * <i>not</i> possible to delete the last skipped element by immediately * calling {@code remove()} on that iterator, as the {@code Iterator} * contract states that a call to {@code remove()} before a call to * {@code next()} will throw an {@link IllegalStateException}. * * @since 3.0 */ public static <T> Iterable<T> skip(final Iterable<T> iterable, final int numberToSkip) { checkNotNull(iterable); checkArgument(numberToSkip >= 0, "number to skip cannot be negative"); if (iterable instanceof List) { final List<T> list = (List<T>) iterable; return new FluentIterable<T>() { @Override public Iterator<T> iterator() { // TODO(kevinb): Support a concurrently modified collection? int toSkip = Math.min(list.size(), numberToSkip); return list.subList(toSkip, list.size()).iterator(); } }; } return new FluentIterable<T>() { @Override public Iterator<T> iterator() { final Iterator<T> iterator = iterable.iterator(); Iterators.advance(iterator, numberToSkip); /* * We can't just return the iterator because an immediate call to its * remove() method would remove one of the skipped elements instead of * throwing an IllegalStateException. */ return new Iterator<T>() { boolean atStart = true; @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { T result = iterator.next(); atStart = false; // not called if next() fails return result; } @Override public void remove() { checkRemove(!atStart); iterator.remove(); } }; } }; } /** * Creates an iterable with the first {@code limitSize} elements of the given * iterable. If the original iterable does not contain that many elements, the * returned iterable will have the same behavior as the original iterable. The * returned iterable's iterator supports {@code remove()} if the original * iterator does. * * @param iterable the iterable to limit * @param limitSize the maximum number of elements in the returned iterable * @throws IllegalArgumentException if {@code limitSize} is negative * @since 3.0 */ public static <T> Iterable<T> limit( final Iterable<T> iterable, final int limitSize) { checkNotNull(iterable); checkArgument(limitSize >= 0, "limit is negative"); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.limit(iterable.iterator(), limitSize); } }; } /** * Returns a view of the supplied iterable that wraps each generated * {@link Iterator} through {@link Iterators#consumingIterator(Iterator)}. * * <p>Note: If {@code iterable} is a {@link Queue}, the returned iterable will * get entries from {@link Queue#remove()} since {@link Queue}'s iteration * order is undefined. Calling {@link Iterator#hasNext()} on a generated * iterator from the returned iterable may cause an item to be immediately * dequeued for return on a subsequent call to {@link Iterator#next()}. * * @param iterable the iterable to wrap * @return a view of the supplied iterable that wraps each generated iterator * through {@link Iterators#consumingIterator(Iterator)}; for queues, * an iterable that generates iterators that return and consume the * queue's elements in queue order * * @see Iterators#consumingIterator(Iterator) * @since 2.0 */ public static <T> Iterable<T> consumingIterable(final Iterable<T> iterable) { if (iterable instanceof Queue) { return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return new ConsumingQueueIterator<T>((Queue<T>) iterable); } @Override public String toString() { return "Iterables.consumingIterable(...)"; } }; } checkNotNull(iterable); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.consumingIterator(iterable.iterator()); } @Override public String toString() { return "Iterables.consumingIterable(...)"; } }; } private static class ConsumingQueueIterator<T> extends AbstractIterator<T> { private final Queue<T> queue; private ConsumingQueueIterator(Queue<T> queue) { this.queue = queue; } @Override public T computeNext() { try { return queue.remove(); } catch (NoSuchElementException e) { return endOfData(); } } } // Methods only in Iterables, not in Iterators /** * Determines if the given iterable contains no elements. * * <p>There is no precise {@link Iterator} equivalent to this method, since * one can only ask an iterator whether it has any elements <i>remaining</i> * (which one does using {@link Iterator#hasNext}). * * @return {@code true} if the iterable contains no elements */ public static boolean isEmpty(Iterable<?> iterable) { if (iterable instanceof Collection) { return ((Collection<?>) iterable).isEmpty(); } return !iterable.iterator().hasNext(); } /** * Returns an iterable over the merged contents of all given * {@code iterables}. Equivalent entries will not be de-duplicated. * * <p>Callers must ensure that the source {@code iterables} are in * non-descending order as this method does not sort its input. * * <p>For any equivalent elements across all {@code iterables}, it is * undefined which element is returned first. * * @since 11.0 */ @Beta public static <T> Iterable<T> mergeSorted( final Iterable<? extends Iterable<? extends T>> iterables, final Comparator<? super T> comparator) { checkNotNull(iterables, "iterables"); checkNotNull(comparator, "comparator"); Iterable<T> iterable = new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.mergeSorted( Iterables.transform(iterables, Iterables.<T>toIterator()), comparator); } }; return new UnmodifiableIterable<T>(iterable); } // TODO(user): Is this the best place for this? Move to fluent functions? // Useful as a public method? private static <T> Function<Iterable<? extends T>, Iterator<? extends T>> toIterator() { return new Function<Iterable<? extends T>, Iterator<? extends T>>() { @Override public Iterator<? extends T> apply(Iterable<? extends T> iterable) { return iterable.iterator(); } }; } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/Iterables.java
Java
asf20
36,439
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.collect.BoundType.CLOSED; import static com.google.common.collect.BoundType.OPEN; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.Multiset.Entry; import java.util.Comparator; import java.util.NoSuchElementException; import java.util.SortedSet; import javax.annotation.Nullable; /** * Provides static utility methods for creating and working with * {@link SortedMultiset} instances. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) final class SortedMultisets { private SortedMultisets() { } /** * A skeleton implementation for {@link SortedMultiset#elementSet}. */ static class ElementSet<E> extends Multisets.ElementSet<E> implements SortedSet<E> { private final SortedMultiset<E> multiset; ElementSet(SortedMultiset<E> multiset) { this.multiset = multiset; } @Override final SortedMultiset<E> multiset() { return multiset; } @Override public Comparator<? super E> comparator() { return multiset().comparator(); } @Override public SortedSet<E> subSet(E fromElement, E toElement) { return multiset().subMultiset(fromElement, CLOSED, toElement, OPEN).elementSet(); } @Override public SortedSet<E> headSet(E toElement) { return multiset().headMultiset(toElement, OPEN).elementSet(); } @Override public SortedSet<E> tailSet(E fromElement) { return multiset().tailMultiset(fromElement, CLOSED).elementSet(); } @Override public E first() { return getElementOrThrow(multiset().firstEntry()); } @Override public E last() { return getElementOrThrow(multiset().lastEntry()); } } private static <E> E getElementOrThrow(Entry<E> entry) { if (entry == null) { throw new NoSuchElementException(); } return entry.getElement(); } private static <E> E getElementOrNull(@Nullable Entry<E> entry) { return (entry == null) ? null : entry.getElement(); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/SortedMultisets.java
Java
asf20
2,647
/* * 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 java.util.Collections; /** * GWT emulation of {@link EmptyImmutableSet}. * * @author Hayward Chan */ final class EmptyImmutableSet extends ForwardingImmutableSet<Object> { private EmptyImmutableSet() { super(Collections.emptySet()); } static final EmptyImmutableSet INSTANCE = new EmptyImmutableSet(); }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/EmptyImmutableSet.java
Java
asf20
965
/* * 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.checkPositionIndex; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.CollectPreconditions.checkRemove; import static java.util.Collections.unmodifiableList; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.AbstractSequentialList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; /** * An implementation of {@code ListMultimap} that supports deterministic * iteration order for both keys and values. The iteration order is preserved * across non-distinct key values. For example, for the following multimap * definition: <pre> {@code * * Multimap<K, V> multimap = LinkedListMultimap.create(); * multimap.put(key1, foo); * multimap.put(key2, bar); * multimap.put(key1, baz);}</pre> * * ... the iteration order for {@link #keys()} is {@code [key1, key2, key1]}, * and similarly for {@link #entries()}. Unlike {@link LinkedHashMultimap}, the * iteration order is kept consistent between keys, entries and values. For * example, calling: <pre> {@code * * map.remove(key1, foo);}</pre> * * <p>changes the entries iteration order to {@code [key2=bar, key1=baz]} and the * key iteration order to {@code [key2, key1]}. The {@link #entries()} iterator * returns mutable map entries, and {@link #replaceValues} attempts to preserve * iteration order as much as possible. * * <p>The collections returned by {@link #keySet()} and {@link #asMap} iterate * through the keys in the order they were first added to the multimap. * Similarly, {@link #get}, {@link #removeAll}, and {@link #replaceValues} * return collections that iterate through the values in the order they were * added. The collections generated by {@link #entries()}, {@link #keys()}, and * {@link #values} iterate across the key-value mappings in the order they were * added to the multimap. * * <p>The {@link #values()} and {@link #entries()} methods both return a * {@code List}, instead of the {@code Collection} specified by the {@link * ListMultimap} interface. * * <p>The methods {@link #get}, {@link #keySet()}, {@link #keys()}, * {@link #values}, {@link #entries()}, and {@link #asMap} return collections * that are views of the multimap. If the multimap is modified while an * iteration over any of those collections is in progress, except through the * iterator's methods, the results of the iteration are undefined. * * <p>Keys and values may be null. All optional multimap methods are supported, * and all returned views are modifiable. * * <p>This class is not threadsafe when any concurrent operations update the * multimap. Concurrent read operations will work correctly. To allow concurrent * update operations, wrap your multimap with a call to {@link * Multimaps#synchronizedListMultimap}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap"> * {@code Multimap}</a>. * * @author Mike Bostock * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public class LinkedListMultimap<K, V> extends AbstractMultimap<K, V> implements ListMultimap<K, V>, Serializable { /* * Order is maintained using a linked list containing all key-value pairs. In * addition, a series of disjoint linked lists of "siblings", each containing * the values for a specific key, is used to implement {@link * ValueForKeyIterator} in constant time. */ private static final class Node<K, V> extends AbstractMapEntry<K, V> { final K key; V value; Node<K, V> next; // the next node (with any key) Node<K, V> previous; // the previous node (with any key) Node<K, V> nextSibling; // the next node with the same key Node<K, V> previousSibling; // the previous node with the same key Node(@Nullable K key, @Nullable V value) { this.key = key; this.value = value; } @Override public K getKey() { return key; } @Override public V getValue() { return value; } @Override public V setValue(@Nullable V newValue) { V result = value; this.value = newValue; return result; } } private static class KeyList<K, V> { Node<K, V> head; Node<K, V> tail; int count; KeyList(Node<K, V> firstNode) { this.head = firstNode; this.tail = firstNode; firstNode.previousSibling = null; firstNode.nextSibling = null; this.count = 1; } } private transient Node<K, V> head; // the head for all keys private transient Node<K, V> tail; // the tail for all keys private transient Map<K, KeyList<K, V>> keyToKeyList; private transient int size; /* * Tracks modifications to keyToKeyList so that addition or removal of keys invalidates * preexisting iterators. This does *not* track simple additions and removals of values * that are not the first to be added or last to be removed for their key. */ private transient int modCount; /** * Creates a new, empty {@code LinkedListMultimap} with the default initial * capacity. */ public static <K, V> LinkedListMultimap<K, V> create() { return new LinkedListMultimap<K, V>(); } /** * Constructs an empty {@code LinkedListMultimap} with enough capacity to hold * the specified number of keys without rehashing. * * @param expectedKeys the expected number of distinct keys * @throws IllegalArgumentException if {@code expectedKeys} is negative */ public static <K, V> LinkedListMultimap<K, V> create(int expectedKeys) { return new LinkedListMultimap<K, V>(expectedKeys); } /** * Constructs a {@code LinkedListMultimap} with the same mappings as the * specified {@code Multimap}. The new multimap has the same * {@link Multimap#entries()} iteration order as the input multimap. * * @param multimap the multimap whose contents are copied to this multimap */ public static <K, V> LinkedListMultimap<K, V> create( Multimap<? extends K, ? extends V> multimap) { return new LinkedListMultimap<K, V>(multimap); } LinkedListMultimap() { keyToKeyList = Maps.newHashMap(); } private LinkedListMultimap(int expectedKeys) { keyToKeyList = new HashMap<K, KeyList<K, V>>(expectedKeys); } private LinkedListMultimap(Multimap<? extends K, ? extends V> multimap) { this(multimap.keySet().size()); putAll(multimap); } /** * Adds a new node for the specified key-value pair before the specified * {@code nextSibling} element, or at the end of the list if {@code * nextSibling} is null. Note: if {@code nextSibling} is specified, it MUST be * for an node for the same {@code key}! */ private Node<K, V> addNode( @Nullable K key, @Nullable V value, @Nullable Node<K, V> nextSibling) { Node<K, V> node = new Node<K, V>(key, value); if (head == null) { // empty list head = tail = node; keyToKeyList.put(key, new KeyList<K, V>(node)); modCount++; } else if (nextSibling == null) { // non-empty list, add to tail tail.next = node; node.previous = tail; tail = node; KeyList<K, V> keyList = keyToKeyList.get(key); if (keyList == null) { keyToKeyList.put(key, keyList = new KeyList<K, V>(node)); modCount++; } else { keyList.count++; Node<K, V> keyTail = keyList.tail; keyTail.nextSibling = node; node.previousSibling = keyTail; keyList.tail = node; } } else { // non-empty list, insert before nextSibling KeyList<K, V> keyList = keyToKeyList.get(key); keyList.count++; node.previous = nextSibling.previous; node.previousSibling = nextSibling.previousSibling; node.next = nextSibling; node.nextSibling = nextSibling; if (nextSibling.previousSibling == null) { // nextSibling was key head keyToKeyList.get(key).head = node; } else { nextSibling.previousSibling.nextSibling = node; } if (nextSibling.previous == null) { // nextSibling was head head = node; } else { nextSibling.previous.next = node; } nextSibling.previous = node; nextSibling.previousSibling = node; } size++; return node; } /** * Removes the specified node from the linked list. This method is only * intended to be used from the {@code Iterator} classes. See also {@link * LinkedListMultimap#removeAllNodes(Object)}. */ private void removeNode(Node<K, V> node) { if (node.previous != null) { node.previous.next = node.next; } else { // node was head head = node.next; } if (node.next != null) { node.next.previous = node.previous; } else { // node was tail tail = node.previous; } if (node.previousSibling == null && node.nextSibling == null) { KeyList<K, V> keyList = keyToKeyList.remove(node.key); keyList.count = 0; modCount++; } else { KeyList<K, V> keyList = keyToKeyList.get(node.key); keyList.count--; if (node.previousSibling == null) { keyList.head = node.nextSibling; } else { node.previousSibling.nextSibling = node.nextSibling; } if (node.nextSibling == null) { keyList.tail = node.previousSibling; } else { node.nextSibling.previousSibling = node.previousSibling; } } size--; } /** Removes all nodes for the specified key. */ private void removeAllNodes(@Nullable Object key) { Iterators.clear(new ValueForKeyIterator(key)); } /** Helper method for verifying that an iterator element is present. */ private static void checkElement(@Nullable Object node) { if (node == null) { throw new NoSuchElementException(); } } /** An {@code Iterator} over all nodes. */ private class NodeIterator implements ListIterator<Entry<K, V>> { int nextIndex; Node<K, V> next; Node<K, V> current; Node<K, V> previous; int expectedModCount = modCount; NodeIterator(int index) { int size = size(); checkPositionIndex(index, size); if (index >= (size / 2)) { previous = tail; nextIndex = size; while (index++ < size) { previous(); } } else { next = head; while (index-- > 0) { next(); } } current = null; } private void checkForConcurrentModification() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } @Override public boolean hasNext() { checkForConcurrentModification(); return next != null; } @Override public Node<K, V> next() { checkForConcurrentModification(); checkElement(next); previous = current = next; next = next.next; nextIndex++; return current; } @Override public void remove() { checkForConcurrentModification(); checkRemove(current != null); if (current != next) { // after call to next() previous = current.previous; nextIndex--; } else { // after call to previous() next = current.next; } removeNode(current); current = null; expectedModCount = modCount; } @Override public boolean hasPrevious() { checkForConcurrentModification(); return previous != null; } @Override public Node<K, V> previous() { checkForConcurrentModification(); checkElement(previous); next = current = previous; previous = previous.previous; nextIndex--; return current; } @Override public int nextIndex() { return nextIndex; } @Override public int previousIndex() { return nextIndex - 1; } @Override public void set(Entry<K, V> e) { throw new UnsupportedOperationException(); } @Override public void add(Entry<K, V> e) { throw new UnsupportedOperationException(); } void setValue(V value) { checkState(current != null); current.value = value; } } /** An {@code Iterator} over distinct keys in key head order. */ private class DistinctKeyIterator implements Iterator<K> { final Set<K> seenKeys = Sets.<K>newHashSetWithExpectedSize(keySet().size()); Node<K, V> next = head; Node<K, V> current; int expectedModCount = modCount; private void checkForConcurrentModification() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } @Override public boolean hasNext() { checkForConcurrentModification(); return next != null; } @Override public K next() { checkForConcurrentModification(); checkElement(next); current = next; seenKeys.add(current.key); do { // skip ahead to next unseen key next = next.next; } while ((next != null) && !seenKeys.add(next.key)); return current.key; } @Override public void remove() { checkForConcurrentModification(); checkRemove(current != null); removeAllNodes(current.key); current = null; expectedModCount = modCount; } } /** A {@code ListIterator} over values for a specified key. */ private class ValueForKeyIterator implements ListIterator<V> { final Object key; int nextIndex; Node<K, V> next; Node<K, V> current; Node<K, V> previous; /** Constructs a new iterator over all values for the specified key. */ ValueForKeyIterator(@Nullable Object key) { this.key = key; KeyList<K, V> keyList = keyToKeyList.get(key); next = (keyList == null) ? null : keyList.head; } /** * Constructs a new iterator over all values for the specified key starting * at the specified index. This constructor is optimized so that it starts * at either the head or the tail, depending on which is closer to the * specified index. This allows adds to the tail to be done in constant * time. * * @throws IndexOutOfBoundsException if index is invalid */ public ValueForKeyIterator(@Nullable Object key, int index) { KeyList<K, V> keyList = keyToKeyList.get(key); int size = (keyList == null) ? 0 : keyList.count; checkPositionIndex(index, size); if (index >= (size / 2)) { previous = (keyList == null) ? null : keyList.tail; nextIndex = size; while (index++ < size) { previous(); } } else { next = (keyList == null) ? null : keyList.head; while (index-- > 0) { next(); } } this.key = key; current = null; } @Override public boolean hasNext() { return next != null; } @Override public V next() { checkElement(next); previous = current = next; next = next.nextSibling; nextIndex++; return current.value; } @Override public boolean hasPrevious() { return previous != null; } @Override public V previous() { checkElement(previous); next = current = previous; previous = previous.previousSibling; nextIndex--; return current.value; } @Override public int nextIndex() { return nextIndex; } @Override public int previousIndex() { return nextIndex - 1; } @Override public void remove() { checkRemove(current != null); if (current != next) { // after call to next() previous = current.previousSibling; nextIndex--; } else { // after call to previous() next = current.nextSibling; } removeNode(current); current = null; } @Override public void set(V value) { checkState(current != null); current.value = value; } @Override @SuppressWarnings("unchecked") public void add(V value) { previous = addNode((K) key, value, next); nextIndex++; current = null; } } // Query Operations @Override public int size() { return size; } @Override public boolean isEmpty() { return head == null; } @Override public boolean containsKey(@Nullable Object key) { return keyToKeyList.containsKey(key); } @Override public boolean containsValue(@Nullable Object value) { return values().contains(value); } // Modification Operations /** * Stores a key-value pair in the multimap. * * @param key key to store in the multimap * @param value value to store in the multimap * @return {@code true} always */ @Override public boolean put(@Nullable K key, @Nullable V value) { addNode(key, value, null); return true; } // Bulk Operations /** * {@inheritDoc} * * <p>If any entries for the specified {@code key} already exist in the * multimap, their values are changed in-place without affecting the iteration * order. * * <p>The returned list is immutable and implements * {@link java.util.RandomAccess}. */ @Override public List<V> replaceValues(@Nullable K key, Iterable<? extends V> values) { List<V> oldValues = getCopy(key); ListIterator<V> keyValues = new ValueForKeyIterator(key); Iterator<? extends V> newValues = values.iterator(); // Replace existing values, if any. while (keyValues.hasNext() && newValues.hasNext()) { keyValues.next(); keyValues.set(newValues.next()); } // Remove remaining old values, if any. while (keyValues.hasNext()) { keyValues.next(); keyValues.remove(); } // Add remaining new values, if any. while (newValues.hasNext()) { keyValues.add(newValues.next()); } return oldValues; } private List<V> getCopy(@Nullable Object key) { return unmodifiableList(Lists.newArrayList(new ValueForKeyIterator(key))); } /** * {@inheritDoc} * * <p>The returned list is immutable and implements * {@link java.util.RandomAccess}. */ @Override public List<V> removeAll(@Nullable Object key) { List<V> oldValues = getCopy(key); removeAllNodes(key); return oldValues; } @Override public void clear() { head = null; tail = null; keyToKeyList.clear(); size = 0; modCount++; } // Views /** * {@inheritDoc} * * <p>If the multimap is modified while an iteration over the list is in * progress (except through the iterator's own {@code add}, {@code set} or * {@code remove} operations) the results of the iteration are undefined. * * <p>The returned list is not serializable and does not have random access. */ @Override public List<V> get(final @Nullable K key) { return new AbstractSequentialList<V>() { @Override public int size() { KeyList<K, V> keyList = keyToKeyList.get(key); return (keyList == null) ? 0 : keyList.count; } @Override public ListIterator<V> listIterator(int index) { return new ValueForKeyIterator(key, index); } }; } @Override Set<K> createKeySet() { return new Sets.ImprovedAbstractSet<K>() { @Override public int size() { return keyToKeyList.size(); } @Override public Iterator<K> iterator() { return new DistinctKeyIterator(); } @Override public boolean contains(Object key) { // for performance return containsKey(key); } @Override public boolean remove(Object o) { // for performance return !LinkedListMultimap.this.removeAll(o).isEmpty(); } }; } /** * {@inheritDoc} * * <p>The iterator generated by the returned collection traverses the values * in the order they were added to the multimap. Because the values may have * duplicates and follow the insertion ordering, this method returns a {@link * List}, instead of the {@link Collection} specified in the {@link * ListMultimap} interface. */ @Override public List<V> values() { return (List<V>) super.values(); } @Override List<V> createValues() { return new AbstractSequentialList<V>() { @Override public int size() { return size; } @Override public ListIterator<V> listIterator(int index) { final NodeIterator nodeItr = new NodeIterator(index); return new TransformedListIterator<Entry<K, V>, V>(nodeItr) { @Override V transform(Entry<K, V> entry) { return entry.getValue(); } @Override public void set(V value) { nodeItr.setValue(value); } }; } }; } /** * {@inheritDoc} * * <p>The iterator generated by the returned collection traverses the entries * in the order they were added to the multimap. Because the entries may have * duplicates and follow the insertion ordering, this method returns a {@link * List}, instead of the {@link Collection} specified in the {@link * ListMultimap} interface. * * <p>An entry's {@link Entry#getKey} method always returns the same key, * regardless of what happens subsequently. As long as the corresponding * key-value mapping is not removed from the multimap, {@link Entry#getValue} * returns the value from the multimap, which may change over time, and {@link * Entry#setValue} modifies that value. Removing the mapping from the * multimap does not alter the value returned by {@code getValue()}, though a * subsequent {@code setValue()} call won't update the multimap but will lead * to a revised value being returned by {@code getValue()}. */ @Override public List<Entry<K, V>> entries() { return (List<Entry<K, V>>) super.entries(); } @Override List<Entry<K, V>> createEntries() { return new AbstractSequentialList<Entry<K, V>>() { @Override public int size() { return size; } @Override public ListIterator<Entry<K, V>> listIterator(int index) { return new NodeIterator(index); } }; } @Override Iterator<Entry<K, V>> entryIterator() { throw new AssertionError("should never be called"); } @Override Map<K, Collection<V>> createAsMap() { return new Multimaps.AsMap<K, V>(this); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/LinkedListMultimap.java
Java
asf20
23,394
/* * 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 java.util.Map; /** * GWt emulation of {@link RegularImmutableMap}. * * @author Hayward Chan */ final class RegularImmutableMap<K, V> extends ForwardingImmutableMap<K, V> { RegularImmutableMap(Map<? extends K, ? extends V> delegate) { super(delegate); } RegularImmutableMap(Entry<? extends K, ? extends V>... entries) { super(entries); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/RegularImmutableMap.java
Java
asf20
1,007
/* * 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 java.util.HashMap; import java.util.Map; import javax.annotation.Nullable; /** * GWT emulation of {@code HashBiMap} that just delegates to two HashMaps. * * @author Mike Bostock */ public final class HashBiMap<K, V> extends AbstractBiMap<K, V> { /** * Returns a new, empty {@code HashBiMap} with the default initial capacity * (16). */ public static <K, V> HashBiMap<K, V> create() { return new HashBiMap<K, V>(); } /** * 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 HashBiMap() { super(new HashMap<K, V>(), new HashMap<V, K>()); } private HashBiMap(int expectedSize) { super( Maps.<K, V>newHashMapWithExpectedSize(expectedSize), Maps.<V, K>newHashMapWithExpectedSize(expectedSize)); } // Override these two methods to show that keys and values may be null @Override public V put(@Nullable K key, @Nullable V value) { return super.put(key, value); } @Override public V forcePut(@Nullable K key, @Nullable V value) { return super.forcePut(key, value); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/HashBiMap.java
Java
asf20
2,365
/* * 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.base.Optional; import java.util.LinkedList; import java.util.Iterator; /** * A variant of {@link TreeTraverser} for binary trees, providing additional traversals specific to * binary trees. * * @author Louis Wasserman */ public abstract class BinaryTreeTraverser<T> extends TreeTraverser<T> { // TODO(user): make this GWT-compatible when we've checked in ArrayDeque and BitSet emulation /** * Returns the left child of the specified node, or {@link Optional#absent()} if the specified * node has no left child. */ public abstract Optional<T> leftChild(T root); /** * Returns the right child of the specified node, or {@link Optional#absent()} if the specified * node has no right child. */ public abstract Optional<T> rightChild(T root); /** * Returns the children of this node, in left-to-right order. */ @Override public final Iterable<T> children(final T root) { checkNotNull(root); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return new AbstractIterator<T>() { boolean doneLeft; boolean doneRight; @Override protected T computeNext() { if (!doneLeft) { doneLeft = true; Optional<T> left = leftChild(root); if (left.isPresent()) { return left.get(); } } if (!doneRight) { doneRight = true; Optional<T> right = rightChild(root); if (right.isPresent()) { return right.get(); } } return endOfData(); } }; } }; } // TODO(user): see if any significant optimizations are possible for breadthFirstIterator public final FluentIterable<T> inOrderTraversal(final T root) { checkNotNull(root); return new FluentIterable<T>() { @Override public UnmodifiableIterator<T> iterator() { return new InOrderIterator(root); } }; } private static final class InOrderNode<T> { final T node; boolean hasExpandedLeft; InOrderNode(T node) { this.node = checkNotNull(node); this.hasExpandedLeft = false; } } private final class InOrderIterator extends AbstractIterator<T> { private final LinkedList<InOrderNode<T>> stack; InOrderIterator(T root) { this.stack = Lists.newLinkedList(); stack.addLast(new InOrderNode<T>(root)); } @Override protected T computeNext() { while (!stack.isEmpty()) { InOrderNode<T> inOrderNode = stack.getLast(); if (inOrderNode.hasExpandedLeft) { stack.removeLast(); pushIfPresent(rightChild(inOrderNode.node)); return inOrderNode.node; } else { inOrderNode.hasExpandedLeft = true; pushIfPresent(leftChild(inOrderNode.node)); } } return endOfData(); } private void pushIfPresent(Optional<T> node) { if (node.isPresent()) { stack.addLast(new InOrderNode<T>(node.get())); } } } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/BinaryTreeTraverser.java
Java
asf20
3,846
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.Map.Entry; import javax.annotation.Nullable; /** * {@code values()} implementation for {@link ImmutableMap}. * * @author Jesse Wilson * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) final class ImmutableMapValues<K, V> extends ImmutableCollection<V> { private final ImmutableMap<K, V> map; ImmutableMapValues(ImmutableMap<K, V> map) { this.map = map; } @Override public int size() { return map.size(); } @Override public UnmodifiableIterator<V> iterator() { return Maps.valueIterator(map.entrySet().iterator()); } @Override public boolean contains(@Nullable Object object) { return object != null && Iterators.contains(iterator(), object); } @Override boolean isPartialView() { return true; } @Override ImmutableList<V> createAsList() { final ImmutableList<Entry<K, V>> entryList = map.entrySet().asList(); return new ImmutableAsList<V>() { @Override public V get(int index) { return entryList.get(index).getValue(); } @Override ImmutableCollection<V> delegateCollection() { return ImmutableMapValues.this; } }; } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableMapValues.java
Java
asf20
1,876
/* * 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 java.util.Set; /** * GWT emulation of {@link ImmutableEnumSet}. The type parameter is not bounded * by {@code Enum<E>} to avoid code-size bloat. * * @author Hayward Chan */ final class ImmutableEnumSet<E> extends ForwardingImmutableSet<E> { static <E> ImmutableSet<E> asImmutable(Set<E> delegate) { switch (delegate.size()) { case 0: return ImmutableSet.of(); case 1: return ImmutableSet.of(Iterables.getOnlyElement(delegate)); default: return new ImmutableEnumSet<E>(delegate); } } public ImmutableEnumSet(Set<E> delegate) { super(delegate); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableEnumSet.java
Java
asf20
1,262
/* * 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.collect.CollectPreconditions.checkEntryNotNull; import java.util.Map; /** * GWT emulation of {@link ImmutableBiMap}. * * @author Hayward Chan */ public abstract class ImmutableBiMap<K, V> extends ForwardingImmutableMap<K, V> implements BiMap<K, V> { // Casting to any type is safe because the set will never hold any elements. @SuppressWarnings("unchecked") public static <K, V> ImmutableBiMap<K, V> of() { return (ImmutableBiMap<K, V>) EmptyImmutableBiMap.INSTANCE; } public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1) { checkEntryNotNull(k1, v1); return new SingletonImmutableBiMap<K, V>(k1, v1); } public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2) { return new RegularImmutableBiMap<K, V>(ImmutableMap.of(k1, v1, k2, v2)); } public static <K, V> ImmutableBiMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3) { return new RegularImmutableBiMap<K, V>(ImmutableMap.of( k1, v1, k2, v2, k3, v3)); } public static <K, V> ImmutableBiMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { return new RegularImmutableBiMap<K, V>(ImmutableMap.of( k1, v1, k2, v2, k3, v3, k4, v4)); } public static <K, V> ImmutableBiMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { return new RegularImmutableBiMap<K, V>(ImmutableMap.of( k1, v1, k2, v2, k3, v3, k4, v4, k5, v5)); } public static <K, V> Builder<K, V> builder() { return new Builder<K, V>(); } public static final class Builder<K, V> extends ImmutableMap.Builder<K, V> { public Builder() {} @Override public Builder<K, V> put(K key, V value) { super.put(key, value); return this; } @Override public Builder<K, V> putAll(Map<? extends K, ? extends V> map) { super.putAll(map); return this; } @Override public ImmutableBiMap<K, V> build() { ImmutableMap<K, V> map = super.build(); if (map.isEmpty()) { return of(); } return new RegularImmutableBiMap<K, V>(super.build()); } } public static <K, V> ImmutableBiMap<K, V> copyOf( Map<? extends K, ? extends V> map) { if (map instanceof ImmutableBiMap) { @SuppressWarnings("unchecked") // safe since map is not writable ImmutableBiMap<K, V> bimap = (ImmutableBiMap<K, V>) map; return bimap; } if (map.isEmpty()) { return of(); } ImmutableMap<K, V> immutableMap = ImmutableMap.copyOf(map); return new RegularImmutableBiMap<K, V>(immutableMap); } ImmutableBiMap(Map<K, V> delegate) { super(delegate); } public abstract ImmutableBiMap<V, K> inverse(); @Override public ImmutableSet<V> values() { return inverse().keySet(); } public final V forcePut(K key, V value) { throw new UnsupportedOperationException(); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableBiMap.java
Java
asf20
3,531
/* * 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.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; } @Override public UnmodifiableIterator<C> iterator() { 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; } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/EmptyContiguousSet.java
Java
asf20
2,569
/* * 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 static com.google.common.collect.CollectPreconditions.checkNonnegative; import static com.google.common.collect.CollectPreconditions.checkRemove; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.common.primitives.Ints; import java.io.Serializable; import java.util.Comparator; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.NoSuchElementException; import javax.annotation.Nullable; /** * A multiset which maintains the ordering of its elements, according to either their natural order * or an explicit {@link Comparator}. In all cases, this implementation uses * {@link Comparable#compareTo} or {@link Comparator#compare} instead of {@link Object#equals} to * determine equivalence of instances. * * <p><b>Warning:</b> The comparison must be <i>consistent with equals</i> as explained by the * {@link Comparable} class specification. Otherwise, the resulting multiset will violate the * {@link java.util.Collection} contract, which is specified in terms of {@link Object#equals}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset"> * {@code Multiset}</a>. * * @author Louis Wasserman * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class TreeMultiset<E> extends AbstractSortedMultiset<E> implements Serializable { /** * Creates a new, empty multiset, sorted according to the elements' natural order. All elements * inserted into the multiset must implement the {@code Comparable} interface. Furthermore, all * such elements must be <i>mutually comparable</i>: {@code e1.compareTo(e2)} must not throw a * {@code ClassCastException} for any elements {@code e1} and {@code e2} in the multiset. If the * user attempts to add an element to the multiset that violates this constraint (for example, * the user attempts to add a string element to a set whose elements are integers), the * {@code add(Object)} call will throw a {@code ClassCastException}. * * <p>The type specification is {@code <E extends Comparable>}, instead of the more specific * {@code <E extends Comparable<? super E>>}, to support classes defined without generics. */ public static <E extends Comparable> TreeMultiset<E> create() { return new TreeMultiset<E>(Ordering.natural()); } /** * Creates a new, empty multiset, sorted according to the specified comparator. All elements * inserted into the multiset must be <i>mutually comparable</i> by the specified comparator: * {@code comparator.compare(e1, * e2)} must not throw a {@code ClassCastException} for any elements {@code e1} and {@code e2} in * the multiset. If the user attempts to add an element to the multiset that violates this * constraint, the {@code add(Object)} call will throw a {@code ClassCastException}. * * @param comparator * the comparator that will be used to sort this multiset. A null value indicates that * the elements' <i>natural ordering</i> should be used. */ @SuppressWarnings("unchecked") public static <E> TreeMultiset<E> create(@Nullable Comparator<? super E> comparator) { return (comparator == null) ? new TreeMultiset<E>((Comparator) Ordering.natural()) : new TreeMultiset<E>(comparator); } /** * Creates an empty multiset containing the given initial elements, sorted according to the * elements' natural order. * * <p>This implementation is highly efficient when {@code elements} is itself a {@link Multiset}. * * <p>The type specification is {@code <E extends Comparable>}, instead of the more specific * {@code <E extends Comparable<? super E>>}, to support classes defined without generics. */ public static <E extends Comparable> TreeMultiset<E> create(Iterable<? extends E> elements) { TreeMultiset<E> multiset = create(); Iterables.addAll(multiset, elements); return multiset; } private final transient Reference<AvlNode<E>> rootReference; private final transient GeneralRange<E> range; private final transient AvlNode<E> header; TreeMultiset(Reference<AvlNode<E>> rootReference, GeneralRange<E> range, AvlNode<E> endLink) { super(range.comparator()); this.rootReference = rootReference; this.range = range; this.header = endLink; } TreeMultiset(Comparator<? super E> comparator) { super(comparator); this.range = GeneralRange.all(comparator); this.header = new AvlNode<E>(null, 1); successor(header, header); this.rootReference = new Reference<AvlNode<E>>(); } /** * A function which can be summed across a subtree. */ private enum Aggregate { SIZE { @Override int nodeAggregate(AvlNode<?> node) { return node.elemCount; } @Override long treeAggregate(@Nullable AvlNode<?> root) { return (root == null) ? 0 : root.totalCount; } }, DISTINCT { @Override int nodeAggregate(AvlNode<?> node) { return 1; } @Override long treeAggregate(@Nullable AvlNode<?> root) { return (root == null) ? 0 : root.distinctElements; } }; abstract int nodeAggregate(AvlNode<?> node); abstract long treeAggregate(@Nullable AvlNode<?> root); } private long aggregateForEntries(Aggregate aggr) { AvlNode<E> root = rootReference.get(); long total = aggr.treeAggregate(root); if (range.hasLowerBound()) { total -= aggregateBelowRange(aggr, root); } if (range.hasUpperBound()) { total -= aggregateAboveRange(aggr, root); } return total; } private long aggregateBelowRange(Aggregate aggr, @Nullable AvlNode<E> node) { if (node == null) { return 0; } int cmp = comparator().compare(range.getLowerEndpoint(), node.elem); if (cmp < 0) { return aggregateBelowRange(aggr, node.left); } else if (cmp == 0) { switch (range.getLowerBoundType()) { case OPEN: return aggr.nodeAggregate(node) + aggr.treeAggregate(node.left); case CLOSED: return aggr.treeAggregate(node.left); default: throw new AssertionError(); } } else { return aggr.treeAggregate(node.left) + aggr.nodeAggregate(node) + aggregateBelowRange(aggr, node.right); } } private long aggregateAboveRange(Aggregate aggr, @Nullable AvlNode<E> node) { if (node == null) { return 0; } int cmp = comparator().compare(range.getUpperEndpoint(), node.elem); if (cmp > 0) { return aggregateAboveRange(aggr, node.right); } else if (cmp == 0) { switch (range.getUpperBoundType()) { case OPEN: return aggr.nodeAggregate(node) + aggr.treeAggregate(node.right); case CLOSED: return aggr.treeAggregate(node.right); default: throw new AssertionError(); } } else { return aggr.treeAggregate(node.right) + aggr.nodeAggregate(node) + aggregateAboveRange(aggr, node.left); } } @Override public int size() { return Ints.saturatedCast(aggregateForEntries(Aggregate.SIZE)); } @Override int distinctElements() { return Ints.saturatedCast(aggregateForEntries(Aggregate.DISTINCT)); } @Override public int count(@Nullable Object element) { try { @SuppressWarnings("unchecked") E e = (E) element; AvlNode<E> root = rootReference.get(); if (!range.contains(e) || root == null) { return 0; } return root.count(comparator(), e); } catch (ClassCastException e) { return 0; } catch (NullPointerException e) { return 0; } } @Override public int add(@Nullable E element, int occurrences) { checkNonnegative(occurrences, "occurrences"); if (occurrences == 0) { return count(element); } checkArgument(range.contains(element)); AvlNode<E> root = rootReference.get(); if (root == null) { comparator().compare(element, element); AvlNode<E> newRoot = new AvlNode<E>(element, occurrences); successor(header, newRoot, header); rootReference.checkAndSet(root, newRoot); return 0; } int[] result = new int[1]; // used as a mutable int reference to hold result AvlNode<E> newRoot = root.add(comparator(), element, occurrences, result); rootReference.checkAndSet(root, newRoot); return result[0]; } @Override public int remove(@Nullable Object element, int occurrences) { checkNonnegative(occurrences, "occurrences"); if (occurrences == 0) { return count(element); } AvlNode<E> root = rootReference.get(); int[] result = new int[1]; // used as a mutable int reference to hold result AvlNode<E> newRoot; try { @SuppressWarnings("unchecked") E e = (E) element; if (!range.contains(e) || root == null) { return 0; } newRoot = root.remove(comparator(), e, occurrences, result); } catch (ClassCastException e) { return 0; } catch (NullPointerException e) { return 0; } rootReference.checkAndSet(root, newRoot); return result[0]; } @Override public int setCount(@Nullable E element, int count) { checkNonnegative(count, "count"); if (!range.contains(element)) { checkArgument(count == 0); return 0; } AvlNode<E> root = rootReference.get(); if (root == null) { if (count > 0) { add(element, count); } return 0; } int[] result = new int[1]; // used as a mutable int reference to hold result AvlNode<E> newRoot = root.setCount(comparator(), element, count, result); rootReference.checkAndSet(root, newRoot); return result[0]; } @Override public boolean setCount(@Nullable E element, int oldCount, int newCount) { checkNonnegative(newCount, "newCount"); checkNonnegative(oldCount, "oldCount"); checkArgument(range.contains(element)); AvlNode<E> root = rootReference.get(); if (root == null) { if (oldCount == 0) { if (newCount > 0) { add(element, newCount); } return true; } else { return false; } } int[] result = new int[1]; // used as a mutable int reference to hold result AvlNode<E> newRoot = root.setCount(comparator(), element, oldCount, newCount, result); rootReference.checkAndSet(root, newRoot); return result[0] == oldCount; } private Entry<E> wrapEntry(final AvlNode<E> baseEntry) { return new Multisets.AbstractEntry<E>() { @Override public E getElement() { return baseEntry.getElement(); } @Override public int getCount() { int result = baseEntry.getCount(); if (result == 0) { return count(getElement()); } else { return result; } } }; } /** * Returns the first node in the tree that is in range. */ @Nullable private AvlNode<E> firstNode() { AvlNode<E> root = rootReference.get(); if (root == null) { return null; } AvlNode<E> node; if (range.hasLowerBound()) { E endpoint = range.getLowerEndpoint(); node = rootReference.get().ceiling(comparator(), endpoint); if (node == null) { return null; } if (range.getLowerBoundType() == BoundType.OPEN && comparator().compare(endpoint, node.getElement()) == 0) { node = node.succ; } } else { node = header.succ; } return (node == header || !range.contains(node.getElement())) ? null : node; } @Nullable private AvlNode<E> lastNode() { AvlNode<E> root = rootReference.get(); if (root == null) { return null; } AvlNode<E> node; if (range.hasUpperBound()) { E endpoint = range.getUpperEndpoint(); node = rootReference.get().floor(comparator(), endpoint); if (node == null) { return null; } if (range.getUpperBoundType() == BoundType.OPEN && comparator().compare(endpoint, node.getElement()) == 0) { node = node.pred; } } else { node = header.pred; } return (node == header || !range.contains(node.getElement())) ? null : node; } @Override Iterator<Entry<E>> entryIterator() { return new Iterator<Entry<E>>() { AvlNode<E> current = firstNode(); Entry<E> prevEntry; @Override public boolean hasNext() { if (current == null) { return false; } else if (range.tooHigh(current.getElement())) { current = null; return false; } else { return true; } } @Override public Entry<E> next() { if (!hasNext()) { throw new NoSuchElementException(); } Entry<E> result = wrapEntry(current); prevEntry = result; if (current.succ == header) { current = null; } else { current = current.succ; } return result; } @Override public void remove() { checkRemove(prevEntry != null); setCount(prevEntry.getElement(), 0); prevEntry = null; } }; } @Override Iterator<Entry<E>> descendingEntryIterator() { return new Iterator<Entry<E>>() { AvlNode<E> current = lastNode(); Entry<E> prevEntry = null; @Override public boolean hasNext() { if (current == null) { return false; } else if (range.tooLow(current.getElement())) { current = null; return false; } else { return true; } } @Override public Entry<E> next() { if (!hasNext()) { throw new NoSuchElementException(); } Entry<E> result = wrapEntry(current); prevEntry = result; if (current.pred == header) { current = null; } else { current = current.pred; } return result; } @Override public void remove() { checkRemove(prevEntry != null); setCount(prevEntry.getElement(), 0); prevEntry = null; } }; } @Override public SortedMultiset<E> headMultiset(@Nullable E upperBound, BoundType boundType) { return new TreeMultiset<E>(rootReference, range.intersect(GeneralRange.upTo( comparator(), upperBound, boundType)), header); } @Override public SortedMultiset<E> tailMultiset(@Nullable E lowerBound, BoundType boundType) { return new TreeMultiset<E>(rootReference, range.intersect(GeneralRange.downTo( comparator(), lowerBound, boundType)), header); } static int distinctElements(@Nullable AvlNode<?> node) { return (node == null) ? 0 : node.distinctElements; } private static final class Reference<T> { @Nullable private T value; @Nullable public T get() { return value; } public void checkAndSet(@Nullable T expected, T newValue) { if (value != expected) { throw new ConcurrentModificationException(); } value = newValue; } } private static final class AvlNode<E> extends Multisets.AbstractEntry<E> { @Nullable private final E elem; // elemCount is 0 iff this node has been deleted. private int elemCount; private int distinctElements; private long totalCount; private int height; private AvlNode<E> left; private AvlNode<E> right; private AvlNode<E> pred; private AvlNode<E> succ; AvlNode(@Nullable E elem, int elemCount) { checkArgument(elemCount > 0); this.elem = elem; this.elemCount = elemCount; this.totalCount = elemCount; this.distinctElements = 1; this.height = 1; this.left = null; this.right = null; } public int count(Comparator<? super E> comparator, E e) { int cmp = comparator.compare(e, elem); if (cmp < 0) { return (left == null) ? 0 : left.count(comparator, e); } else if (cmp > 0) { return (right == null) ? 0 : right.count(comparator, e); } else { return elemCount; } } private AvlNode<E> addRightChild(E e, int count) { right = new AvlNode<E>(e, count); successor(this, right, succ); height = Math.max(2, height); distinctElements++; totalCount += count; return this; } private AvlNode<E> addLeftChild(E e, int count) { left = new AvlNode<E>(e, count); successor(pred, left, this); height = Math.max(2, height); distinctElements++; totalCount += count; return this; } AvlNode<E> add(Comparator<? super E> comparator, @Nullable E e, int count, int[] result) { /* * It speeds things up considerably to unconditionally add count to totalCount here, * but that destroys failure atomicity in the case of count overflow. =( */ int cmp = comparator.compare(e, elem); if (cmp < 0) { AvlNode<E> initLeft = left; if (initLeft == null) { result[0] = 0; return addLeftChild(e, count); } int initHeight = initLeft.height; left = initLeft.add(comparator, e, count, result); if (result[0] == 0) { distinctElements++; } this.totalCount += count; return (left.height == initHeight) ? this : rebalance(); } else if (cmp > 0) { AvlNode<E> initRight = right; if (initRight == null) { result[0] = 0; return addRightChild(e, count); } int initHeight = initRight.height; right = initRight.add(comparator, e, count, result); if (result[0] == 0) { distinctElements++; } this.totalCount += count; return (right.height == initHeight) ? this : rebalance(); } // adding count to me! No rebalance possible. result[0] = elemCount; long resultCount = (long) elemCount + count; checkArgument(resultCount <= Integer.MAX_VALUE); this.elemCount += count; this.totalCount += count; return this; } AvlNode<E> remove(Comparator<? super E> comparator, @Nullable E e, int count, int[] result) { int cmp = comparator.compare(e, elem); if (cmp < 0) { AvlNode<E> initLeft = left; if (initLeft == null) { result[0] = 0; return this; } left = initLeft.remove(comparator, e, count, result); if (result[0] > 0) { if (count >= result[0]) { this.distinctElements--; this.totalCount -= result[0]; } else { this.totalCount -= count; } } return (result[0] == 0) ? this : rebalance(); } else if (cmp > 0) { AvlNode<E> initRight = right; if (initRight == null) { result[0] = 0; return this; } right = initRight.remove(comparator, e, count, result); if (result[0] > 0) { if (count >= result[0]) { this.distinctElements--; this.totalCount -= result[0]; } else { this.totalCount -= count; } } return rebalance(); } // removing count from me! result[0] = elemCount; if (count >= elemCount) { return deleteMe(); } else { this.elemCount -= count; this.totalCount -= count; return this; } } AvlNode<E> setCount(Comparator<? super E> comparator, @Nullable E e, int count, int[] result) { int cmp = comparator.compare(e, elem); if (cmp < 0) { AvlNode<E> initLeft = left; if (initLeft == null) { result[0] = 0; return (count > 0) ? addLeftChild(e, count) : this; } left = initLeft.setCount(comparator, e, count, result); if (count == 0 && result[0] != 0) { this.distinctElements--; } else if (count > 0 && result[0] == 0) { this.distinctElements++; } this.totalCount += count - result[0]; return rebalance(); } else if (cmp > 0) { AvlNode<E> initRight = right; if (initRight == null) { result[0] = 0; return (count > 0) ? addRightChild(e, count) : this; } right = initRight.setCount(comparator, e, count, result); if (count == 0 && result[0] != 0) { this.distinctElements--; } else if (count > 0 && result[0] == 0) { this.distinctElements++; } this.totalCount += count - result[0]; return rebalance(); } // setting my count result[0] = elemCount; if (count == 0) { return deleteMe(); } this.totalCount += count - elemCount; this.elemCount = count; return this; } AvlNode<E> setCount( Comparator<? super E> comparator, @Nullable E e, int expectedCount, int newCount, int[] result) { int cmp = comparator.compare(e, elem); if (cmp < 0) { AvlNode<E> initLeft = left; if (initLeft == null) { result[0] = 0; if (expectedCount == 0 && newCount > 0) { return addLeftChild(e, newCount); } return this; } left = initLeft.setCount(comparator, e, expectedCount, newCount, result); if (result[0] == expectedCount) { if (newCount == 0 && result[0] != 0) { this.distinctElements--; } else if (newCount > 0 && result[0] == 0) { this.distinctElements++; } this.totalCount += newCount - result[0]; } return rebalance(); } else if (cmp > 0) { AvlNode<E> initRight = right; if (initRight == null) { result[0] = 0; if (expectedCount == 0 && newCount > 0) { return addRightChild(e, newCount); } return this; } right = initRight.setCount(comparator, e, expectedCount, newCount, result); if (result[0] == expectedCount) { if (newCount == 0 && result[0] != 0) { this.distinctElements--; } else if (newCount > 0 && result[0] == 0) { this.distinctElements++; } this.totalCount += newCount - result[0]; } return rebalance(); } // setting my count result[0] = elemCount; if (expectedCount == elemCount) { if (newCount == 0) { return deleteMe(); } this.totalCount += newCount - elemCount; this.elemCount = newCount; } return this; } private AvlNode<E> deleteMe() { int oldElemCount = this.elemCount; this.elemCount = 0; successor(pred, succ); if (left == null) { return right; } else if (right == null) { return left; } else if (left.height >= right.height) { AvlNode<E> newTop = pred; // newTop is the maximum node in my left subtree newTop.left = left.removeMax(newTop); newTop.right = right; newTop.distinctElements = distinctElements - 1; newTop.totalCount = totalCount - oldElemCount; return newTop.rebalance(); } else { AvlNode<E> newTop = succ; newTop.right = right.removeMin(newTop); newTop.left = left; newTop.distinctElements = distinctElements - 1; newTop.totalCount = totalCount - oldElemCount; return newTop.rebalance(); } } // Removes the minimum node from this subtree to be reused elsewhere private AvlNode<E> removeMin(AvlNode<E> node) { if (left == null) { return right; } else { left = left.removeMin(node); distinctElements--; totalCount -= node.elemCount; return rebalance(); } } // Removes the maximum node from this subtree to be reused elsewhere private AvlNode<E> removeMax(AvlNode<E> node) { if (right == null) { return left; } else { right = right.removeMax(node); distinctElements--; totalCount -= node.elemCount; return rebalance(); } } private void recomputeMultiset() { this.distinctElements = 1 + TreeMultiset.distinctElements(left) + TreeMultiset.distinctElements(right); this.totalCount = elemCount + totalCount(left) + totalCount(right); } private void recomputeHeight() { this.height = 1 + Math.max(height(left), height(right)); } private void recompute() { recomputeMultiset(); recomputeHeight(); } private AvlNode<E> rebalance() { switch (balanceFactor()) { case -2: if (right.balanceFactor() > 0) { right = right.rotateRight(); } return rotateLeft(); case 2: if (left.balanceFactor() < 0) { left = left.rotateLeft(); } return rotateRight(); default: recomputeHeight(); return this; } } private int balanceFactor() { return height(left) - height(right); } private AvlNode<E> rotateLeft() { checkState(right != null); AvlNode<E> newTop = right; this.right = newTop.left; newTop.left = this; newTop.totalCount = this.totalCount; newTop.distinctElements = this.distinctElements; this.recompute(); newTop.recomputeHeight(); return newTop; } private AvlNode<E> rotateRight() { checkState(left != null); AvlNode<E> newTop = left; this.left = newTop.right; newTop.right = this; newTop.totalCount = this.totalCount; newTop.distinctElements = this.distinctElements; this.recompute(); newTop.recomputeHeight(); return newTop; } private static long totalCount(@Nullable AvlNode<?> node) { return (node == null) ? 0 : node.totalCount; } private static int height(@Nullable AvlNode<?> node) { return (node == null) ? 0 : node.height; } @Nullable private AvlNode<E> ceiling(Comparator<? super E> comparator, E e) { int cmp = comparator.compare(e, elem); if (cmp < 0) { return (left == null) ? this : Objects.firstNonNull(left.ceiling(comparator, e), this); } else if (cmp == 0) { return this; } else { return (right == null) ? null : right.ceiling(comparator, e); } } @Nullable private AvlNode<E> floor(Comparator<? super E> comparator, E e) { int cmp = comparator.compare(e, elem); if (cmp > 0) { return (right == null) ? this : Objects.firstNonNull(right.floor(comparator, e), this); } else if (cmp == 0) { return this; } else { return (left == null) ? null : left.floor(comparator, e); } } @Override public E getElement() { return elem; } @Override public int getCount() { return elemCount; } @Override public String toString() { return Multisets.immutableEntry(getElement(), getCount()).toString(); } } private static <T> void successor(AvlNode<T> a, AvlNode<T> b) { a.succ = b; b.pred = a; } private static <T> void successor(AvlNode<T> a, AvlNode<T> b, AvlNode<T> c) { successor(a, b); successor(b, c); } /* * TODO(jlevy): Decide whether entrySet() should return entries with an equals() method that * calls the comparator to compare the two keys. If that change is made, * AbstractMultiset.equals() can simply check whether two multisets have equal entry sets. */ }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/TreeMultiset.java
Java
asf20
28,663
/* * 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 java.util.Collections.unmodifiableList; import java.util.List; /** * GWT emulated version of {@link RegularImmutableList}. * * @author Hayward Chan */ class RegularImmutableList<E> extends ForwardingImmutableList<E> { private final List<E> delegate; RegularImmutableList(List<E> delegate) { // TODO(cpovirk): avoid redundant unmodifiableList wrapping this.delegate = unmodifiableList(delegate); } @Override List<E> delegateList() { return delegate; } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/RegularImmutableList.java
Java
asf20
1,135
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.collect.CollectPreconditions.checkNonnegative; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.VisibleForTesting; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; /** * 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)); checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey"); 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(); } } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ArrayListMultimap.java
Java
asf20
4,958
/* * 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 java.util.Collections; /** * GWT emulation of {@link EmptyImmutableBiMap}. * * @author Hayward Chan */ @SuppressWarnings("serial") final class EmptyImmutableBiMap extends ImmutableBiMap<Object, Object> { static final EmptyImmutableBiMap INSTANCE = new EmptyImmutableBiMap(); private EmptyImmutableBiMap() { super(Collections.emptyMap()); } @Override public ImmutableBiMap<Object, Object> inverse() { return this; } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/EmptyImmutableBiMap.java
Java
asf20
1,086
/* * 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 java.util.NoSuchElementException; /** * 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); } @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); } @Override public ContiguousSet<C> tailSet(C fromElement) { return tailSetImpl(checkNotNull(fromElement), true); } /* * 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(); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ContiguousSet.java
Java
asf20
5,757
/* * 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.VisibleForTesting; import java.io.Serializable; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; 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. } 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; } 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; } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/Synchronized.java
Java
asf20
32,566
/* * 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 java.util.Map; /** * GWT emulation of {@link ImmutableEnumMap}. The type parameter is not bounded * by {@code Enum<E>} to avoid code-size bloat. * * @author Hayward Chan */ final class ImmutableEnumMap<K, V> extends ForwardingImmutableMap<K, V> { static <K, V> ImmutableMap<K, V> asImmutable(Map<K, V> map) { for (Map.Entry<K, V> entry : checkNotNull(map).entrySet()) { checkNotNull(entry.getKey()); checkNotNull(entry.getValue()); } return new ImmutableEnumMap<K, V>(map); } ImmutableEnumMap(Map<? extends K, ? extends V> delegate) { super(WellBehavedMap.wrap(delegate)); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableEnumMap.java
Java
asf20
1,331
/* * 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.HashMap; /** * Multiset implementation backed by a {@link HashMap}. * * @author Kevin Bourrillion * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public final class HashMultiset<E> extends AbstractMapBasedMultiset<E> { /** * Creates a new, empty {@code HashMultiset} using the default initial * capacity. */ public static <E> HashMultiset<E> create() { return new HashMultiset<E>(); } /** * Creates a new, empty {@code HashMultiset} with the specified expected * number of distinct elements. * * @param distinctElements the expected number of distinct elements * @throws IllegalArgumentException if {@code distinctElements} is negative */ public static <E> HashMultiset<E> create(int distinctElements) { return new HashMultiset<E>(distinctElements); } /** * Creates a new {@code HashMultiset} containing the specified elements. * * <p>This implementation is highly efficient when {@code elements} is itself * a {@link Multiset}. * * @param elements the elements that the multiset should contain */ public static <E> HashMultiset<E> create(Iterable<? extends E> elements) { HashMultiset<E> multiset = create(Multisets.inferDistinctElements(elements)); Iterables.addAll(multiset, elements); return multiset; } private HashMultiset() { super(new HashMap<E, Count>()); } private HashMultiset(int distinctElements) { super(Maps.<E, Count>newHashMapWithExpectedSize(distinctElements)); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/HashMultiset.java
Java
asf20
2,302
/* * 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.collect.Multisets.UnmodifiableMultiset; import java.util.Collections; import java.util.Comparator; import java.util.SortedSet; /** * Implementation of {@link Multisets#unmodifiableSortedMultiset(SortedMultiset)} * for GWT. * * @author Louis Wasserman */ final class UnmodifiableSortedMultiset<E> extends UnmodifiableMultiset<E> implements SortedMultiset<E> { UnmodifiableSortedMultiset(SortedMultiset<E> delegate) { super(delegate); } @Override protected SortedMultiset<E> delegate() { return (SortedMultiset<E>) super.delegate(); } @Override public Comparator<? super E> comparator() { return delegate().comparator(); } @Override SortedSet<E> createElementSet() { return Collections.unmodifiableSortedSet(delegate().elementSet()); } @Override public SortedSet<E> elementSet() { return (SortedSet<E>) super.elementSet(); } private transient UnmodifiableSortedMultiset<E> descendingMultiset; @Override public SortedMultiset<E> descendingMultiset() { UnmodifiableSortedMultiset<E> result = descendingMultiset; if (result == null) { result = new UnmodifiableSortedMultiset<E>( delegate().descendingMultiset()); result.descendingMultiset = this; return descendingMultiset = result; } return result; } @Override public Entry<E> firstEntry() { return delegate().firstEntry(); } @Override public Entry<E> lastEntry() { return delegate().lastEntry(); } @Override public Entry<E> pollFirstEntry() { throw new UnsupportedOperationException(); } @Override public Entry<E> pollLastEntry() { throw new UnsupportedOperationException(); } @Override public SortedMultiset<E> headMultiset(E upperBound, BoundType boundType) { return Multisets.unmodifiableSortedMultiset( delegate().headMultiset(upperBound, boundType)); } @Override public SortedMultiset<E> subMultiset( E lowerBound, BoundType lowerBoundType, E upperBound, BoundType upperBoundType) { return Multisets.unmodifiableSortedMultiset(delegate().subMultiset( lowerBound, lowerBoundType, upperBound, upperBoundType)); } @Override public SortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) { return Multisets.unmodifiableSortedMultiset( delegate().tailMultiset(lowerBound, boundType)); } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/UnmodifiableSortedMultiset.java
Java
asf20
3,090
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.CollectPreconditions.checkEntryNotNull; import static com.google.common.collect.Iterables.getOnlyElement; import java.io.Serializable; import java.util.Collections; import java.util.EnumMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.annotation.Nullable; /** * GWT emulation of {@link ImmutableMap}. For non sorted maps, it is a thin * wrapper around {@link java.util.Collections#emptyMap()}, {@link * Collections#singletonMap(Object, Object)} and {@link java.util.LinkedHashMap} * for empty, singleton and regular maps respectively. For sorted maps, it's * a thin wrapper around {@link java.util.TreeMap}. * * @see ImmutableSortedMap * * @author Hayward Chan */ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable { ImmutableMap() {} public static <K, V> ImmutableMap<K, V> of() { return ImmutableBiMap.of(); } public static <K, V> ImmutableMap<K, V> of(K k1, V v1) { return ImmutableBiMap.of(k1, v1); } public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2) { return new RegularImmutableMap<K, V>(entryOf(k1, v1), entryOf(k2, v2)); } public static <K, V> ImmutableMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3) { return new RegularImmutableMap<K, V>( entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3)); } public static <K, V> ImmutableMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { return new RegularImmutableMap<K, V>( entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4)); } public static <K, V> ImmutableMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { return new RegularImmutableMap<K, V>(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5)); } // looking for of() with > 5 entries? Use the builder instead. public static <K, V> Builder<K, V> builder() { return new Builder<K, V>(); } static <K, V> Entry<K, V> entryOf(K key, V value) { checkEntryNotNull(key, value); return Maps.immutableEntry(key, value); } public static class Builder<K, V> { final List<Entry<K, V>> entries = Lists.newArrayList(); public Builder() {} public Builder<K, V> put(K key, V value) { entries.add(entryOf(key, value)); return this; } public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { if (entry instanceof ImmutableEntry) { checkNotNull(entry.getKey()); checkNotNull(entry.getValue()); @SuppressWarnings("unchecked") // all supported methods are covariant Entry<K, V> immutableEntry = (Entry<K, V>) entry; entries.add(immutableEntry); } else { entries.add(entryOf((K) entry.getKey(), (V) entry.getValue())); } return this; } public Builder<K, V> putAll(Map<? extends K, ? extends V> map) { for (Entry<? extends K, ? extends V> entry : map.entrySet()) { put(entry.getKey(), entry.getValue()); } return this; } public ImmutableMap<K, V> build() { return fromEntryList(entries); } private static <K, V> ImmutableMap<K, V> fromEntryList( List<Entry<K, V>> entries) { int size = entries.size(); switch (size) { case 0: return of(); case 1: Entry<K, V> entry = getOnlyElement(entries); return of(entry.getKey(), entry.getValue()); default: @SuppressWarnings("unchecked") Entry<K, V>[] entryArray = entries.toArray(new Entry[entries.size()]); return new RegularImmutableMap<K, V>(entryArray); } } } public static <K, V> ImmutableMap<K, V> copyOf( Map<? extends K, ? extends V> map) { if ((map instanceof ImmutableMap) && !(map instanceof ImmutableSortedMap)) { @SuppressWarnings("unchecked") // safe since map is not writable ImmutableMap<K, V> kvMap = (ImmutableMap<K, V>) map; return kvMap; } else if (map instanceof EnumMap) { EnumMap<?, ?> enumMap = (EnumMap<?, ?>) map; for (Map.Entry<?, ?> entry : enumMap.entrySet()) { checkNotNull(entry.getKey()); checkNotNull(entry.getValue()); } @SuppressWarnings("unchecked") // immutable collections are safe for covariant casts ImmutableMap<K, V> result = ImmutableEnumMap.asImmutable(new EnumMap(enumMap)); return result; } int size = map.size(); switch (size) { case 0: return of(); case 1: Entry<? extends K, ? extends V> entry = getOnlyElement(map.entrySet()); return ImmutableMap.<K, V>of(entry.getKey(), entry.getValue()); default: Map<K, V> orderPreservingCopy = Maps.newLinkedHashMap(); for (Entry<? extends K, ? extends V> e : map.entrySet()) { orderPreservingCopy.put( checkNotNull(e.getKey()), checkNotNull(e.getValue())); } return new RegularImmutableMap<K, V>(orderPreservingCopy); } } abstract boolean isPartialView(); public final V put(K k, V v) { throw new UnsupportedOperationException(); } public final V remove(Object o) { throw new UnsupportedOperationException(); } public final void putAll(Map<? extends K, ? extends V> map) { throw new UnsupportedOperationException(); } public final void clear() { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { return size() == 0; } @Override public boolean containsKey(@Nullable Object key) { return get(key) != null; } @Override public boolean containsValue(@Nullable Object value) { return values().contains(value); } private transient ImmutableSet<Entry<K, V>> cachedEntrySet = null; public final ImmutableSet<Entry<K, V>> entrySet() { if (cachedEntrySet != null) { return cachedEntrySet; } return cachedEntrySet = createEntrySet(); } abstract ImmutableSet<Entry<K, V>> createEntrySet(); private transient ImmutableSet<K> cachedKeySet = null; public ImmutableSet<K> keySet() { if (cachedKeySet != null) { return cachedKeySet; } return cachedKeySet = createKeySet(); } ImmutableSet<K> createKeySet() { return new ImmutableMapKeySet<K, V>(this); } private transient ImmutableCollection<V> cachedValues = null; public ImmutableCollection<V> values() { if (cachedValues != null) { return cachedValues; } return cachedValues = createValues(); } // esnickell is editing here // cached so that this.multimapView().inverse() only computes inverse once private transient ImmutableSetMultimap<K, V> multimapView; public ImmutableSetMultimap<K, V> asMultimap() { ImmutableSetMultimap<K, V> result = multimapView; return (result == null) ? (multimapView = createMultimapView()) : result; } private ImmutableSetMultimap<K, V> createMultimapView() { ImmutableMap<K, ImmutableSet<V>> map = viewValuesAsImmutableSet(); return new ImmutableSetMultimap<K, V>(map, map.size(), null); } private ImmutableMap<K, ImmutableSet<V>> viewValuesAsImmutableSet() { final Map<K, V> outer = this; return new ImmutableMap<K, ImmutableSet<V>>() { @Override public int size() { return outer.size(); } @Override public ImmutableSet<V> get(@Nullable Object key) { V outerValue = outer.get(key); return outerValue == null ? null : ImmutableSet.of(outerValue); } @Override ImmutableSet<Entry<K, ImmutableSet<V>>> createEntrySet() { return new ImmutableSet<Entry<K, ImmutableSet<V>>>() { @Override public UnmodifiableIterator<Entry<K, ImmutableSet<V>>> iterator() { final Iterator<Entry<K,V>> outerEntryIterator = outer.entrySet().iterator(); return new UnmodifiableIterator<Entry<K, ImmutableSet<V>>>() { @Override public boolean hasNext() { return outerEntryIterator.hasNext(); } @Override public Entry<K, ImmutableSet<V>> next() { final Entry<K, V> outerEntry = outerEntryIterator.next(); return new AbstractMapEntry<K, ImmutableSet<V>>() { @Override public K getKey() { return outerEntry.getKey(); } @Override public ImmutableSet<V> getValue() { return ImmutableSet.of(outerEntry.getValue()); } }; } }; } @Override boolean isPartialView() { return false; } @Override public int size() { return outer.size(); } }; } @Override boolean isPartialView() { return false; } }; } ImmutableCollection<V> createValues() { return new ImmutableMapValues<K, V>(this); } @Override public boolean equals(@Nullable Object object) { return Maps.equalsImpl(this, object); } @Override public int hashCode() { // not caching hash code since it could change if map values are mutable // in a way that modifies their hash codes return entrySet().hashCode(); } @Override public String toString() { return Maps.toStringImpl(this); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableMap.java
Java
asf20
10,220
/* * 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 java.util.Comparator; /** * GWT emulation of {@link EmptyImmutableSortedSet}. * * @author Hayward Chan */ class EmptyImmutableSortedSet<E> extends ImmutableSortedSet<E> { EmptyImmutableSortedSet(Comparator<? super E> comparator) { super(Sets.newTreeSet(comparator)); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/EmptyImmutableSortedSet.java
Java
asf20
929
/* * 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.checkElementIndex; 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.Objects; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * Fixed-size {@link Table} implementation backed by a two-dimensional array. * * <p>The allowed row and column keys must be supplied when the table is * created. The table always contains a mapping for every row key / column pair. * The value corresponding to a given row and column is null unless another * value is provided. * * <p>The table's size is constant: the product of the number of supplied row * keys and the number of supplied column keys. The {@code remove} and {@code * clear} methods are not supported by the table or its views. The {@link * #erase} and {@link #eraseAll} methods may be used instead. * * <p>The ordering of the row and column keys provided when the table is * constructed determines the iteration ordering across rows and columns in the * table's views. None of the view iterators support {@link Iterator#remove}. * If the table is modified after an iterator is created, the iterator remains * valid. * * <p>This class requires less memory than the {@link HashBasedTable} and {@link * TreeBasedTable} implementations, except when the table is sparse. * * <p>Null row keys or column keys are not permitted. * * <p>This class provides methods involving the underlying array structure, * where the array indices correspond to the position of a row or column in the * lists of allowed keys and values. See the {@link #at}, {@link #set}, {@link * #toArray}, {@link #rowKeyList}, and {@link #columnKeyList} methods for more * details. * * <p>Note that this implementation is not synchronized. If multiple threads * access the same cell of an {@code ArrayTable} concurrently and one of the * threads modifies its value, there is no guarantee that the new value will be * fully visible to the other threads. To guarantee that modifications are * visible, synchronize access to the table. Unlike other {@code Table} * implementations, synchronization is unnecessary between a thread that writes * to one cell and a thread that reads from another. * * <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 10.0 */ @Beta @GwtCompatible(emulated = true) public final class ArrayTable<R, C, V> extends AbstractTable<R, C, V> implements Serializable { /** * Creates an empty {@code ArrayTable}. * * @param rowKeys row keys that may be stored in the generated table * @param columnKeys column keys that may be stored in the generated table * @throws NullPointerException if any of the provided keys is null * @throws IllegalArgumentException if {@code rowKeys} or {@code columnKeys} * contains duplicates or is empty */ public static <R, C, V> ArrayTable<R, C, V> create( Iterable<? extends R> rowKeys, Iterable<? extends C> columnKeys) { return new ArrayTable<R, C, V>(rowKeys, columnKeys); } /* * TODO(jlevy): Add factory methods taking an Enum class, instead of an * iterable, to specify the allowed row keys and/or column keys. Note that * custom serialization logic is needed to support different enum sizes during * serialization and deserialization. */ /** * Creates an {@code ArrayTable} with the mappings in the provided table. * * <p>If {@code table} includes a mapping with row key {@code r} and a * separate mapping with column key {@code c}, the returned table contains a * mapping with row key {@code r} and column key {@code c}. If that row key / * column key pair in not in {@code table}, the pair maps to {@code null} in * the generated table. * * <p>The returned table allows subsequent {@code put} calls with the row keys * in {@code table.rowKeySet()} and the column keys in {@code * table.columnKeySet()}. Calling {@link #put} with other keys leads to an * {@code IllegalArgumentException}. * * <p>The ordering of {@code table.rowKeySet()} and {@code * table.columnKeySet()} determines the row and column iteration ordering of * the returned table. * * @throws NullPointerException if {@code table} has a null key * @throws IllegalArgumentException if the provided table is empty */ public static <R, C, V> ArrayTable<R, C, V> create(Table<R, C, V> table) { return (table instanceof ArrayTable<?, ?, ?>) ? new ArrayTable<R, C, V>((ArrayTable<R, C, V>) table) : new ArrayTable<R, C, V>(table); } private final ImmutableList<R> rowList; private final ImmutableList<C> columnList; // TODO(jlevy): Add getters returning rowKeyToIndex and columnKeyToIndex? private final ImmutableMap<R, Integer> rowKeyToIndex; private final ImmutableMap<C, Integer> columnKeyToIndex; private final V[][] array; private ArrayTable(Iterable<? extends R> rowKeys, Iterable<? extends C> columnKeys) { this.rowList = ImmutableList.copyOf(rowKeys); this.columnList = ImmutableList.copyOf(columnKeys); checkArgument(!rowList.isEmpty()); checkArgument(!columnList.isEmpty()); /* * TODO(jlevy): Support empty rowKeys or columnKeys? If we do, when * columnKeys is empty but rowKeys isn't, the table is empty but * containsRow() can return true and rowKeySet() isn't empty. */ rowKeyToIndex = index(rowList); columnKeyToIndex = index(columnList); @SuppressWarnings("unchecked") V[][] tmpArray = (V[][]) new Object[rowList.size()][columnList.size()]; array = tmpArray; // Necessary because in GWT the arrays are initialized with "undefined" instead of null. eraseAll(); } private static <E> ImmutableMap<E, Integer> index(List<E> list) { ImmutableMap.Builder<E, Integer> columnBuilder = ImmutableMap.builder(); for (int i = 0; i < list.size(); i++) { columnBuilder.put(list.get(i), i); } return columnBuilder.build(); } private ArrayTable(Table<R, C, V> table) { this(table.rowKeySet(), table.columnKeySet()); putAll(table); } private ArrayTable(ArrayTable<R, C, V> table) { rowList = table.rowList; columnList = table.columnList; rowKeyToIndex = table.rowKeyToIndex; columnKeyToIndex = table.columnKeyToIndex; @SuppressWarnings("unchecked") V[][] copy = (V[][]) new Object[rowList.size()][columnList.size()]; array = copy; // Necessary because in GWT the arrays are initialized with "undefined" instead of null. eraseAll(); for (int i = 0; i < rowList.size(); i++) { System.arraycopy(table.array[i], 0, copy[i], 0, table.array[i].length); } } private abstract static class ArrayMap<K, V> extends Maps.ImprovedAbstractMap<K, V> { private final ImmutableMap<K, Integer> keyIndex; private ArrayMap(ImmutableMap<K, Integer> keyIndex) { this.keyIndex = keyIndex; } @Override public Set<K> keySet() { return keyIndex.keySet(); } K getKey(int index) { return keyIndex.keySet().asList().get(index); } abstract String getKeyRole(); @Nullable abstract V getValue(int index); @Nullable abstract V setValue(int index, V newValue); @Override public int size() { return keyIndex.size(); } @Override public boolean isEmpty() { return keyIndex.isEmpty(); } @Override protected Set<Entry<K, V>> createEntrySet() { return new Maps.EntrySet<K, V>() { @Override Map<K, V> map() { return ArrayMap.this; } @Override public Iterator<Entry<K, V>> iterator() { return new AbstractIndexedListIterator<Entry<K, V>>(size()) { @Override protected Entry<K, V> get(final int index) { return new AbstractMapEntry<K, V>() { @Override public K getKey() { return ArrayMap.this.getKey(index); } @Override public V getValue() { return ArrayMap.this.getValue(index); } @Override public V setValue(V value) { return ArrayMap.this.setValue(index, value); } }; } }; } }; } // TODO(user): consider an optimized values() implementation @Override public boolean containsKey(@Nullable Object key) { return keyIndex.containsKey(key); } @Override public V get(@Nullable Object key) { Integer index = keyIndex.get(key); if (index == null) { return null; } else { return getValue(index); } } @Override public V put(K key, V value) { Integer index = keyIndex.get(key); if (index == null) { throw new IllegalArgumentException( getKeyRole() + " " + key + " not in " + keyIndex.keySet()); } return setValue(index, value); } @Override public V remove(Object key) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } } /** * Returns, as an immutable list, the row keys provided when the table was * constructed, including those that are mapped to null values only. */ public ImmutableList<R> rowKeyList() { return rowList; } /** * Returns, as an immutable list, the column keys provided when the table was * constructed, including those that are mapped to null values only. */ public ImmutableList<C> columnKeyList() { return columnList; } /** * Returns the value corresponding to the specified row and column indices. * The same value is returned by {@code * get(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex))}, but * this method runs more quickly. * * @param rowIndex position of the row key in {@link #rowKeyList()} * @param columnIndex position of the row key in {@link #columnKeyList()} * @return the value with the specified row and column * @throws IndexOutOfBoundsException if either index is negative, {@code * rowIndex} is greater then or equal to the number of allowed row keys, * or {@code columnIndex} is greater then or equal to the number of * allowed column keys */ public V at(int rowIndex, int columnIndex) { // In GWT array access never throws IndexOutOfBoundsException. checkElementIndex(rowIndex, rowList.size()); checkElementIndex(columnIndex, columnList.size()); return array[rowIndex][columnIndex]; } /** * Associates {@code value} with the specified row and column indices. The * logic {@code * put(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex), value)} * has the same behavior, but this method runs more quickly. * * @param rowIndex position of the row key in {@link #rowKeyList()} * @param columnIndex position of the row key in {@link #columnKeyList()} * @param value value to store in the table * @return the previous value with the specified row and column * @throws IndexOutOfBoundsException if either index is negative, {@code * rowIndex} is greater then or equal to the number of allowed row keys, * or {@code columnIndex} is greater then or equal to the number of * allowed column keys */ public V set(int rowIndex, int columnIndex, @Nullable V value) { // In GWT array access never throws IndexOutOfBoundsException. checkElementIndex(rowIndex, rowList.size()); checkElementIndex(columnIndex, columnList.size()); V oldValue = array[rowIndex][columnIndex]; array[rowIndex][columnIndex] = value; return oldValue; } /** * Not supported. Use {@link #eraseAll} instead. * * @throws UnsupportedOperationException always * @deprecated Use {@link #eraseAll} */ @Override @Deprecated public void clear() { throw new UnsupportedOperationException(); } /** * Associates the value {@code null} with every pair of allowed row and column * keys. */ public void eraseAll() { for (V[] row : array) { Arrays.fill(row, null); } } /** * Returns {@code true} if the provided keys are among the keys provided when * the table was constructed. */ @Override public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) { return containsRow(rowKey) && containsColumn(columnKey); } /** * Returns {@code true} if the provided column key is among the column keys * provided when the table was constructed. */ @Override public boolean containsColumn(@Nullable Object columnKey) { return columnKeyToIndex.containsKey(columnKey); } /** * Returns {@code true} if the provided row key is among the row keys * provided when the table was constructed. */ @Override public boolean containsRow(@Nullable Object rowKey) { return rowKeyToIndex.containsKey(rowKey); } @Override public boolean containsValue(@Nullable Object value) { for (V[] row : array) { for (V element : row) { if (Objects.equal(value, element)) { return true; } } } return false; } @Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) { Integer rowIndex = rowKeyToIndex.get(rowKey); Integer columnIndex = columnKeyToIndex.get(columnKey); return (rowIndex == null || columnIndex == null) ? null : at(rowIndex, columnIndex); } /** * Always returns {@code false}. */ @Override public boolean isEmpty() { return false; } /** * {@inheritDoc} * * @throws IllegalArgumentException if {@code rowKey} is not in {@link * #rowKeySet()} or {@code columnKey} is not in {@link #columnKeySet()}. */ @Override public V put(R rowKey, C columnKey, @Nullable V value) { checkNotNull(rowKey); checkNotNull(columnKey); Integer rowIndex = rowKeyToIndex.get(rowKey); checkArgument(rowIndex != null, "Row %s not in %s", rowKey, rowList); Integer columnIndex = columnKeyToIndex.get(columnKey); checkArgument(columnIndex != null, "Column %s not in %s", columnKey, columnList); return set(rowIndex, columnIndex, value); } /* * TODO(jlevy): Consider creating a merge() method, similar to putAll() but * copying non-null values only. */ /** * {@inheritDoc} * * <p>If {@code table} is an {@code ArrayTable}, its null values will be * stored in this table, possibly replacing values that were previously * non-null. * * @throws NullPointerException if {@code table} has a null key * @throws IllegalArgumentException if any of the provided table's row keys or * column keys is not in {@link #rowKeySet()} or {@link #columnKeySet()} */ @Override public void putAll(Table<? extends R, ? extends C, ? extends V> table) { super.putAll(table); } /** * Not supported. Use {@link #erase} instead. * * @throws UnsupportedOperationException always * @deprecated Use {@link #erase} */ @Override @Deprecated public V remove(Object rowKey, Object columnKey) { throw new UnsupportedOperationException(); } /** * Associates the value {@code null} with the specified keys, assuming both * keys are valid. If either key is null or isn't among the keys provided * during construction, this method has no effect. * * <p>This method is equivalent to {@code put(rowKey, columnKey, null)} when * both provided keys are valid. * * @param rowKey row key of mapping to be erased * @param columnKey column key of mapping to be erased * @return the value previously associated with the keys, or {@code null} if * no mapping existed for the keys */ public V erase(@Nullable Object rowKey, @Nullable Object columnKey) { Integer rowIndex = rowKeyToIndex.get(rowKey); Integer columnIndex = columnKeyToIndex.get(columnKey); if (rowIndex == null || columnIndex == null) { return null; } return set(rowIndex, columnIndex, null); } // TODO(jlevy): Add eraseRow and eraseColumn methods? @Override public int size() { return rowList.size() * columnList.size(); } /** * Returns an unmodifiable set of all row key / column key / value * triplets. Changes to the table will update the returned set. * * <p>The returned set's iterator traverses the mappings with the first row * key, the mappings with the second row key, and so on. * * <p>The value in the returned cells may change if the table subsequently * changes. * * @return set of table cells consisting of row key / column key / value * triplets */ @Override public Set<Cell<R, C, V>> cellSet() { return super.cellSet(); } @Override Iterator<Cell<R, C, V>> cellIterator() { return new AbstractIndexedListIterator<Cell<R, C, V>>(size()) { @Override protected Cell<R, C, V> get(final int index) { return new Tables.AbstractCell<R, C, V>() { final int rowIndex = index / columnList.size(); final int columnIndex = index % columnList.size(); @Override public R getRowKey() { return rowList.get(rowIndex); } @Override public C getColumnKey() { return columnList.get(columnIndex); } @Override public V getValue() { return at(rowIndex, columnIndex); } }; } }; } /** * Returns a view of all mappings that have the given column key. If the * column key isn't in {@link #columnKeySet()}, an empty immutable map is * returned. * * <p>Otherwise, for each row key in {@link #rowKeySet()}, the returned map * associates the row key with the corresponding value in the table. Changes * to the returned map will update the underlying table, and vice versa. * * @param columnKey key of column to search for in the table * @return the corresponding map from row keys to values */ @Override public Map<R, V> column(C columnKey) { checkNotNull(columnKey); Integer columnIndex = columnKeyToIndex.get(columnKey); return (columnIndex == null) ? ImmutableMap.<R, V>of() : new Column(columnIndex); } private class Column extends ArrayMap<R, V> { final int columnIndex; Column(int columnIndex) { super(rowKeyToIndex); this.columnIndex = columnIndex; } @Override String getKeyRole() { return "Row"; } @Override V getValue(int index) { return at(index, columnIndex); } @Override V setValue(int index, V newValue) { return set(index, columnIndex, newValue); } } /** * Returns an immutable set of the valid column keys, including those that * are associated with null values only. * * @return immutable set of column keys */ @Override public ImmutableSet<C> columnKeySet() { return columnKeyToIndex.keySet(); } private transient ColumnMap columnMap; @Override public Map<C, Map<R, V>> columnMap() { ColumnMap map = columnMap; return (map == null) ? columnMap = new ColumnMap() : map; } private class ColumnMap extends ArrayMap<C, Map<R, V>> { private ColumnMap() { super(columnKeyToIndex); } @Override String getKeyRole() { return "Column"; } @Override Map<R, V> getValue(int index) { return new Column(index); } @Override Map<R, V> setValue(int index, Map<R, V> newValue) { throw new UnsupportedOperationException(); } @Override public Map<R, V> put(C key, Map<R, V> value) { throw new UnsupportedOperationException(); } } /** * Returns a view of all mappings that have the given row key. If the * row key isn't in {@link #rowKeySet()}, an empty immutable map is * returned. * * <p>Otherwise, for each column key in {@link #columnKeySet()}, the returned * map associates the column key with the corresponding value in the * table. Changes to the returned map will update the underlying table, and * vice versa. * * @param rowKey key of row to search for in the table * @return the corresponding map from column keys to values */ @Override public Map<C, V> row(R rowKey) { checkNotNull(rowKey); Integer rowIndex = rowKeyToIndex.get(rowKey); return (rowIndex == null) ? ImmutableMap.<C, V>of() : new Row(rowIndex); } private class Row extends ArrayMap<C, V> { final int rowIndex; Row(int rowIndex) { super(columnKeyToIndex); this.rowIndex = rowIndex; } @Override String getKeyRole() { return "Column"; } @Override V getValue(int index) { return at(rowIndex, index); } @Override V setValue(int index, V newValue) { return set(rowIndex, index, newValue); } } /** * Returns an immutable set of the valid row keys, including those that are * associated with null values only. * * @return immutable set of row keys */ @Override public ImmutableSet<R> rowKeySet() { return rowKeyToIndex.keySet(); } private transient RowMap rowMap; @Override public Map<R, Map<C, V>> rowMap() { RowMap map = rowMap; return (map == null) ? rowMap = new RowMap() : map; } private class RowMap extends ArrayMap<R, Map<C, V>> { private RowMap() { super(rowKeyToIndex); } @Override String getKeyRole() { return "Row"; } @Override Map<C, V> getValue(int index) { return new Row(index); } @Override Map<C, V> setValue(int index, Map<C, V> newValue) { throw new UnsupportedOperationException(); } @Override public Map<C, V> put(R key, Map<C, V> value) { throw new UnsupportedOperationException(); } } /** * Returns an unmodifiable collection of all values, which may contain * duplicates. Changes to the table will update the returned collection. * * <p>The returned collection's iterator traverses the values of the first row * key, the values of the second row key, and so on. * * @return collection of values */ @Override public Collection<V> values() { return super.values(); } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ArrayTable.java
Java
asf20
23,499
/* * 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 java.util.Collections; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * GWT implementation of {@link ImmutableMap} that forwards to another map. * * @author Hayward Chan */ public abstract class ForwardingImmutableMap<K, V> extends ImmutableMap<K, V> { final transient Map<K, V> delegate; ForwardingImmutableMap(Map<? extends K, ? extends V> delegate) { this.delegate = Collections.unmodifiableMap(delegate); } @SuppressWarnings("unchecked") ForwardingImmutableMap(Entry<? extends K, ? extends V>... entries) { Map<K, V> delegate = Maps.newLinkedHashMap(); for (Entry<? extends K, ? extends V> entry : entries) { K key = checkNotNull(entry.getKey()); V previous = delegate.put(key, checkNotNull(entry.getValue())); if (previous != null) { throw new IllegalArgumentException("duplicate key: " + key); } } this.delegate = Collections.unmodifiableMap(delegate); } boolean isPartialView() { return false; } public final boolean isEmpty() { return delegate.isEmpty(); } public final boolean containsKey(@Nullable Object key) { return Maps.safeContainsKey(delegate, key); } public final boolean containsValue(@Nullable Object value) { return delegate.containsValue(value); } public V get(@Nullable Object key) { return (key == null) ? null : Maps.safeGet(delegate, key); } @Override ImmutableSet<Entry<K, V>> createEntrySet() { return ImmutableSet.unsafeDelegate( new ForwardingSet<Entry<K, V>>() { @Override protected Set<Entry<K, V>> delegate() { return delegate.entrySet(); } @Override public boolean contains(Object object) { if (object instanceof Entry<?, ?> && ((Entry<?, ?>) object).getKey() == null) { return false; } try { return super.contains(object); } catch (ClassCastException e) { return false; } } @Override public <T> T[] toArray(T[] array) { T[] result = super.toArray(array); if (size() < result.length) { // It works around a GWT bug where elements after last is not // properly null'ed. result[size()] = null; } return result; } }); } @Override ImmutableSet<K> createKeySet() { return ImmutableSet.unsafeDelegate(delegate.keySet()); } @Override ImmutableCollection<V> createValues() { return ImmutableCollection.unsafeDelegate(delegate.values()); } @Override public int size() { return delegate.size(); } @Override public boolean equals(@Nullable Object object) { return delegate.equals(object); } @Override public int hashCode() { return delegate.hashCode(); } @Override public String toString() { return delegate.toString(); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ForwardingImmutableMap.java
Java
asf20
3,669
/* * 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.collect.CollectPreconditions.checkEntryNotNull; import com.google.common.annotations.GwtCompatible; 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) { checkEntryNotNull(key, value); builderMultimap.put(key, value); return this; } /** * Adds an entry to the built multimap. * * @since 11.0 */ public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { return put(entry.getKey(), entry.getValue()); } /** * 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) { if (key == null) { throw new NullPointerException( "null key in entry: null=" + Iterables.toString(values)); } Collection<V> valueList = builderMultimap.get(key); for (V value : values) { checkEntryNotNull(key, value); valueList.add(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. 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(); } @Override public int size() { return multimap.size(); } @Override boolean isPartialView() { return true; } private static final long serialVersionUID = 0; } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableMultimap.java
Java
asf20
19,706
/* * 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 java.io.Serializable; import java.util.AbstractCollection; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import javax.annotation.Nullable; /** * GWT emulated version of {@link ImmutableCollection}. * * @author Jesse Wilson */ @SuppressWarnings("serial") // we're overriding default serialization public abstract class ImmutableCollection<E> extends AbstractCollection<E> implements Serializable { static final ImmutableCollection<Object> EMPTY_IMMUTABLE_COLLECTION = new ForwardingImmutableCollection<Object>(Collections.emptyList()); ImmutableCollection() {} public abstract UnmodifiableIterator<E> iterator(); public boolean contains(@Nullable Object object) { return object != null && super.contains(object); } public final boolean add(E e) { throw new UnsupportedOperationException(); } public final boolean remove(Object object) { throw new UnsupportedOperationException(); } public final boolean addAll(Collection<? extends E> newElements) { throw new UnsupportedOperationException(); } public final boolean removeAll(Collection<?> oldElements) { throw new UnsupportedOperationException(); } public final boolean retainAll(Collection<?> elementsToKeep) { throw new UnsupportedOperationException(); } public final void clear() { throw new UnsupportedOperationException(); } private transient ImmutableList<E> asList; public ImmutableList<E> asList() { ImmutableList<E> list = asList; return (list == null) ? (asList = createAsList()) : list; } ImmutableList<E> createAsList() { switch (size()) { case 0: return ImmutableList.of(); case 1: return ImmutableList.of(iterator().next()); default: return new RegularImmutableAsList<E>(this, toArray()); } } static <E> ImmutableCollection<E> unsafeDelegate(Collection<E> delegate) { return new ForwardingImmutableCollection<E>(delegate); } boolean isPartialView() { return false; } abstract static class Builder<E> { public abstract Builder<E> add(E element); public Builder<E> add(E... elements) { checkNotNull(elements); // for GWT for (E element : elements) { add(checkNotNull(element)); } return this; } public Builder<E> addAll(Iterable<? extends E> elements) { checkNotNull(elements); // for GWT for (E element : elements) { add(checkNotNull(element)); } return this; } public Builder<E> addAll(Iterator<? extends E> elements) { checkNotNull(elements); // for GWT while (elements.hasNext()) { add(checkNotNull(elements.next())); } return this; } public abstract ImmutableCollection<E> build(); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableCollection.java
Java
asf20
3,517
/* * 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 java.util.EnumMap; import java.util.Iterator; /** * Multiset implementation backed by an {@link EnumMap}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset"> * {@code Multiset}</a>. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class EnumMultiset<E extends Enum<E>> extends AbstractMapBasedMultiset<E> { /** Creates an empty {@code EnumMultiset}. */ public static <E extends Enum<E>> EnumMultiset<E> create(Class<E> type) { return new EnumMultiset<E>(type); } /** * Creates a new {@code EnumMultiset} containing the specified elements. * * <p>This implementation is highly efficient when {@code elements} is itself a {@link * Multiset}. * * @param elements the elements that the multiset should contain * @throws IllegalArgumentException if {@code elements} is empty */ public static <E extends Enum<E>> EnumMultiset<E> create(Iterable<E> elements) { Iterator<E> iterator = elements.iterator(); checkArgument(iterator.hasNext(), "EnumMultiset constructor passed empty Iterable"); EnumMultiset<E> multiset = new EnumMultiset<E>(iterator.next().getDeclaringClass()); Iterables.addAll(multiset, elements); return multiset; } /** * Returns a new {@code EnumMultiset} instance containing the given elements. Unlike * {@link EnumMultiset#create(Iterable)}, this method does not produce an exception on an empty * iterable. * * @since 14.0 */ public static <E extends Enum<E>> EnumMultiset<E> create(Iterable<E> elements, Class<E> type) { EnumMultiset<E> result = create(type); Iterables.addAll(result, elements); return result; } private transient Class<E> type; /** Creates an empty {@code EnumMultiset}. */ private EnumMultiset(Class<E> type) { super(WellBehavedMap.wrap(new EnumMap<E, Count>(type))); this.type = type; } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/EnumMultiset.java
Java
asf20
2,780
/* * 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 java.util.Collections; /** * GWT emulation of {@link SingletonImmutableBiMap}. * * @author Hayward Chan */ final class SingletonImmutableBiMap<K, V> extends ImmutableBiMap<K, V> { // These references are used both by the custom field serializer, and by the // GWT compiler to infer the keys and values of the map that needs to be // serialized. // // Although they are non-final, they are package private and the reference is // never modified after a map is constructed. K singleKey; V singleValue; transient SingletonImmutableBiMap<V, K> inverse; SingletonImmutableBiMap(K key, V value) { super(Collections.singletonMap(checkNotNull(key), checkNotNull(value))); this.singleKey = key; this.singleValue = value; } private SingletonImmutableBiMap( K key, V value, SingletonImmutableBiMap<V, K> inverse) { super(Collections.singletonMap(checkNotNull(key), checkNotNull(value))); this.singleKey = key; this.singleValue = value; this.inverse = inverse; } @Override public ImmutableBiMap<V, K> inverse() { ImmutableBiMap<V, K> result = inverse; if (result == null) { return inverse = new SingletonImmutableBiMap<V, K>(singleValue, singleKey, this); } else { return result; } } @Override public ImmutableSet<V> values() { return ImmutableSet.of(singleValue); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/SingletonImmutableBiMap.java
Java
asf20
2,083
/* * 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 java.util.Collection; import java.util.Collections; import java.util.Set; import javax.annotation.Nullable; /** * GWT implementation of {@link ImmutableSet} that forwards to another {@code Set} implementation. * * @author Hayward Chan */ @SuppressWarnings("serial") // Serialization only done in GWT. public abstract class ForwardingImmutableSet<E> extends ImmutableSet<E> { private final transient Set<E> delegate; ForwardingImmutableSet(Set<E> delegate) { // TODO(cpovirk): are we over-wrapping? this.delegate = Collections.unmodifiableSet(delegate); } @Override public UnmodifiableIterator<E> iterator() { return Iterators.unmodifiableIterator(delegate.iterator()); } @Override public boolean contains(@Nullable Object object) { return object != null && delegate.contains(object); } @Override public boolean containsAll(Collection<?> targets) { return delegate.containsAll(targets); } @Override public int size() { return delegate.size(); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public Object[] toArray() { return delegate.toArray(); } @Override public <T> T[] toArray(T[] other) { return delegate.toArray(other); } @Override public String toString() { return delegate.toString(); } // TODO(cpovirk): equals(), as well, in case it's any faster than Sets.equalsImpl? @Override public int hashCode() { return delegate.hashCode(); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ForwardingImmutableSet.java
Java
asf20
2,124
/* * 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.Comparator; import java.util.TreeMap; /** * GWT emulated version of {@link EmptyImmutableSortedMap}. * * @author Chris Povirk */ final class EmptyImmutableSortedMap<K, V> extends ImmutableSortedMap<K, V> { private EmptyImmutableSortedMap(Comparator<? super K> comparator) { super(new TreeMap<K, V>(comparator), comparator); } @SuppressWarnings("unchecked") private static final ImmutableSortedMap<Object, Object> NATURAL_EMPTY_MAP = new EmptyImmutableSortedMap<Object, Object>(NATURAL_ORDER); static <K, V> ImmutableSortedMap<K, V> forComparator(Comparator<? super K> comparator) { if (comparator == NATURAL_ORDER) { return (ImmutableSortedMap) NATURAL_EMPTY_MAP; } return new EmptyImmutableSortedMap<K, V>(comparator); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/EmptyImmutableSortedMap.java
Java
asf20
1,426
/* * 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.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Maps.EntryTransformer; import java.io.Serializable; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import javax.annotation.Nullable; /** * Minimal GWT emulation of {@code com.google.common.collect.Platform}. * * <p><strong>This .java file should never be consumed by javac.</strong> * * @author Hayward Chan */ final class Platform { static <T> T[] newArray(T[] reference, int length) { return GwtPlatform.newArray(reference, length); } /* * Regarding newSetForMap() and SetFromMap: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ static <E> Set<E> newSetFromMap(Map<E, Boolean> map) { return new SetFromMap<E>(map); } private static class SetFromMap<E> extends AbstractSet<E> implements Set<E>, Serializable { private final Map<E, Boolean> m; // The backing map private transient Set<E> s; // Its keySet SetFromMap(Map<E, Boolean> map) { checkArgument(map.isEmpty(), "Map is non-empty"); m = map; s = map.keySet(); } @Override public void clear() { m.clear(); } @Override public int size() { return m.size(); } @Override public boolean isEmpty() { return m.isEmpty(); } @Override public boolean contains(Object o) { return m.containsKey(o); } @Override public boolean remove(Object o) { return m.remove(o) != null; } @Override public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; } @Override public Iterator<E> iterator() { return s.iterator(); } @Override public Object[] toArray() { return s.toArray(); } @Override public <T> T[] toArray(T[] a) { return s.toArray(a); } @Override public String toString() { return s.toString(); } @Override public int hashCode() { return s.hashCode(); } @Override public boolean equals(@Nullable Object object) { return this == object || this.s.equals(object); } @Override public boolean containsAll(Collection<?> c) { return s.containsAll(c); } @Override public boolean removeAll(Collection<?> c) { return s.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return s.retainAll(c); } } static MapMaker tryWeakKeys(MapMaker mapMaker) { return mapMaker; } static <K, V1, V2> SortedMap<K, V2> mapsTransformEntriesSortedMap( SortedMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { return Maps.transformEntriesIgnoreNavigable(fromMap, transformer); } static <K, V> SortedMap<K, V> mapsAsMapSortedSet( SortedSet<K> set, Function<? super K, V> function) { return Maps.asMapSortedIgnoreNavigable(set, function); } static <E> SortedSet<E> setsFilterSortedSet( SortedSet<E> unfiltered, Predicate<? super E> predicate) { return Sets.filterSortedIgnoreNavigable(unfiltered, predicate); } static <K, V> SortedMap<K, V> mapsFilterSortedMap( SortedMap<K, V> unfiltered, Predicate<? super Map.Entry<K, V>> predicate) { return Maps.filterSortedIgnoreNavigable(unfiltered, predicate); } private Platform() {} }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/Platform.java
Java
asf20
4,277
/* * 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.util.Comparator; import java.util.Iterator; import java.util.Set; import java.util.SortedSet; /** * A skeleton implementation of a descending multiset. Only needs * {@code forwardMultiset()} and {@code entryIterator()}. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) abstract class DescendingMultiset<E> extends ForwardingMultiset<E> implements SortedMultiset<E> { abstract SortedMultiset<E> forwardMultiset(); private transient Comparator<? super E> comparator; @Override public Comparator<? super E> comparator() { Comparator<? super E> result = comparator; if (result == null) { return comparator = Ordering.from(forwardMultiset().comparator()).<E>reverse(); } return result; } private transient SortedSet<E> elementSet; @Override public SortedSet<E> elementSet() { SortedSet<E> result = elementSet; if (result == null) { return elementSet = new SortedMultisets.ElementSet<E>(this); } return result; } @Override public Entry<E> pollFirstEntry() { return forwardMultiset().pollLastEntry(); } @Override public Entry<E> pollLastEntry() { return forwardMultiset().pollFirstEntry(); } @Override public SortedMultiset<E> headMultiset(E toElement, BoundType boundType) { return forwardMultiset().tailMultiset(toElement, boundType) .descendingMultiset(); } @Override public SortedMultiset<E> subMultiset(E fromElement, BoundType fromBoundType, E toElement, BoundType toBoundType) { return forwardMultiset().subMultiset(toElement, toBoundType, fromElement, fromBoundType).descendingMultiset(); } @Override public SortedMultiset<E> tailMultiset(E fromElement, BoundType boundType) { return forwardMultiset().headMultiset(fromElement, boundType) .descendingMultiset(); } @Override protected Multiset<E> delegate() { return forwardMultiset(); } @Override public SortedMultiset<E> descendingMultiset() { return forwardMultiset(); } @Override public Entry<E> firstEntry() { return forwardMultiset().lastEntry(); } @Override public Entry<E> lastEntry() { return forwardMultiset().firstEntry(); } abstract Iterator<Entry<E>> entryIterator(); private transient Set<Entry<E>> entrySet; @Override public Set<Entry<E>> entrySet() { Set<Entry<E>> result = entrySet; return (result == null) ? entrySet = createEntrySet() : result; } Set<Entry<E>> createEntrySet() { return new Multisets.EntrySet<E>() { @Override Multiset<E> multiset() { return DescendingMultiset.this; } @Override public Iterator<Entry<E>> iterator() { return entryIterator(); } @Override public int size() { return forwardMultiset().entrySet().size(); } }; } @Override public Iterator<E> iterator() { return Multisets.iteratorImpl(this); } @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } @Override public String toString() { return entrySet().toString(); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/DescendingMultiset.java
Java
asf20
3,861
/* * 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 static com.google.common.collect.CollectPreconditions.checkRemove; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * A general-purpose bimap implementation using any two backing {@code Map} * instances. * * <p>Note that this class contains {@code equals()} calls that keep it from * supporting {@code IdentityHashMap} backing maps. * * @author Kevin Bourrillion * @author Mike Bostock */ @GwtCompatible(emulated = true) abstract class AbstractBiMap<K, V> extends ForwardingMap<K, V> implements BiMap<K, V>, Serializable { private transient Map<K, V> delegate; transient AbstractBiMap<V, K> inverse; /** Package-private constructor for creating a map-backed bimap. */ AbstractBiMap(Map<K, V> forward, Map<V, K> backward) { setDelegates(forward, backward); } /** Private constructor for inverse bimap. */ private AbstractBiMap(Map<K, V> backward, AbstractBiMap<V, K> forward) { delegate = backward; inverse = forward; } @Override protected Map<K, V> delegate() { return delegate; } /** * Returns its input, or throws an exception if this is not a valid key. */ K checkKey(@Nullable K key) { return key; } /** * Returns its input, or throws an exception if this is not a valid value. */ V checkValue(@Nullable V value) { return value; } /** * Specifies the delegate maps going in each direction. Called by the * constructor and by subclasses during deserialization. */ void setDelegates(Map<K, V> forward, Map<V, K> backward) { checkState(delegate == null); checkState(inverse == null); checkArgument(forward.isEmpty()); checkArgument(backward.isEmpty()); checkArgument(forward != backward); delegate = forward; inverse = new Inverse<V, K>(backward, this); } void setInverse(AbstractBiMap<V, K> inverse) { this.inverse = inverse; } // Query Operations (optimizations) @Override public boolean containsValue(@Nullable Object value) { return inverse.containsKey(value); } // Modification Operations @Override public V put(@Nullable K key, @Nullable V value) { return putInBothMaps(key, value, false); } @Override public V forcePut(@Nullable K key, @Nullable V value) { return putInBothMaps(key, value, true); } private V putInBothMaps(@Nullable K key, @Nullable V value, boolean force) { checkKey(key); checkValue(value); boolean containedKey = containsKey(key); if (containedKey && Objects.equal(value, get(key))) { return value; } if (force) { inverse().remove(value); } else { checkArgument(!containsValue(value), "value already present: %s", value); } V oldValue = delegate.put(key, value); updateInverseMap(key, containedKey, oldValue, value); return oldValue; } private void updateInverseMap( K key, boolean containedKey, V oldValue, V newValue) { if (containedKey) { removeFromInverseMap(oldValue); } inverse.delegate.put(newValue, key); } @Override public V remove(@Nullable Object key) { return containsKey(key) ? removeFromBothMaps(key) : null; } private V removeFromBothMaps(Object key) { V oldValue = delegate.remove(key); removeFromInverseMap(oldValue); return oldValue; } private void removeFromInverseMap(V oldValue) { inverse.delegate.remove(oldValue); } // Bulk Operations @Override public void putAll(Map<? extends K, ? extends V> map) { for (Entry<? extends K, ? extends V> entry : map.entrySet()) { put(entry.getKey(), entry.getValue()); } } @Override public void clear() { delegate.clear(); inverse.delegate.clear(); } // Views @Override public BiMap<V, K> inverse() { return inverse; } private transient Set<K> keySet; @Override public Set<K> keySet() { Set<K> result = keySet; return (result == null) ? keySet = new KeySet() : result; } private class KeySet extends ForwardingSet<K> { @Override protected Set<K> delegate() { return delegate.keySet(); } @Override public void clear() { AbstractBiMap.this.clear(); } @Override public boolean remove(Object key) { if (!contains(key)) { return false; } removeFromBothMaps(key); return true; } @Override public boolean removeAll(Collection<?> keysToRemove) { return standardRemoveAll(keysToRemove); } @Override public boolean retainAll(Collection<?> keysToRetain) { return standardRetainAll(keysToRetain); } @Override public Iterator<K> iterator() { return Maps.keyIterator(entrySet().iterator()); } } private transient Set<V> valueSet; @Override public Set<V> values() { /* * We can almost reuse the inverse's keySet, except we have to fix the * iteration order so that it is consistent with the forward map. */ Set<V> result = valueSet; return (result == null) ? valueSet = new ValueSet() : result; } private class ValueSet extends ForwardingSet<V> { final Set<V> valuesDelegate = inverse.keySet(); @Override protected Set<V> delegate() { return valuesDelegate; } @Override public Iterator<V> iterator() { return Maps.valueIterator(entrySet().iterator()); } @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } @Override public String toString() { return standardToString(); } } private transient Set<Entry<K, V>> entrySet; @Override public Set<Entry<K, V>> entrySet() { Set<Entry<K, V>> result = entrySet; return (result == null) ? entrySet = new EntrySet() : result; } private class EntrySet extends ForwardingSet<Entry<K, V>> { final Set<Entry<K, V>> esDelegate = delegate.entrySet(); @Override protected Set<Entry<K, V>> delegate() { return esDelegate; } @Override public void clear() { AbstractBiMap.this.clear(); } @Override public boolean remove(Object object) { if (!esDelegate.contains(object)) { return false; } // safe because esDelgate.contains(object). Entry<?, ?> entry = (Entry<?, ?>) object; inverse.delegate.remove(entry.getValue()); /* * Remove the mapping in inverse before removing from esDelegate because * if entry is part of esDelegate, entry might be invalidated after the * mapping is removed from esDelegate. */ esDelegate.remove(entry); return true; } @Override public Iterator<Entry<K, V>> iterator() { final Iterator<Entry<K, V>> iterator = esDelegate.iterator(); return new Iterator<Entry<K, V>>() { Entry<K, V> entry; @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Entry<K, V> next() { entry = iterator.next(); final Entry<K, V> finalEntry = entry; return new ForwardingMapEntry<K, V>() { @Override protected Entry<K, V> delegate() { return finalEntry; } @Override public V setValue(V value) { // Preconditions keep the map and inverse consistent. checkState(contains(this), "entry no longer in map"); // similar to putInBothMaps, but set via entry if (Objects.equal(value, getValue())) { return value; } checkArgument(!containsValue(value), "value already present: %s", value); V oldValue = finalEntry.setValue(value); checkState(Objects.equal(value, get(getKey())), "entry no longer in map"); updateInverseMap(getKey(), true, oldValue, value); return oldValue; } }; } @Override public void remove() { checkRemove(entry != null); V value = entry.getValue(); iterator.remove(); removeFromInverseMap(value); } }; } // See java.util.Collections.CheckedEntrySet for details on attacks. @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } @Override public boolean contains(Object o) { return Maps.containsEntryImpl(delegate(), o); } @Override public boolean containsAll(Collection<?> c) { return standardContainsAll(c); } @Override public boolean removeAll(Collection<?> c) { return standardRemoveAll(c); } @Override public boolean retainAll(Collection<?> c) { return standardRetainAll(c); } } /** The inverse of any other {@code AbstractBiMap} subclass. */ private static class Inverse<K, V> extends AbstractBiMap<K, V> { private Inverse(Map<K, V> backward, AbstractBiMap<V, K> forward) { super(backward, forward); } /* * Serialization stores the forward bimap, the inverse of this inverse. * Deserialization calls inverse() on the forward bimap and returns that * inverse. * * If a bimap and its inverse are serialized together, the deserialized * instances have inverse() methods that return the other. */ @Override K checkKey(K key) { return inverse.checkValue(key); } @Override V checkValue(V value) { return inverse.checkKey(value); } } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/AbstractBiMap.java
Java
asf20
10,527
/* * 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; /** * List returned by {@link ImmutableCollection#asList} that delegates {@code contains} checks * to the backing collection. * * @author Jared Levy * @author Louis Wasserman */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") abstract class ImmutableAsList<E> extends ImmutableList<E> { abstract ImmutableCollection<E> delegateCollection(); @Override public boolean contains(Object target) { // The collection's contains() is at least as fast as ImmutableList's // and is often faster. return delegateCollection().contains(target); } @Override public int size() { return delegateCollection().size(); } @Override public boolean isEmpty() { return delegateCollection().isEmpty(); } @Override boolean isPartialView() { return delegateCollection().isPartialView(); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableAsList.java
Java
asf20
1,548
/* * 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 java.util.SortedSet; /** * GWT emulation of {@link RegularImmutableSortedSet}. * * @author Hayward Chan */ final class RegularImmutableSortedSet<E> extends ImmutableSortedSet<E> { /** true if this set is a subset of another immutable sorted set. */ final boolean isSubset; RegularImmutableSortedSet(SortedSet<E> delegate, boolean isSubset) { super(delegate); this.isSubset = isSubset; } @Override ImmutableList<E> createAsList() { return new ImmutableSortedAsList<E>(this, ImmutableList.<E>asImmutableList(toArray())); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/RegularImmutableSortedSet.java
Java
asf20
1,200
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.BoundType.CLOSED; import com.google.common.annotations.GwtCompatible; import java.util.Collection; import javax.annotation.Nullable; /** * An implementation of {@link ContiguousSet} that contains one or more elements. * * @author Gregory Kick */ @GwtCompatible(emulated = true) @SuppressWarnings("unchecked") // allow ungenerified Comparable types final class RegularContiguousSet<C extends Comparable> extends ContiguousSet<C> { private final Range<C> range; RegularContiguousSet(Range<C> range, DiscreteDomain<C> domain) { super(domain); this.range = range; } private ContiguousSet<C> intersectionInCurrentDomain(Range<C> other) { return (range.isConnected(other)) ? ContiguousSet.create(range.intersection(other), domain) : new EmptyContiguousSet<C>(domain); } @Override ContiguousSet<C> headSetImpl(C toElement, boolean inclusive) { return intersectionInCurrentDomain(Range.upTo(toElement, BoundType.forBoolean(inclusive))); } @Override ContiguousSet<C> subSetImpl(C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) { if (fromElement.compareTo(toElement) == 0 && !fromInclusive && !toInclusive) { // Range would reject our attempt to create (x, x). return new EmptyContiguousSet<C>(domain); } return intersectionInCurrentDomain(Range.range( fromElement, BoundType.forBoolean(fromInclusive), toElement, BoundType.forBoolean(toInclusive))); } @Override ContiguousSet<C> tailSetImpl(C fromElement, boolean inclusive) { return intersectionInCurrentDomain(Range.downTo(fromElement, BoundType.forBoolean(inclusive))); } @Override public UnmodifiableIterator<C> iterator() { return new AbstractSequentialIterator<C>(first()) { final C last = last(); @Override protected C computeNext(C previous) { return equalsOrThrow(previous, last) ? null : domain.next(previous); } }; } private static boolean equalsOrThrow(Comparable<?> left, @Nullable Comparable<?> right) { return right != null && Range.compareOrThrow(left, right) == 0; } @Override boolean isPartialView() { return false; } @Override public C first() { return range.lowerBound.leastValueAbove(domain); } @Override public C last() { return range.upperBound.greatestValueBelow(domain); } @Override public int size() { long distance = domain.distance(first(), last()); return (distance >= Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) distance + 1; } @Override public boolean contains(@Nullable Object object) { if (object == null) { return false; } try { return range.contains((C) object); } catch (ClassCastException e) { return false; } } @Override public boolean containsAll(Collection<?> targets) { return Collections2.containsAllImpl(this, targets); } @Override public boolean isEmpty() { return false; } @Override public ContiguousSet<C> intersection(ContiguousSet<C> other) { checkNotNull(other); checkArgument(this.domain.equals(other.domain)); if (other.isEmpty()) { return other; } else { C lowerEndpoint = Ordering.natural().max(this.first(), other.first()); C upperEndpoint = Ordering.natural().min(this.last(), other.last()); return (lowerEndpoint.compareTo(upperEndpoint) < 0) ? ContiguousSet.create(Range.closed(lowerEndpoint, upperEndpoint), domain) : new EmptyContiguousSet<C>(domain); } } @Override public Range<C> range() { return range(CLOSED, CLOSED); } @Override public Range<C> range(BoundType lowerBoundType, BoundType upperBoundType) { return Range.create(range.lowerBound.withLowerBoundType(lowerBoundType, domain), range.upperBound.withUpperBoundType(upperBoundType, domain)); } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } else if (object instanceof RegularContiguousSet) { RegularContiguousSet<?> that = (RegularContiguousSet<?>) object; if (this.domain.equals(that.domain)) { return this.first().equals(that.first()) && this.last().equals(that.last()); } } return super.equals(object); } // copied to make sure not to use the GWT-emulated version @Override public int hashCode() { return Sets.hashCodeImpl(this); } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/RegularContiguousSet.java
Java
asf20
5,272
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.collect.CollectPreconditions.checkNonnegative; import static com.google.common.collect.CollectPreconditions.checkRemove; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; 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)); checkNonnegative(valueSetCapacity, "expectedValuesPerKey"); 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(); 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() { 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); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/LinkedHashMultimap.java
Java
asf20
17,761
/* * 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; /** * An {@link ImmutableAsList} implementation specialized for when the delegate collection is * already backed by an {@code ImmutableList} or array. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) @SuppressWarnings("serial") // uses writeReplace, not default serialization class RegularImmutableAsList<E> extends ImmutableAsList<E> { private final ImmutableCollection<E> delegate; private final ImmutableList<? extends E> delegateList; RegularImmutableAsList(ImmutableCollection<E> delegate, ImmutableList<? extends E> delegateList) { this.delegate = delegate; this.delegateList = delegateList; } RegularImmutableAsList(ImmutableCollection<E> delegate, Object[] array) { this(delegate, ImmutableList.<E>asImmutableList(array)); } @Override ImmutableCollection<E> delegateCollection() { return delegate; } ImmutableList<? extends E> delegateList() { return delegateList; } @SuppressWarnings("unchecked") // safe covariant cast! @Override public UnmodifiableListIterator<E> listIterator(int index) { return (UnmodifiableListIterator<E>) delegateList.listIterator(index); } @Override public E get(int index) { return delegateList.get(index); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/RegularImmutableAsList.java
Java
asf20
1,928
/* * 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 java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; /** * GWT emulated version of {@link ImmutableSet}. For the unsorted sets, they * are thin wrapper around {@link java.util.Collections#emptySet()}, {@link * Collections#singleton(Object)} and {@link java.util.LinkedHashSet} for * empty, singleton and regular sets respectively. For the sorted sets, it's * a thin wrapper around {@link java.util.TreeSet}. * * @see ImmutableSortedSet * * @author Hayward Chan */ @SuppressWarnings("serial") // Serialization only done in GWT. public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements Set<E> { ImmutableSet() {} // Casting to any type is safe because the set will never hold any elements. @SuppressWarnings({"unchecked"}) public static <E> ImmutableSet<E> of() { return (ImmutableSet<E>) EmptyImmutableSet.INSTANCE; } public static <E> ImmutableSet<E> of(E element) { return new SingletonImmutableSet<E>(element); } @SuppressWarnings("unchecked") public static <E> ImmutableSet<E> of(E e1, E e2) { return create(e1, e2); } @SuppressWarnings("unchecked") public static <E> ImmutableSet<E> of(E e1, E e2, E e3) { return create(e1, e2, e3); } @SuppressWarnings("unchecked") public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4) { return create(e1, e2, e3, e4); } @SuppressWarnings("unchecked") public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5) { return create(e1, e2, e3, e4, e5); } @SuppressWarnings("unchecked") public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E... others) { int size = others.length + 6; List<E> all = new ArrayList<E>(size); Collections.addAll(all, e1, e2, e3, e4, e5, e6); Collections.addAll(all, others); return copyOf(all.iterator()); } public static <E> ImmutableSet<E> copyOf(E[] elements) { checkNotNull(elements); switch (elements.length) { case 0: return of(); case 1: return of(elements[0]); default: return create(elements); } } public static <E> ImmutableSet<E> copyOf(Collection<? extends E> elements) { Iterable<? extends E> iterable = elements; return copyOf(iterable); } public static <E> ImmutableSet<E> copyOf(Iterable<? extends E> elements) { if (elements instanceof ImmutableSet && !(elements instanceof ImmutableSortedSet)) { @SuppressWarnings("unchecked") // all supported methods are covariant ImmutableSet<E> set = (ImmutableSet<E>) elements; return set; } return copyOf(elements.iterator()); } public static <E> ImmutableSet<E> copyOf(Iterator<? extends E> elements) { if (!elements.hasNext()) { return of(); } E first = elements.next(); if (!elements.hasNext()) { // TODO: Remove "ImmutableSet.<E>" when eclipse bug is fixed. return ImmutableSet.<E>of(first); } Set<E> delegate = Sets.newLinkedHashSet(); delegate.add(checkNotNull(first)); do { delegate.add(checkNotNull(elements.next())); } while (elements.hasNext()); return unsafeDelegate(delegate); } // Factory methods that skips the null checks on elements, only used when // the elements are known to be non-null. static <E> ImmutableSet<E> unsafeDelegate(Set<E> delegate) { switch (delegate.size()) { case 0: return of(); case 1: return new SingletonImmutableSet<E>(delegate.iterator().next()); default: return new RegularImmutableSet<E>(delegate); } } private static <E> ImmutableSet<E> create(E... elements) { // Create the set first, to remove duplicates if necessary. Set<E> set = Sets.newLinkedHashSet(); Collections.addAll(set, elements); for (E element : set) { checkNotNull(element); } switch (set.size()) { case 0: return of(); case 1: return new SingletonImmutableSet<E>(set.iterator().next()); default: return new RegularImmutableSet<E>(set); } } @Override public boolean equals(Object obj) { return Sets.equalsImpl(this, obj); } @Override public int hashCode() { return Sets.hashCodeImpl(this); } public static <E> Builder<E> builder() { return new Builder<E>(); } public static class Builder<E> extends ImmutableCollection.Builder<E> { // accessed directly by ImmutableSortedSet final ArrayList<E> contents = Lists.newArrayList(); public Builder() {} @Override public Builder<E> add(E element) { contents.add(checkNotNull(element)); return this; } @Override public Builder<E> add(E... elements) { checkNotNull(elements); // for GWT contents.ensureCapacity(contents.size() + elements.length); super.add(elements); return this; } @Override public Builder<E> addAll(Iterable<? extends E> elements) { if (elements instanceof Collection) { Collection<?> collection = (Collection<?>) elements; contents.ensureCapacity(contents.size() + collection.size()); } super.addAll(elements); return this; } @Override public Builder<E> addAll(Iterator<? extends E> elements) { super.addAll(elements); return this; } @Override public ImmutableSet<E> build() { return copyOf(contents.iterator()); } } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableSet.java
Java
asf20
6,190
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.Map.Entry; import javax.annotation.Nullable; /** * {@code keySet()} implementation for {@link ImmutableMap}. * * @author Jesse Wilson * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) final class ImmutableMapKeySet<K, V> extends ImmutableSet<K> { private final ImmutableMap<K, V> map; ImmutableMapKeySet(ImmutableMap<K, V> map) { this.map = map; } @Override public int size() { return map.size(); } @Override public UnmodifiableIterator<K> iterator() { return asList().iterator(); } @Override public boolean contains(@Nullable Object object) { return map.containsKey(object); } @Override ImmutableList<K> createAsList() { final ImmutableList<Entry<K, V>> entryList = map.entrySet().asList(); return new ImmutableAsList<K>() { @Override public K get(int index) { return entryList.get(index).getKey(); } @Override ImmutableCollection<K> delegateCollection() { return ImmutableMapKeySet.this; } }; } @Override boolean isPartialView() { return true; } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableMapKeySet.java
Java
asf20
1,808
/* * 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.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.CollectPreconditions.checkRemove; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.PriorityQueue; import java.util.Queue; import javax.annotation.Nullable; /** * This class contains static utility methods that operate on or return objects * of type {@link Iterator}. Except as noted, each method has a corresponding * {@link Iterable}-based method in the {@link Iterables} class. * * <p><i>Performance notes:</i> Unless otherwise noted, all of the iterators * produced in this class are <i>lazy</i>, which means that they only advance * the backing iteration when absolutely necessary. * * <p>See the Guava User Guide section on <a href= * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Iterables"> * {@code Iterators}</a>. * * @author Kevin Bourrillion * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class Iterators { private Iterators() {} static final UnmodifiableListIterator<Object> EMPTY_LIST_ITERATOR = new UnmodifiableListIterator<Object>() { @Override public boolean hasNext() { return false; } @Override public Object next() { throw new NoSuchElementException(); } @Override public boolean hasPrevious() { return false; } @Override public Object previous() { throw new NoSuchElementException(); } @Override public int nextIndex() { return 0; } @Override public int previousIndex() { return -1; } }; /** * Returns the empty iterator. * * <p>The {@link Iterable} equivalent of this method is {@link * ImmutableSet#of()}. */ public static <T> UnmodifiableIterator<T> emptyIterator() { return emptyListIterator(); } /** * Returns the empty iterator. * * <p>The {@link Iterable} equivalent of this method is {@link * ImmutableSet#of()}. */ // Casting to any type is safe since there are no actual elements. @SuppressWarnings("unchecked") static <T> UnmodifiableListIterator<T> emptyListIterator() { return (UnmodifiableListIterator<T>) EMPTY_LIST_ITERATOR; } private static final Iterator<Object> EMPTY_MODIFIABLE_ITERATOR = new Iterator<Object>() { @Override public boolean hasNext() { return false; } @Override public Object next() { throw new NoSuchElementException(); } @Override public void remove() { checkRemove(false); } }; /** * Returns the empty {@code Iterator} that throws * {@link IllegalStateException} instead of * {@link UnsupportedOperationException} on a call to * {@link Iterator#remove()}. */ // Casting to any type is safe since there are no actual elements. @SuppressWarnings("unchecked") static <T> Iterator<T> emptyModifiableIterator() { return (Iterator<T>) EMPTY_MODIFIABLE_ITERATOR; } /** Returns an unmodifiable view of {@code iterator}. */ public static <T> UnmodifiableIterator<T> unmodifiableIterator( final Iterator<T> iterator) { checkNotNull(iterator); if (iterator instanceof UnmodifiableIterator) { return (UnmodifiableIterator<T>) iterator; } return new UnmodifiableIterator<T>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { return iterator.next(); } }; } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <T> UnmodifiableIterator<T> unmodifiableIterator( UnmodifiableIterator<T> iterator) { return checkNotNull(iterator); } /** * Returns the number of elements remaining in {@code iterator}. The iterator * will be left exhausted: its {@code hasNext()} method will return * {@code false}. */ public static int size(Iterator<?> iterator) { int count = 0; while (iterator.hasNext()) { iterator.next(); count++; } return count; } /** * Returns {@code true} if {@code iterator} contains {@code element}. */ public static boolean contains(Iterator<?> iterator, @Nullable Object element) { return any(iterator, equalTo(element)); } /** * Traverses an iterator and removes every element that belongs to the * provided collection. The iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. * * @param removeFrom the iterator to (potentially) remove elements from * @param elementsToRemove the elements to remove * @return {@code true} if any element was removed from {@code iterator} */ public static boolean removeAll( Iterator<?> removeFrom, Collection<?> elementsToRemove) { return removeIf(removeFrom, in(elementsToRemove)); } /** * Removes every element that satisfies the provided predicate from the * iterator. The iterator will be left exhausted: its {@code hasNext()} * method will return {@code false}. * * @param removeFrom the iterator to (potentially) remove elements from * @param predicate a predicate that determines whether an element should * be removed * @return {@code true} if any elements were removed from the iterator * @since 2.0 */ public static <T> boolean removeIf( Iterator<T> removeFrom, Predicate<? super T> predicate) { checkNotNull(predicate); boolean modified = false; while (removeFrom.hasNext()) { if (predicate.apply(removeFrom.next())) { removeFrom.remove(); modified = true; } } return modified; } /** * Traverses an iterator and removes every element that does not belong to the * provided collection. The iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. * * @param removeFrom the iterator to (potentially) remove elements from * @param elementsToRetain the elements to retain * @return {@code true} if any element was removed from {@code iterator} */ public static boolean retainAll( Iterator<?> removeFrom, Collection<?> elementsToRetain) { return removeIf(removeFrom, not(in(elementsToRetain))); } /** * Determines whether two iterators contain equal elements in the same order. * More specifically, this method returns {@code true} if {@code iterator1} * and {@code iterator2} contain the same number of elements and every element * of {@code iterator1} is equal to the corresponding element of * {@code iterator2}. * * <p>Note that this will modify the supplied iterators, since they will have * been advanced some number of elements forward. */ public static boolean elementsEqual( Iterator<?> iterator1, Iterator<?> iterator2) { while (iterator1.hasNext()) { if (!iterator2.hasNext()) { return false; } Object o1 = iterator1.next(); Object o2 = iterator2.next(); if (!Objects.equal(o1, o2)) { return false; } } return !iterator2.hasNext(); } /** * Returns a string representation of {@code iterator}, with the format * {@code [e1, e2, ..., en]}. The iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. */ public static String toString(Iterator<?> iterator) { return Collections2.STANDARD_JOINER .appendTo(new StringBuilder().append('['), iterator) .append(']') .toString(); } /** * Returns the single element contained in {@code iterator}. * * @throws NoSuchElementException if the iterator is empty * @throws IllegalArgumentException if the iterator contains multiple * elements. The state of the iterator is unspecified. */ public static <T> T getOnlyElement(Iterator<T> iterator) { T first = iterator.next(); if (!iterator.hasNext()) { return first; } StringBuilder sb = new StringBuilder(); sb.append("expected one element but was: <" + first); for (int i = 0; i < 4 && iterator.hasNext(); i++) { sb.append(", " + iterator.next()); } if (iterator.hasNext()) { sb.append(", ..."); } sb.append('>'); throw new IllegalArgumentException(sb.toString()); } /** * Returns the single element contained in {@code iterator}, or {@code * defaultValue} if the iterator is empty. * * @throws IllegalArgumentException if the iterator contains multiple * elements. The state of the iterator is unspecified. */ @Nullable public static <T> T getOnlyElement(Iterator<? extends T> iterator, @Nullable T defaultValue) { return iterator.hasNext() ? getOnlyElement(iterator) : defaultValue; } /** * Adds all elements in {@code iterator} to {@code collection}. The iterator * will be left exhausted: its {@code hasNext()} method will return * {@code false}. * * @return {@code true} if {@code collection} was modified as a result of this * operation */ public static <T> boolean addAll( Collection<T> addTo, Iterator<? extends T> iterator) { checkNotNull(addTo); checkNotNull(iterator); boolean wasModified = false; while (iterator.hasNext()) { wasModified |= addTo.add(iterator.next()); } return wasModified; } /** * Returns the number of elements in the specified iterator that equal the * specified object. The iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. * * @see Collections#frequency */ public static int frequency(Iterator<?> iterator, @Nullable Object element) { return size(filter(iterator, equalTo(element))); } /** * Returns an iterator that cycles indefinitely over the elements of {@code * iterable}. * * <p>The returned iterator supports {@code remove()} if the provided iterator * does. After {@code remove()} is called, subsequent cycles omit the removed * element, which is no longer in {@code iterable}. The iterator's * {@code hasNext()} method returns {@code true} until {@code iterable} is * empty. * * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an * infinite loop. You should use an explicit {@code break} or be certain that * you will eventually remove all the elements. */ public static <T> Iterator<T> cycle(final Iterable<T> iterable) { checkNotNull(iterable); return new Iterator<T>() { Iterator<T> iterator = emptyIterator(); Iterator<T> removeFrom; @Override public boolean hasNext() { if (!iterator.hasNext()) { iterator = iterable.iterator(); } return iterator.hasNext(); } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } removeFrom = iterator; return iterator.next(); } @Override public void remove() { checkRemove(removeFrom != null); removeFrom.remove(); removeFrom = null; } }; } /** * Returns an iterator that cycles indefinitely over the provided elements. * * <p>The returned iterator supports {@code remove()}. After {@code remove()} * is called, subsequent cycles omit the removed * element, but {@code elements} does not change. The iterator's * {@code hasNext()} method returns {@code true} until all of the original * elements have been removed. * * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an * infinite loop. You should use an explicit {@code break} or be certain that * you will eventually remove all the elements. */ public static <T> Iterator<T> cycle(T... elements) { return cycle(Lists.newArrayList(elements)); } /** * Combines two iterators into a single iterator. The returned iterator * iterates across the elements in {@code a}, followed by the elements in * {@code b}. The source iterators are not polled until necessary. * * <p>The returned iterator supports {@code remove()} when the corresponding * input iterator supports it. * * <p><b>Note:</b> the current implementation is not suitable for nested * concatenated iterators, i.e. the following should be avoided when in a loop: * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the * resulting iterator has a cubic complexity to the depth of the nesting. */ public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b) { return concat(ImmutableList.of(a, b).iterator()); } /** * Combines three iterators into a single iterator. The returned iterator * iterates across the elements in {@code a}, followed by the elements in * {@code b}, followed by the elements in {@code c}. The source iterators * are not polled until necessary. * * <p>The returned iterator supports {@code remove()} when the corresponding * input iterator supports it. * * <p><b>Note:</b> the current implementation is not suitable for nested * concatenated iterators, i.e. the following should be avoided when in a loop: * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the * resulting iterator has a cubic complexity to the depth of the nesting. */ public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b, Iterator<? extends T> c) { return concat(ImmutableList.of(a, b, c).iterator()); } /** * Combines four iterators into a single iterator. The returned iterator * iterates across the elements in {@code a}, followed by the elements in * {@code b}, followed by the elements in {@code c}, followed by the elements * in {@code d}. The source iterators are not polled until necessary. * * <p>The returned iterator supports {@code remove()} when the corresponding * input iterator supports it. * * <p><b>Note:</b> the current implementation is not suitable for nested * concatenated iterators, i.e. the following should be avoided when in a loop: * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the * resulting iterator has a cubic complexity to the depth of the nesting. */ public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b, Iterator<? extends T> c, Iterator<? extends T> d) { return concat(ImmutableList.of(a, b, c, d).iterator()); } /** * Combines multiple iterators into a single iterator. The returned iterator * iterates across the elements of each iterator in {@code inputs}. The input * iterators are not polled until necessary. * * <p>The returned iterator supports {@code remove()} when the corresponding * input iterator supports it. * * <p><b>Note:</b> the current implementation is not suitable for nested * concatenated iterators, i.e. the following should be avoided when in a loop: * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the * resulting iterator has a cubic complexity to the depth of the nesting. * * @throws NullPointerException if any of the provided iterators is null */ public static <T> Iterator<T> concat(Iterator<? extends T>... inputs) { return concat(ImmutableList.copyOf(inputs).iterator()); } /** * Combines multiple iterators into a single iterator. The returned iterator * iterates across the elements of each iterator in {@code inputs}. The input * iterators are not polled until necessary. * * <p>The returned iterator supports {@code remove()} when the corresponding * input iterator supports it. The methods of the returned iterator may throw * {@code NullPointerException} if any of the input iterators is null. * * <p><b>Note:</b> the current implementation is not suitable for nested * concatenated iterators, i.e. the following should be avoided when in a loop: * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the * resulting iterator has a cubic complexity to the depth of the nesting. */ public static <T> Iterator<T> concat( final Iterator<? extends Iterator<? extends T>> inputs) { checkNotNull(inputs); return new Iterator<T>() { Iterator<? extends T> current = emptyIterator(); Iterator<? extends T> removeFrom; @Override public boolean hasNext() { // http://code.google.com/p/google-collections/issues/detail?id=151 // current.hasNext() might be relatively expensive, worth minimizing. boolean currentHasNext; // checkNotNull eager for GWT // note: it must be here & not where 'current' is assigned, // because otherwise we'll have called inputs.next() before throwing // the first NPE, and the next time around we'll call inputs.next() // again, incorrectly moving beyond the error. while (!(currentHasNext = checkNotNull(current).hasNext()) && inputs.hasNext()) { current = inputs.next(); } return currentHasNext; } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } removeFrom = current; return current.next(); } @Override public void remove() { checkRemove(removeFrom != null); removeFrom.remove(); removeFrom = null; } }; } /** * Divides an iterator into unmodifiable sublists of the given size (the final * list may be smaller). For example, partitioning an iterator containing * {@code [a, b, c, d, e]} with a partition size of 3 yields {@code * [[a, b, c], [d, e]]} -- an outer iterator containing two inner lists of * three and two elements, all in the original order. * * <p>The returned lists implement {@link java.util.RandomAccess}. * * @param iterator the iterator to return a partitioned view of * @param size the desired size of each partition (the last may be smaller) * @return an iterator of immutable lists containing the elements of {@code * iterator} divided into partitions * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T> UnmodifiableIterator<List<T>> partition( Iterator<T> iterator, int size) { return partitionImpl(iterator, size, false); } /** * Divides an iterator into unmodifiable sublists of the given size, padding * the final iterator with null values if necessary. For example, partitioning * an iterator containing {@code [a, b, c, d, e]} with a partition size of 3 * yields {@code [[a, b, c], [d, e, null]]} -- an outer iterator containing * two inner lists of three elements each, all in the original order. * * <p>The returned lists implement {@link java.util.RandomAccess}. * * @param iterator the iterator to return a partitioned view of * @param size the desired size of each partition * @return an iterator of immutable lists containing the elements of {@code * iterator} divided into partitions (the final iterable may have * trailing null elements) * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T> UnmodifiableIterator<List<T>> paddedPartition( Iterator<T> iterator, int size) { return partitionImpl(iterator, size, true); } private static <T> UnmodifiableIterator<List<T>> partitionImpl( final Iterator<T> iterator, final int size, final boolean pad) { checkNotNull(iterator); checkArgument(size > 0); return new UnmodifiableIterator<List<T>>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public List<T> next() { if (!hasNext()) { throw new NoSuchElementException(); } Object[] array = new Object[size]; int count = 0; for (; count < size && iterator.hasNext(); count++) { array[count] = iterator.next(); } for (int i = count; i < size; i++) { array[i] = null; // for GWT } @SuppressWarnings("unchecked") // we only put Ts in it List<T> list = Collections.unmodifiableList( (List<T>) Arrays.asList(array)); return (pad || count == size) ? list : list.subList(0, count); } }; } /** * Returns the elements of {@code unfiltered} that satisfy a predicate. */ public static <T> UnmodifiableIterator<T> filter( final Iterator<T> unfiltered, final Predicate<? super T> predicate) { checkNotNull(unfiltered); checkNotNull(predicate); return new AbstractIterator<T>() { @Override protected T computeNext() { while (unfiltered.hasNext()) { T element = unfiltered.next(); if (predicate.apply(element)) { return element; } } return endOfData(); } }; } /** * Returns {@code true} if one or more elements returned by {@code iterator} * satisfy the given predicate. */ public static <T> boolean any( Iterator<T> iterator, Predicate<? super T> predicate) { return indexOf(iterator, predicate) != -1; } /** * Returns {@code true} if every element returned by {@code iterator} * satisfies the given predicate. If {@code iterator} is empty, {@code true} * is returned. */ public static <T> boolean all( Iterator<T> iterator, Predicate<? super T> predicate) { checkNotNull(predicate); while (iterator.hasNext()) { T element = iterator.next(); if (!predicate.apply(element)) { return false; } } return true; } /** * Returns the first element in {@code iterator} that satisfies the given * predicate; use this method only when such an element is known to exist. If * no such element is found, the iterator will be left exhausted: its {@code * hasNext()} method will return {@code false}. If it is possible that * <i>no</i> element will match, use {@link #tryFind} or {@link * #find(Iterator, Predicate, Object)} instead. * * @throws NoSuchElementException if no element in {@code iterator} matches * the given predicate */ public static <T> T find( Iterator<T> iterator, Predicate<? super T> predicate) { return filter(iterator, predicate).next(); } /** * Returns the first element in {@code iterator} that satisfies the given * predicate. If no such element is found, {@code defaultValue} will be * returned from this method and the iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. Note that this can * usually be handled more naturally using {@code * tryFind(iterator, predicate).or(defaultValue)}. * * @since 7.0 */ @Nullable public static <T> T find(Iterator<? extends T> iterator, Predicate<? super T> predicate, @Nullable T defaultValue) { return getNext(filter(iterator, predicate), defaultValue); } /** * Returns an {@link Optional} containing the first element in {@code * iterator} that satisfies the given predicate, if such an element exists. If * no such element is found, an empty {@link Optional} will be returned from * this method and the iterator will be left exhausted: its {@code * hasNext()} method will return {@code false}. * * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code * null}. If {@code null} is matched in {@code iterator}, a * NullPointerException will be thrown. * * @since 11.0 */ public static <T> Optional<T> tryFind( Iterator<T> iterator, Predicate<? super T> predicate) { UnmodifiableIterator<T> filteredIterator = filter(iterator, predicate); return filteredIterator.hasNext() ? Optional.of(filteredIterator.next()) : Optional.<T>absent(); } /** * Returns the index in {@code iterator} of the first element that satisfies * the provided {@code predicate}, or {@code -1} if the Iterator has no such * elements. * * <p>More formally, returns the lowest index {@code i} such that * {@code predicate.apply(Iterators.get(iterator, i))} returns {@code true}, * or {@code -1} if there is no such index. * * <p>If -1 is returned, the iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. Otherwise, * the iterator will be set to the element which satisfies the * {@code predicate}. * * @since 2.0 */ public static <T> int indexOf( Iterator<T> iterator, Predicate<? super T> predicate) { checkNotNull(predicate, "predicate"); for (int i = 0; iterator.hasNext(); i++) { T current = iterator.next(); if (predicate.apply(current)) { return i; } } return -1; } /** * Returns an iterator that applies {@code function} to each element of {@code * fromIterator}. * * <p>The returned iterator supports {@code remove()} if the provided iterator * does. After a successful {@code remove()} call, {@code fromIterator} no * longer contains the corresponding element. */ public static <F, T> Iterator<T> transform(final Iterator<F> fromIterator, final Function<? super F, ? extends T> function) { checkNotNull(function); return new TransformedIterator<F, T>(fromIterator) { @Override T transform(F from) { return function.apply(from); } }; } /** * Advances {@code iterator} {@code position + 1} times, returning the * element at the {@code position}th position. * * @param position position of the element to return * @return the element at the specified position in {@code iterator} * @throws IndexOutOfBoundsException if {@code position} is negative or * greater than or equal to the number of elements remaining in * {@code iterator} */ public static <T> T get(Iterator<T> iterator, int position) { checkNonnegative(position); int skipped = advance(iterator, position); if (!iterator.hasNext()) { throw new IndexOutOfBoundsException("position (" + position + ") must be less than the number of elements that remained (" + skipped + ")"); } return iterator.next(); } static void checkNonnegative(int position) { if (position < 0) { throw new IndexOutOfBoundsException("position (" + position + ") must not be negative"); } } /** * Advances {@code iterator} {@code position + 1} times, returning the * element at the {@code position}th position or {@code defaultValue} * otherwise. * * @param position position of the element to return * @param defaultValue the default value to return if the iterator is empty * or if {@code position} is greater than the number of elements * remaining in {@code iterator} * @return the element at the specified position in {@code iterator} or * {@code defaultValue} if {@code iterator} produces fewer than * {@code position + 1} elements. * @throws IndexOutOfBoundsException if {@code position} is negative * @since 4.0 */ @Nullable public static <T> T get(Iterator<? extends T> iterator, int position, @Nullable T defaultValue) { checkNonnegative(position); advance(iterator, position); return getNext(iterator, defaultValue); } /** * Returns the next element in {@code iterator} or {@code defaultValue} if * the iterator is empty. The {@link Iterables} analog to this method is * {@link Iterables#getFirst}. * * @param defaultValue the default value to return if the iterator is empty * @return the next element of {@code iterator} or the default value * @since 7.0 */ @Nullable public static <T> T getNext(Iterator<? extends T> iterator, @Nullable T defaultValue) { return iterator.hasNext() ? iterator.next() : defaultValue; } /** * Advances {@code iterator} to the end, returning the last element. * * @return the last element of {@code iterator} * @throws NoSuchElementException if the iterator is empty */ public static <T> T getLast(Iterator<T> iterator) { while (true) { T current = iterator.next(); if (!iterator.hasNext()) { return current; } } } /** * Advances {@code iterator} to the end, returning the last element or * {@code defaultValue} if the iterator is empty. * * @param defaultValue the default value to return if the iterator is empty * @return the last element of {@code iterator} * @since 3.0 */ @Nullable public static <T> T getLast(Iterator<? extends T> iterator, @Nullable T defaultValue) { return iterator.hasNext() ? getLast(iterator) : defaultValue; } /** * Calls {@code next()} on {@code iterator}, either {@code numberToAdvance} times * or until {@code hasNext()} returns {@code false}, whichever comes first. * * @return the number of elements the iterator was advanced * @since 13.0 (since 3.0 as {@code Iterators.skip}) */ public static int advance(Iterator<?> iterator, int numberToAdvance) { checkNotNull(iterator); checkArgument(numberToAdvance >= 0, "numberToAdvance must be nonnegative"); int i; for (i = 0; i < numberToAdvance && iterator.hasNext(); i++) { iterator.next(); } return i; } /** * Creates an iterator returning the first {@code limitSize} elements of the * given iterator. If the original iterator does not contain that many * elements, the returned iterator will have the same behavior as the original * iterator. The returned iterator supports {@code remove()} if the original * iterator does. * * @param iterator the iterator to limit * @param limitSize the maximum number of elements in the returned iterator * @throws IllegalArgumentException if {@code limitSize} is negative * @since 3.0 */ public static <T> Iterator<T> limit( final Iterator<T> iterator, final int limitSize) { checkNotNull(iterator); checkArgument(limitSize >= 0, "limit is negative"); return new Iterator<T>() { private int count; @Override public boolean hasNext() { return count < limitSize && iterator.hasNext(); } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } count++; return iterator.next(); } @Override public void remove() { iterator.remove(); } }; } /** * Returns a view of the supplied {@code iterator} that removes each element * from the supplied {@code iterator} as it is returned. * * <p>The provided iterator must support {@link Iterator#remove()} or * else the returned iterator will fail on the first call to {@code * next}. * * @param iterator the iterator to remove and return elements from * @return an iterator that removes and returns elements from the * supplied iterator * @since 2.0 */ public static <T> Iterator<T> consumingIterator(final Iterator<T> iterator) { checkNotNull(iterator); return new UnmodifiableIterator<T>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { T next = iterator.next(); iterator.remove(); return next; } @Override public String toString() { return "Iterators.consumingIterator(...)"; } }; } /** * Deletes and returns the next value from the iterator, or returns * {@code null} if there is no such value. */ @Nullable static <T> T pollNext(Iterator<T> iterator) { if (iterator.hasNext()) { T result = iterator.next(); iterator.remove(); return result; } else { return null; } } // Methods only in Iterators, not in Iterables /** * Clears the iterator using its remove method. */ static void clear(Iterator<?> iterator) { checkNotNull(iterator); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } } /** * Returns an iterator containing the elements of {@code array} in order. The * returned iterator is a view of the array; subsequent changes to the array * will be reflected in the iterator. * * <p><b>Note:</b> It is often preferable to represent your data using a * collection type, for example using {@link Arrays#asList(Object[])}, making * this method unnecessary. * * <p>The {@code Iterable} equivalent of this method is either {@link * Arrays#asList(Object[])}, {@link ImmutableList#copyOf(Object[])}}, * or {@link ImmutableList#of}. */ public static <T> UnmodifiableIterator<T> forArray(final T... array) { return forArray(array, 0, array.length, 0); } /** * Returns a list iterator containing the elements in the specified range of * {@code array} in order, starting at the specified index. * * <p>The {@code Iterable} equivalent of this method is {@code * Arrays.asList(array).subList(offset, offset + length).listIterator(index)}. */ static <T> UnmodifiableListIterator<T> forArray( final T[] array, final int offset, int length, int index) { checkArgument(length >= 0); int end = offset + length; // Technically we should give a slightly more descriptive error on overflow Preconditions.checkPositionIndexes(offset, end, array.length); Preconditions.checkPositionIndex(index, length); if (length == 0) { return emptyListIterator(); } /* * We can't use call the two-arg constructor with arguments (offset, end) * because the returned Iterator is a ListIterator that may be moved back * past the beginning of the iteration. */ return new AbstractIndexedListIterator<T>(length, index) { @Override protected T get(int index) { return array[offset + index]; } }; } /** * Returns an iterator containing only {@code value}. * * <p>The {@link Iterable} equivalent of this method is {@link * Collections#singleton}. */ public static <T> UnmodifiableIterator<T> singletonIterator( @Nullable final T value) { return new UnmodifiableIterator<T>() { boolean done; @Override public boolean hasNext() { return !done; } @Override public T next() { if (done) { throw new NoSuchElementException(); } done = true; return value; } }; } /** * Adapts an {@code Enumeration} to the {@code Iterator} interface. * * <p>This method has no equivalent in {@link Iterables} because viewing an * {@code Enumeration} as an {@code Iterable} is impossible. However, the * contents can be <i>copied</i> into a collection using {@link * Collections#list}. */ public static <T> UnmodifiableIterator<T> forEnumeration( final Enumeration<T> enumeration) { checkNotNull(enumeration); return new UnmodifiableIterator<T>() { @Override public boolean hasNext() { return enumeration.hasMoreElements(); } @Override public T next() { return enumeration.nextElement(); } }; } /** * Adapts an {@code Iterator} to the {@code Enumeration} interface. * * <p>The {@code Iterable} equivalent of this method is either {@link * Collections#enumeration} (if you have a {@link Collection}), or * {@code Iterators.asEnumeration(collection.iterator())}. */ public static <T> Enumeration<T> asEnumeration(final Iterator<T> iterator) { checkNotNull(iterator); return new Enumeration<T>() { @Override public boolean hasMoreElements() { return iterator.hasNext(); } @Override public T nextElement() { return iterator.next(); } }; } /** * Implementation of PeekingIterator that avoids peeking unless necessary. */ private static class PeekingImpl<E> implements PeekingIterator<E> { private final Iterator<? extends E> iterator; private boolean hasPeeked; private E peekedElement; public PeekingImpl(Iterator<? extends E> iterator) { this.iterator = checkNotNull(iterator); } @Override public boolean hasNext() { return hasPeeked || iterator.hasNext(); } @Override public E next() { if (!hasPeeked) { return iterator.next(); } E result = peekedElement; hasPeeked = false; peekedElement = null; return result; } @Override public void remove() { checkState(!hasPeeked, "Can't remove after you've peeked at next"); iterator.remove(); } @Override public E peek() { if (!hasPeeked) { peekedElement = iterator.next(); hasPeeked = true; } return peekedElement; } } /** * Returns a {@code PeekingIterator} backed by the given iterator. * * <p>Calls to the {@code peek} method with no intervening calls to {@code * next} do not affect the iteration, and hence return the same object each * time. A subsequent call to {@code next} is guaranteed to return the same * object again. For example: <pre> {@code * * PeekingIterator<String> peekingIterator = * Iterators.peekingIterator(Iterators.forArray("a", "b")); * String a1 = peekingIterator.peek(); // returns "a" * String a2 = peekingIterator.peek(); // also returns "a" * String a3 = peekingIterator.next(); // also returns "a"}</pre> * * <p>Any structural changes to the underlying iteration (aside from those * performed by the iterator's own {@link PeekingIterator#remove()} method) * will leave the iterator in an undefined state. * * <p>The returned iterator does not support removal after peeking, as * explained by {@link PeekingIterator#remove()}. * * <p>Note: If the given iterator is already a {@code PeekingIterator}, * it <i>might</i> be returned to the caller, although this is neither * guaranteed to occur nor required to be consistent. For example, this * method <i>might</i> choose to pass through recognized implementations of * {@code PeekingIterator} when the behavior of the implementation is * known to meet the contract guaranteed by this method. * * <p>There is no {@link Iterable} equivalent to this method, so use this * method to wrap each individual iterator as it is generated. * * @param iterator the backing iterator. The {@link PeekingIterator} assumes * ownership of this iterator, so users should cease making direct calls * to it after calling this method. * @return a peeking iterator backed by that iterator. Apart from the * additional {@link PeekingIterator#peek()} method, this iterator behaves * exactly the same as {@code iterator}. */ public static <T> PeekingIterator<T> peekingIterator( Iterator<? extends T> iterator) { if (iterator instanceof PeekingImpl) { // Safe to cast <? extends T> to <T> because PeekingImpl only uses T // covariantly (and cannot be subclassed to add non-covariant uses). @SuppressWarnings("unchecked") PeekingImpl<T> peeking = (PeekingImpl<T>) iterator; return peeking; } return new PeekingImpl<T>(iterator); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <T> PeekingIterator<T> peekingIterator( PeekingIterator<T> iterator) { return checkNotNull(iterator); } /** * Returns an iterator over the merged contents of all given * {@code iterators}, traversing every element of the input iterators. * Equivalent entries will not be de-duplicated. * * <p>Callers must ensure that the source {@code iterators} are in * non-descending order as this method does not sort its input. * * <p>For any equivalent elements across all {@code iterators}, it is * undefined which element is returned first. * * @since 11.0 */ @Beta public static <T> UnmodifiableIterator<T> mergeSorted( Iterable<? extends Iterator<? extends T>> iterators, Comparator<? super T> comparator) { checkNotNull(iterators, "iterators"); checkNotNull(comparator, "comparator"); return new MergingIterator<T>(iterators, comparator); } /** * An iterator that performs a lazy N-way merge, calculating the next value * each time the iterator is polled. This amortizes the sorting cost over the * iteration and requires less memory than sorting all elements at once. * * <p>Retrieving a single element takes approximately O(log(M)) time, where M * is the number of iterators. (Retrieving all elements takes approximately * O(N*log(M)) time, where N is the total number of elements.) */ private static class MergingIterator<T> extends UnmodifiableIterator<T> { final Queue<PeekingIterator<T>> queue; public MergingIterator(Iterable<? extends Iterator<? extends T>> iterators, final Comparator<? super T> itemComparator) { // A comparator that's used by the heap, allowing the heap // to be sorted based on the top of each iterator. Comparator<PeekingIterator<T>> heapComparator = new Comparator<PeekingIterator<T>>() { @Override public int compare(PeekingIterator<T> o1, PeekingIterator<T> o2) { return itemComparator.compare(o1.peek(), o2.peek()); } }; queue = new PriorityQueue<PeekingIterator<T>>(2, heapComparator); for (Iterator<? extends T> iterator : iterators) { if (iterator.hasNext()) { queue.add(Iterators.peekingIterator(iterator)); } } } @Override public boolean hasNext() { return !queue.isEmpty(); } @Override public T next() { PeekingIterator<T> nextIter = queue.remove(); T next = nextIter.next(); if (nextIter.hasNext()) { queue.add(nextIter); } return next; } } /** * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */ static <T> ListIterator<T> cast(Iterator<T> iterator) { return (ListIterator<T>) iterator; } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/Iterators.java
Java
asf20
44,131
/* * 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 java.util.Collection; import java.util.List; import javax.annotation.Nullable; /** * GWT emulated version of {@link ImmutableList}. * TODO(cpovirk): more doc * * @author Hayward Chan */ abstract class ForwardingImmutableList<E> extends ImmutableList<E> { ForwardingImmutableList() { } abstract List<E> delegateList(); public int indexOf(@Nullable Object object) { return delegateList().indexOf(object); } public int lastIndexOf(@Nullable Object object) { return delegateList().lastIndexOf(object); } public E get(int index) { return delegateList().get(index); } public ImmutableList<E> subList(int fromIndex, int toIndex) { return unsafeDelegateList(delegateList().subList(fromIndex, toIndex)); } @Override public Object[] toArray() { // Note that ArrayList.toArray() doesn't work here because it returns E[] // instead of Object[]. return delegateList().toArray(new Object[size()]); } @Override public boolean equals(Object obj) { return delegateList().equals(obj); } @Override public int hashCode() { return delegateList().hashCode(); } @Override public UnmodifiableIterator<E> iterator() { return Iterators.unmodifiableIterator(delegateList().iterator()); } @Override public boolean contains(@Nullable Object object) { return object != null && delegateList().contains(object); } @Override public boolean containsAll(Collection<?> targets) { return delegateList().containsAll(targets); } public int size() { return delegateList().size(); } @Override public boolean isEmpty() { return delegateList().isEmpty(); } @Override public <T> T[] toArray(T[] other) { return delegateList().toArray(other); } @Override public String toString() { return delegateList().toString(); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ForwardingImmutableList.java
Java
asf20
2,469
/* * 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 java.util.Iterator; import java.util.LinkedList; import java.util.Queue; /** * Views elements of a type {@code T} as nodes in a tree, and provides methods to traverse the trees * induced by this traverser. * * <p>For example, the tree <pre> {@code * * h * / | \ * / e \ * d g * /|\ | * / | \ f * a b c * }</pre> * * can be iterated over in preorder (hdabcegf), postorder (abcdefgh), or breadth-first order * (hdegabc). * * <p>Null nodes are strictly forbidden. * * @author Louis Wasserman */ public abstract class TreeTraverser<T> { /** * Returns the children of the specified node. Must not contain null. */ public abstract Iterable<T> children(T root); /** * Returns an unmodifiable iterable over the nodes in a tree structure, using pre-order * traversal. That is, each node's subtrees are traversed after the node itself is returned. * * <p>No guarantees are made about the behavior of the traversal when nodes change while * iteration is in progress or when the iterators generated by {@link #children} are advanced. */ public final FluentIterable<T> preOrderTraversal(final T root) { checkNotNull(root); return new FluentIterable<T>() { @Override public UnmodifiableIterator<T> iterator() { return preOrderIterator(root); } }; } // overridden in BinaryTreeTraverser UnmodifiableIterator<T> preOrderIterator(T root) { return new PreOrderIterator(root); } private final class PreOrderIterator extends UnmodifiableIterator<T> { private final LinkedList<Iterator<T>> stack; PreOrderIterator(T root) { this.stack = Lists.newLinkedList(); stack.addLast(Iterators.singletonIterator(checkNotNull(root))); } @Override public boolean hasNext() { return !stack.isEmpty(); } @Override public T next() { Iterator<T> itr = stack.getLast(); // throws NSEE if empty T result = checkNotNull(itr.next()); if (!itr.hasNext()) { stack.removeLast(); } Iterator<T> childItr = children(result).iterator(); if (childItr.hasNext()) { stack.addLast(childItr); } return result; } } /** * Returns an unmodifiable iterable over the nodes in a tree structure, using post-order * traversal. That is, each node's subtrees are traversed before the node itself is returned. * * <p>No guarantees are made about the behavior of the traversal when nodes change while * iteration is in progress or when the iterators generated by {@link #children} are advanced. */ public final FluentIterable<T> postOrderTraversal(final T root) { checkNotNull(root); return new FluentIterable<T>() { @Override public UnmodifiableIterator<T> iterator() { return postOrderIterator(root); } }; } // overridden in BinaryTreeTraverser UnmodifiableIterator<T> postOrderIterator(T root) { return new PostOrderIterator(root); } private static final class PostOrderNode<T> { final T root; final Iterator<T> childIterator; PostOrderNode(T root, Iterator<T> childIterator) { this.root = checkNotNull(root); this.childIterator = checkNotNull(childIterator); } } private final class PostOrderIterator extends AbstractIterator<T> { private final LinkedList<PostOrderNode<T>> stack; PostOrderIterator(T root) { this.stack = Lists.newLinkedList(); stack.addLast(expand(root)); } @Override protected T computeNext() { while (!stack.isEmpty()) { PostOrderNode<T> top = stack.getLast(); if (top.childIterator.hasNext()) { T child = top.childIterator.next(); stack.addLast(expand(child)); } else { stack.removeLast(); return top.root; } } return endOfData(); } private PostOrderNode<T> expand(T t) { return new PostOrderNode<T>(t, children(t).iterator()); } } /** * Returns an unmodifiable iterable over the nodes in a tree structure, using breadth-first * traversal. That is, all the nodes of depth 0 are returned, then depth 1, then 2, and so on. * * <p>No guarantees are made about the behavior of the traversal when nodes change while * iteration is in progress or when the iterators generated by {@link #children} are advanced. */ public final FluentIterable<T> breadthFirstTraversal(final T root) { checkNotNull(root); return new FluentIterable<T>() { @Override public UnmodifiableIterator<T> iterator() { return new BreadthFirstIterator(root); } }; } private final class BreadthFirstIterator extends UnmodifiableIterator<T> implements PeekingIterator<T> { private final Queue<T> queue; BreadthFirstIterator(T root) { this.queue = Lists.newLinkedList(); queue.add(checkNotNull(root)); } @Override public boolean hasNext() { return !queue.isEmpty(); } @Override public T peek() { return queue.element(); } @Override public T next() { T result = queue.remove(); for (T child : children(result)) { queue.add(checkNotNull(child)); } return result; } } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/TreeTraverser.java
Java
asf20
6,037
/* * 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.Comparator; import java.util.SortedMap; /** * GWT emulated version of {@link RegularImmutableSortedMap}. * * @author Chris Povirk */ final class RegularImmutableSortedMap<K, V> extends ImmutableSortedMap<K, V> { RegularImmutableSortedMap(SortedMap<K, V> delegate, Comparator<? super K> comparator) { super(delegate, comparator); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/RegularImmutableSortedMap.java
Java
asf20
1,001
/* * 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.VisibleForTesting; import com.google.common.base.Preconditions; import java.util.Collection; import java.util.HashMap; 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); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/HashMultimap.java
Java
asf20
3,925
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.base.Function; import com.google.gwt.user.client.Timer; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; /** * MapMaker emulation. Since Javascript is single-threaded and have no references, this reduces to * the creation of expiring and computing maps. * * @author Charles Fry */ public final class MapMaker extends GenericMapMaker<Object, Object> { // TODO(fry,user): ConcurrentHashMap never throws a CME when mutating the map during iteration, but // this implementation (based on a LHM) does. This will all be replaced soon anyways, so leaving // it as is for now. private static class ExpiringComputingMap<K, V> extends LinkedHashMap<K, V> implements ConcurrentMap<K, V> { private final long expirationMillis; private final Function<? super K, ? extends V> computer; private final int maximumSize; ExpiringComputingMap( long expirationMillis, int maximumSize, int initialCapacity) { this(expirationMillis, null, maximumSize, initialCapacity); } ExpiringComputingMap(long expirationMillis, Function<? super K, ? extends V> computer, int maximumSize, int initialCapacity) { super(initialCapacity, /* ignored loadFactor */ 0.75f, (maximumSize != -1)); this.expirationMillis = expirationMillis; this.computer = computer; this.maximumSize = maximumSize; } @Override public V put(K key, V value) { V result = super.put(key, value); if (expirationMillis > 0) { scheduleRemoval(key, value); } return result; } @Override protected boolean removeEldestEntry(Map.Entry<K, V> ignored) { return (maximumSize == -1) ? false : size() > maximumSize; } @Override public V putIfAbsent(K key, V value) { if (!containsKey(key)) { return put(key, value); } else { return get(key); } } @Override public boolean remove(Object key, Object value) { if (containsKey(key) && get(key).equals(value)) { remove(key); return true; } return false; } @Override public boolean replace(K key, V oldValue, V newValue) { if (containsKey(key) && get(key).equals(oldValue)) { put(key, newValue); return true; } return false; } @Override public V replace(K key, V value) { return containsKey(key) ? put(key, value) : null; } private void scheduleRemoval(final K key, final V value) { // from MapMaker /* * TODO: Keep weak reference to map, too. Build a priority queue out of the entries themselves * instead of creating a task per entry. Then, we could have one recurring task per map (which * would clean the entire map and then reschedule itself depending upon when the next * expiration comes). We also want to avoid removing an entry prematurely if the entry was set * to the same value again. */ Timer timer = new Timer() { @Override public void run() { remove(key, value); } }; timer.schedule((int) expirationMillis); } @Override public V get(Object k) { // from CustomConcurrentHashMap V result = super.get(k); if (result == null && computer != null) { /* * This cast isn't safe, but we can rely on the fact that K is almost always passed to * Map.get(), and tools like IDEs and Findbugs can catch situations where this isn't the * case. * * The alternative is to add an overloaded method, but the chances of a user calling get() * instead of the new API and the risks inherent in adding a new API outweigh this little * hole. */ @SuppressWarnings("unchecked") K key = (K) k; result = compute(key); } return result; } private V compute(K key) { // from MapMaker V value; try { value = computer.apply(key); } catch (Throwable t) { throw new ComputationException(t); } if (value == null) { String message = computer + " returned null for key " + key + "."; throw new NullPointerException(message); } put(key, value); return value; } } private int initialCapacity = 16; private long expirationMillis = 0; private int maximumSize = -1; private boolean useCustomMap; public MapMaker() {} @Override public MapMaker initialCapacity(int initialCapacity) { if (initialCapacity < 0) { throw new IllegalArgumentException(); } this.initialCapacity = initialCapacity; return this; } @Override MapMaker expireAfterWrite(long duration, TimeUnit unit) { if (expirationMillis != 0) { throw new IllegalStateException( "expiration time of " + expirationMillis + " ns was already set"); } if (duration <= 0) { throw new IllegalArgumentException("invalid duration: " + duration); } this.expirationMillis = unit.toMillis(duration); useCustomMap = true; return this; } @Override MapMaker maximumSize(int maximumSize) { if (this.maximumSize != -1) { throw new IllegalStateException("maximum size of " + maximumSize + " was already set"); } if (maximumSize < 0) { throw new IllegalArgumentException("invalid maximum size: " + maximumSize); } this.maximumSize = maximumSize; useCustomMap = true; return this; } @Override public MapMaker concurrencyLevel(int concurrencyLevel) { if (concurrencyLevel < 1) { throw new IllegalArgumentException("GWT only supports a concurrency level of 1"); } // GWT technically only supports concurrencyLevel == 1, but we silently // ignore other positive values. return this; } @Override public <K, V> ConcurrentMap<K, V> makeMap() { return useCustomMap ? new ExpiringComputingMap<K, V>(expirationMillis, null, maximumSize, initialCapacity) : new ConcurrentHashMap<K, V>(initialCapacity); } @Override public <K, V> ConcurrentMap<K, V> makeComputingMap(Function<? super K, ? extends V> computer) { return new ExpiringComputingMap<K, V>( expirationMillis, computer, maximumSize, initialCapacity); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/MapMaker.java
Java
asf20
7,079
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Predicate; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.SortedSet; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; /** * {@code FluentIterable} provides a rich interface for manipulating {@code Iterable} instances in a * chained fashion. A {@code FluentIterable} can be created from an {@code Iterable}, or from a set * of elements. The following types of methods are provided on {@code FluentIterable}: * <ul> * <li>chained methods which return a new {@code FluentIterable} based in some way on the contents * of the current one (for example {@link #transform}) * <li>conversion methods which copy the {@code FluentIterable}'s contents into a new collection or * array (for example {@link #toList}) * <li>element extraction methods which facilitate the retrieval of certain elements (for example * {@link #last}) * <li>query methods which answer questions about the {@code FluentIterable}'s contents (for example * {@link #anyMatch}) * </ul> * * <p>Here is an example that merges the lists returned by two separate database calls, transforms * it by invoking {@code toString()} on each element, and returns the first 10 elements as an * {@code ImmutableList}: <pre> {@code * * FluentIterable * .from(database.getClientList()) * .filter(activeInLastMonth()) * .transform(Functions.toStringFunction()) * .limit(10) * .toList();}</pre> * * <p>Anything which can be done using {@code FluentIterable} could be done in a different fashion * (often with {@link Iterables}), however the use of {@code FluentIterable} makes many sets of * operations significantly more concise. * * @author Marcin Mikosik * @since 12.0 */ @GwtCompatible(emulated = true) public abstract class FluentIterable<E> implements Iterable<E> { // We store 'iterable' and use it instead of 'this' to allow Iterables to perform instanceof // checks on the _original_ iterable when FluentIterable.from is used. private final Iterable<E> iterable; /** Constructor for use by subclasses. */ protected FluentIterable() { this.iterable = this; } FluentIterable(Iterable<E> iterable) { this.iterable = checkNotNull(iterable); } /** * Returns a fluent iterable that wraps {@code iterable}, or {@code iterable} itself if it * is already a {@code FluentIterable}. */ public static <E> FluentIterable<E> from(final Iterable<E> iterable) { return (iterable instanceof FluentIterable) ? (FluentIterable<E>) iterable : new FluentIterable<E>(iterable) { @Override public Iterator<E> iterator() { return iterable.iterator(); } }; } /** * Construct a fluent iterable from another fluent iterable. This is obviously never necessary, * but is intended to help call out cases where one migration from {@code Iterable} to * {@code FluentIterable} has obviated the need to explicitly convert to a {@code FluentIterable}. * * @deprecated instances of {@code FluentIterable} don't need to be converted to * {@code FluentIterable} */ @Deprecated public static <E> FluentIterable<E> from(FluentIterable<E> iterable) { return checkNotNull(iterable); } /** * Returns a string representation of this fluent iterable, with the format * {@code [e1, e2, ..., en]}. */ @Override public String toString() { return Iterables.toString(iterable); } /** * Returns the number of elements in this fluent iterable. */ public final int size() { return Iterables.size(iterable); } /** * Returns {@code true} if this fluent iterable contains any object for which * {@code equals(element)} is true. */ public final boolean contains(@Nullable Object element) { return Iterables.contains(iterable, element); } /** * Returns a fluent iterable whose {@code Iterator} cycles indefinitely over the elements of * this fluent iterable. * * <p>That iterator supports {@code remove()} if {@code iterable.iterator()} does. After * {@code remove()} is called, subsequent cycles omit the removed element, which is no longer in * this fluent iterable. The iterator's {@code hasNext()} method returns {@code true} until * this fluent iterable is empty. * * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You * should use an explicit {@code break} or be certain that you will eventually remove all the * elements. */ @CheckReturnValue public final FluentIterable<E> cycle() { return from(Iterables.cycle(iterable)); } /** * Returns the elements from this fluent iterable that satisfy a predicate. The * resulting fluent iterable's iterator does not support {@code remove()}. */ @CheckReturnValue public final FluentIterable<E> filter(Predicate<? super E> predicate) { return from(Iterables.filter(iterable, predicate)); } /** * Returns {@code true} if any element in this fluent iterable satisfies the predicate. */ public final boolean anyMatch(Predicate<? super E> predicate) { return Iterables.any(iterable, predicate); } /** * Returns {@code true} if every element in this fluent iterable satisfies the predicate. * If this fluent iterable is empty, {@code true} is returned. */ public final boolean allMatch(Predicate<? super E> predicate) { return Iterables.all(iterable, predicate); } /** * Returns an {@link Optional} containing the first element in this fluent iterable that * satisfies the given predicate, if such an element exists. * * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code null}. If {@code null} * is matched in this fluent iterable, a {@link NullPointerException} will be thrown. */ public final Optional<E> firstMatch(Predicate<? super E> predicate) { return Iterables.tryFind(iterable, predicate); } /** * Returns a fluent iterable that applies {@code function} to each element of this * fluent iterable. * * <p>The returned fluent iterable's iterator supports {@code remove()} if this iterable's * iterator does. After a successful {@code remove()} call, this fluent iterable no longer * contains the corresponding element. */ public final <T> FluentIterable<T> transform(Function<? super E, T> function) { return from(Iterables.transform(iterable, function)); } /** * Applies {@code function} to each element of this fluent iterable and returns * a fluent iterable with the concatenated combination of results. {@code function} * returns an Iterable of results. * * <p>The returned fluent iterable's iterator supports {@code remove()} if this * function-returned iterables' iterator does. After a successful {@code remove()} call, * the returned fluent iterable no longer contains the corresponding element. * * @since 13.0 (required {@code Function<E, Iterable<T>>} until 14.0) */ public <T> FluentIterable<T> transformAndConcat( Function<? super E, ? extends Iterable<? extends T>> function) { return from(Iterables.concat(transform(function))); } /** * Returns an {@link Optional} containing the first element in this fluent iterable. * If the iterable is empty, {@code Optional.absent()} is returned. * * @throws NullPointerException if the first element is null; if this is a possibility, use * {@code iterator().next()} or {@link Iterables#getFirst} instead. */ public final Optional<E> first() { Iterator<E> iterator = iterable.iterator(); return iterator.hasNext() ? Optional.of(iterator.next()) : Optional.<E>absent(); } /** * Returns an {@link Optional} containing the last element in this fluent iterable. * If the iterable is empty, {@code Optional.absent()} is returned. * * @throws NullPointerException if the last element is null; if this is a possibility, use * {@link Iterables#getLast} instead. */ public final Optional<E> last() { // Iterables#getLast was inlined here so we don't have to throw/catch a NSEE // TODO(kevinb): Support a concurrently modified collection? if (iterable instanceof List) { List<E> list = (List<E>) iterable; if (list.isEmpty()) { return Optional.absent(); } return Optional.of(list.get(list.size() - 1)); } Iterator<E> iterator = iterable.iterator(); if (!iterator.hasNext()) { return Optional.absent(); } /* * TODO(kevinb): consider whether this "optimization" is worthwhile. Users * with SortedSets tend to know they are SortedSets and probably would not * call this method. */ if (iterable instanceof SortedSet) { SortedSet<E> sortedSet = (SortedSet<E>) iterable; return Optional.of(sortedSet.last()); } while (true) { E current = iterator.next(); if (!iterator.hasNext()) { return Optional.of(current); } } } /** * Returns a view of this fluent iterable that skips its first {@code numberToSkip} * elements. If this fluent iterable contains fewer than {@code numberToSkip} elements, * the returned fluent iterable skips all of its elements. * * <p>Modifications to this fluent iterable before a call to {@code iterator()} are * reflected in the returned fluent iterable. That is, the its iterator skips the first * {@code numberToSkip} elements that exist when the iterator is created, not when {@code skip()} * is called. * * <p>The returned fluent iterable's iterator supports {@code remove()} if the * {@code Iterator} of this fluent iterable supports it. Note that it is <i>not</i> * possible to delete the last skipped element by immediately calling {@code remove()} on the * returned fluent iterable's iterator, as the {@code Iterator} contract states that a call * to {@code * remove()} before a call to {@code next()} will throw an * {@link IllegalStateException}. */ @CheckReturnValue public final FluentIterable<E> skip(int numberToSkip) { return from(Iterables.skip(iterable, numberToSkip)); } /** * Creates a fluent iterable with the first {@code size} elements of this * fluent iterable. If this fluent iterable does not contain that many elements, * the returned fluent iterable will have the same behavior as this fluent iterable. * The returned fluent iterable's iterator supports {@code remove()} if this * fluent iterable's iterator does. * * @param size the maximum number of elements in the returned fluent iterable * @throws IllegalArgumentException if {@code size} is negative */ @CheckReturnValue public final FluentIterable<E> limit(int size) { return from(Iterables.limit(iterable, size)); } /** * Determines whether this fluent iterable is empty. */ public final boolean isEmpty() { return !iterable.iterator().hasNext(); } /** * Returns an {@code ImmutableList} containing all of the elements from this fluent iterable in * proper sequence. * * @since 14.0 (since 12.0 as {@code toImmutableList()}). */ public final ImmutableList<E> toList() { return ImmutableList.copyOf(iterable); } /** * Returns an {@code ImmutableList} containing all of the elements from this {@code * FluentIterable} in the order specified by {@code comparator}. To produce an {@code * ImmutableList} sorted by its natural ordering, use {@code toSortedList(Ordering.natural())}. * * @param comparator the function by which to sort list elements * @throws NullPointerException if any element is null * @since 14.0 (since 13.0 as {@code toSortedImmutableList()}). */ @Beta public final ImmutableList<E> toSortedList(Comparator<? super E> comparator) { return Ordering.from(comparator).immutableSortedCopy(iterable); } /** * Returns an {@code ImmutableSet} containing all of the elements from this fluent iterable with * duplicates removed. * * @since 14.0 (since 12.0 as {@code toImmutableSet()}). */ public final ImmutableSet<E> toSet() { return ImmutableSet.copyOf(iterable); } /** * Returns an {@code ImmutableSortedSet} containing all of the elements from this {@code * FluentIterable} in the order specified by {@code comparator}, with duplicates (determined by * {@code comparator.compare(x, y) == 0}) removed. To produce an {@code ImmutableSortedSet} sorted * by its natural ordering, use {@code toSortedSet(Ordering.natural())}. * * @param comparator the function by which to sort set elements * @throws NullPointerException if any element is null * @since 14.0 (since 12.0 as {@code toImmutableSortedSet()}). */ public final ImmutableSortedSet<E> toSortedSet(Comparator<? super E> comparator) { return ImmutableSortedSet.copyOf(comparator, iterable); } /** * Returns an immutable map for which the elements of this {@code FluentIterable} are the keys in * the same order, mapped to values by the given function. If this iterable contains duplicate * elements, the returned map will contain each distinct element once in the order it first * appears. * * @throws NullPointerException if any element of this iterable is {@code null}, or if {@code * valueFunction} produces {@code null} for any key * @since 14.0 */ public final <V> ImmutableMap<E, V> toMap(Function<? super E, V> valueFunction) { return Maps.toMap(iterable, valueFunction); } /** * Creates an index {@code ImmutableListMultimap} that contains the results of applying a * specified function to each item in this {@code FluentIterable} of values. Each element of this * iterable will be stored as a value in the resulting multimap, yielding a multimap with the same * size as this iterable. The key used to store that value in the multimap will be the result of * calling the function on that value. The resulting multimap is created as an immutable snapshot. * In the returned multimap, keys appear in the order they are first encountered, and the values * corresponding to each key appear in the same order as they are encountered. * * @param keyFunction the function used to produce the key for each value * @throws NullPointerException if any of the following cases is true: * <ul> * <li>{@code keyFunction} is null * <li>An element in this fluent iterable is null * <li>{@code keyFunction} returns {@code null} for any element of this iterable * </ul> * @since 14.0 */ public final <K> ImmutableListMultimap<K, E> index(Function<? super E, K> keyFunction) { return Multimaps.index(iterable, keyFunction); } /** * Returns an immutable map for which the {@link java.util.Map#values} are the elements of this * {@code FluentIterable} in the given order, and each key is the product of invoking a supplied * function on its corresponding value. * * @param keyFunction the function used to produce the key for each value * @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one * value in this fluent iterable * @throws NullPointerException if any element of this fluent iterable is null, or if * {@code keyFunction} produces {@code null} for any value * @since 14.0 */ public final <K> ImmutableMap<K, E> uniqueIndex(Function<? super E, K> keyFunction) { return Maps.uniqueIndex(iterable, keyFunction); } /** * Copies all the elements from this fluent iterable to {@code collection}. This is equivalent to * calling {@code Iterables.addAll(collection, this)}. * * @param collection the collection to copy elements to * @return {@code collection}, for convenience * @since 14.0 */ public final <C extends Collection<? super E>> C copyInto(C collection) { checkNotNull(collection); if (iterable instanceof Collection) { collection.addAll(Collections2.cast(iterable)); } else { for (E item : iterable) { collection.add(item); } } return collection; } /** * Returns the element at the specified position in this fluent iterable. * * @param position position of the element to return * @return the element at the specified position in this fluent iterable * @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to * the size of this fluent iterable */ public final E get(int position) { return Iterables.get(iterable, position); } /** * Function that transforms {@code Iterable<E>} into a fluent iterable. */ private static class FromIterableFunction<E> implements Function<Iterable<E>, FluentIterable<E>> { @Override public FluentIterable<E> apply(Iterable<E> fromObject) { return FluentIterable.from(fromObject); } } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/FluentIterable.java
Java
asf20
17,922
/* * 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.LinkedHashMap; /** * A {@code Multiset} implementation with predictable iteration order. Its * iterator orders elements according to when the first occurrence of the * element was added. When the multiset contains multiple instances of an * element, those instances are consecutive in the iteration order. If all * occurrences of an element are removed, after which that element is added to * the multiset, the element will appear at the end of the iteration. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset"> * {@code Multiset}</a>. * * @author Kevin Bourrillion * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // we're overriding default serialization public final class LinkedHashMultiset<E> extends AbstractMapBasedMultiset<E> { /** * Creates a new, empty {@code LinkedHashMultiset} using the default initial * capacity. */ public static <E> LinkedHashMultiset<E> create() { return new LinkedHashMultiset<E>(); } /** * Creates a new, empty {@code LinkedHashMultiset} with the specified expected * number of distinct elements. * * @param distinctElements the expected number of distinct elements * @throws IllegalArgumentException if {@code distinctElements} is negative */ public static <E> LinkedHashMultiset<E> create(int distinctElements) { return new LinkedHashMultiset<E>(distinctElements); } /** * Creates a new {@code LinkedHashMultiset} containing the specified elements. * * <p>This implementation is highly efficient when {@code elements} is itself * a {@link Multiset}. * * @param elements the elements that the multiset should contain */ public static <E> LinkedHashMultiset<E> create( Iterable<? extends E> elements) { LinkedHashMultiset<E> multiset = create(Multisets.inferDistinctElements(elements)); Iterables.addAll(multiset, elements); return multiset; } private LinkedHashMultiset() { super(new LinkedHashMap<E, Count>()); } private LinkedHashMultiset(int distinctElements) { // Could use newLinkedHashMapWithExpectedSize() if it existed super(new LinkedHashMap<E, Count>(Maps.capacity(distinctElements))); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/LinkedHashMultiset.java
Java
asf20
3,088
/* * This file is a modified version of * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/main/java/util/concurrent/TimeUnit.java * which contained the following notice: * * 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/ */ package java.util.concurrent; /** * GWT emulation of TimeUnit, created by removing unsupported operations from * Doug Lea's public domain version. */ public enum TimeUnit { NANOSECONDS { public long toNanos(long d) { return d; } public long toMicros(long d) { return d/(C1/C0); } public long toMillis(long d) { return d/(C2/C0); } public long toSeconds(long d) { return d/(C3/C0); } public long toMinutes(long d) { return d/(C4/C0); } public long toHours(long d) { return d/(C5/C0); } public long toDays(long d) { return d/(C6/C0); } public long convert(long d, TimeUnit u) { return u.toNanos(d); } int excessNanos(long d, long m) { return (int)(d - (m*C2)); } }, MICROSECONDS { public long toNanos(long d) { return x(d, C1/C0, MAX/(C1/C0)); } public long toMicros(long d) { return d; } public long toMillis(long d) { return d/(C2/C1); } public long toSeconds(long d) { return d/(C3/C1); } public long toMinutes(long d) { return d/(C4/C1); } public long toHours(long d) { return d/(C5/C1); } public long toDays(long d) { return d/(C6/C1); } public long convert(long d, TimeUnit u) { return u.toMicros(d); } int excessNanos(long d, long m) { return (int)((d*C1) - (m*C2)); } }, MILLISECONDS { public long toNanos(long d) { return x(d, C2/C0, MAX/(C2/C0)); } public long toMicros(long d) { return x(d, C2/C1, MAX/(C2/C1)); } public long toMillis(long d) { return d; } public long toSeconds(long d) { return d/(C3/C2); } public long toMinutes(long d) { return d/(C4/C2); } public long toHours(long d) { return d/(C5/C2); } public long toDays(long d) { return d/(C6/C2); } public long convert(long d, TimeUnit u) { return u.toMillis(d); } int excessNanos(long d, long m) { return 0; } }, SECONDS { public long toNanos(long d) { return x(d, C3/C0, MAX/(C3/C0)); } public long toMicros(long d) { return x(d, C3/C1, MAX/(C3/C1)); } public long toMillis(long d) { return x(d, C3/C2, MAX/(C3/C2)); } public long toSeconds(long d) { return d; } public long toMinutes(long d) { return d/(C4/C3); } public long toHours(long d) { return d/(C5/C3); } public long toDays(long d) { return d/(C6/C3); } public long convert(long d, TimeUnit u) { return u.toSeconds(d); } int excessNanos(long d, long m) { return 0; } }, MINUTES { public long toNanos(long d) { return x(d, C4/C0, MAX/(C4/C0)); } public long toMicros(long d) { return x(d, C4/C1, MAX/(C4/C1)); } public long toMillis(long d) { return x(d, C4/C2, MAX/(C4/C2)); } public long toSeconds(long d) { return x(d, C4/C3, MAX/(C4/C3)); } public long toMinutes(long d) { return d; } public long toHours(long d) { return d/(C5/C4); } public long toDays(long d) { return d/(C6/C4); } public long convert(long d, TimeUnit u) { return u.toMinutes(d); } int excessNanos(long d, long m) { return 0; } }, HOURS { public long toNanos(long d) { return x(d, C5/C0, MAX/(C5/C0)); } public long toMicros(long d) { return x(d, C5/C1, MAX/(C5/C1)); } public long toMillis(long d) { return x(d, C5/C2, MAX/(C5/C2)); } public long toSeconds(long d) { return x(d, C5/C3, MAX/(C5/C3)); } public long toMinutes(long d) { return x(d, C5/C4, MAX/(C5/C4)); } public long toHours(long d) { return d; } public long toDays(long d) { return d/(C6/C5); } public long convert(long d, TimeUnit u) { return u.toHours(d); } int excessNanos(long d, long m) { return 0; } }, DAYS { public long toNanos(long d) { return x(d, C6/C0, MAX/(C6/C0)); } public long toMicros(long d) { return x(d, C6/C1, MAX/(C6/C1)); } public long toMillis(long d) { return x(d, C6/C2, MAX/(C6/C2)); } public long toSeconds(long d) { return x(d, C6/C3, MAX/(C6/C3)); } public long toMinutes(long d) { return x(d, C6/C4, MAX/(C6/C4)); } public long toHours(long d) { return x(d, C6/C5, MAX/(C6/C5)); } public long toDays(long d) { return d; } public long convert(long d, TimeUnit u) { return u.toDays(d); } int excessNanos(long d, long m) { return 0; } }; // Handy constants for conversion methods static final long C0 = 1L; static final long C1 = C0 * 1000L; static final long C2 = C1 * 1000L; static final long C3 = C2 * 1000L; static final long C4 = C3 * 60L; static final long C5 = C4 * 60L; static final long C6 = C5 * 24L; static final long MAX = Long.MAX_VALUE; static long x(long d, long m, long over) { if (d > over) return Long.MAX_VALUE; if (d < -over) return Long.MIN_VALUE; return d * m; } // exceptions below changed from AbstractMethodError for GWT public long convert(long sourceDuration, TimeUnit sourceUnit) { throw new AssertionError(); } public long toNanos(long duration) { throw new AssertionError(); } public long toMicros(long duration) { throw new AssertionError(); } public long toMillis(long duration) { throw new AssertionError(); } public long toSeconds(long duration) { throw new AssertionError(); } public long toMinutes(long duration) { throw new AssertionError(); } public long toHours(long duration) { throw new AssertionError(); } public long toDays(long duration) { throw new AssertionError(); } abstract int excessNanos(long d, long m); }
zzhhhhh-aw4rwer
guava-gwt/src-super/java/util/super/java/util/concurrent/TimeUnit.java
Java
asf20
5,795
/* * 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 java.util.concurrent; /** * Emulation of ExecutionException. * * @author Charles Fry */ public class ExecutionException extends Exception { protected ExecutionException() { } protected ExecutionException(String message) { super(message); } public ExecutionException(String message, Throwable cause) { super(message, cause); } public ExecutionException(Throwable cause) { super(cause); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/java/util/super/java/util/concurrent/ExecutionException.java
Java
asf20
1,033
/* * 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 java.util.concurrent; import java.util.Map; /** * Minimal GWT emulation of a map providing atomic operations. * * @author Jesse Wilson */ public interface ConcurrentMap<K, V> extends Map<K, V> { V putIfAbsent(K key, V value); boolean remove(Object key, Object value); V replace(K key, V value); boolean replace(K key, V oldValue, V newValue); }
zzhhhhh-aw4rwer
guava-gwt/src-super/java/util/super/java/util/concurrent/ConcurrentMap.java
Java
asf20
973
/* * 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 java.util.concurrent.atomic; /** * GWT emulated version of {@link AtomicInteger}. It's a thin wrapper * around the primitive {@code int}. * * @author Hayward Chan */ public class AtomicInteger extends Number implements java.io.Serializable { private int value; public AtomicInteger(int initialValue) { value = initialValue; } public AtomicInteger() { } public final int get() { return value; } public final void set(int newValue) { value = newValue; } public final void lazySet(int newValue) { set(newValue); } public final int getAndSet(int newValue) { int current = value; value = newValue; return current; } public final boolean compareAndSet(int expect, int update) { if (value == expect) { value = update; return true; } else { return false; } } public final int getAndIncrement() { return value++; } public final int getAndDecrement() { return value--; } public final int getAndAdd(int delta) { int current = value; value += delta; return current; } public final int incrementAndGet() { return ++value; } public final int decrementAndGet() { return --value; } public final int addAndGet(int delta) { value += delta; return value; } @Override public String toString() { return Integer.toString(value); } public int intValue() { return value; } public long longValue() { return (long) value; } public float floatValue() { return (float) value; } public double doubleValue() { return (double) value; } }
zzhhhhh-aw4rwer
guava-gwt/src-super/java/util/super/java/util/concurrent/atomic/AtomicInteger.java
Java
asf20
2,231
/* * 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 java.util.concurrent.atomic; /** * GWT emulated version of {@link AtomicLong}. It's a thin wrapper * around the primitive {@code long}. * * @author Jige Yu */ public class AtomicLong extends Number implements java.io.Serializable { private long value; public AtomicLong(long initialValue) { this.value = initialValue; } public AtomicLong() { } public final long get() { return value; } public final void set(long newValue) { value = newValue; } public final void lazySet(long newValue) { set(newValue); } public final long getAndSet(long newValue) { long current = value; value = newValue; return current; } public final boolean compareAndSet(long expect, long update) { if (value == expect) { value = update; return true; } else { return false; } } public final long getAndIncrement() { return value++; } public final long getAndDecrement() { return value--; } public final long getAndAdd(long delta) { long current = value; value += delta; return current; } public final long incrementAndGet() { return ++value; } public final long decrementAndGet() { return --value; } public final long addAndGet(long delta) { value += delta; return value; } @Override public String toString() { return Long.toString(value); } public int intValue() { return (int) value; } public long longValue() { return value; } public float floatValue() { return (float) value; } public double doubleValue() { return (double) value; } }
zzhhhhh-aw4rwer
guava-gwt/src-super/java/util/super/java/util/concurrent/atomic/AtomicLong.java
Java
asf20
2,235
/* * 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 java.util.concurrent; /** * Emulation of Callable. * * @author Charles Fry */ public interface Callable<V> { V call() throws Exception; }
zzhhhhh-aw4rwer
guava-gwt/src-super/java/util/super/java/util/concurrent/Callable.java
Java
asf20
755
/* * 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 java.util.concurrent; import java.util.AbstractMap; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Minimal emulation of {@link java.util.concurrent.ConcurrentHashMap}. * Note that javascript intepreter is <a * href="http://code.google.com/docreader/#p=google-web-toolkit-doc-1-5&t=DevGuideJavaCompatibility"> * single-threaded</a>, it is essentially a {@link java.util.HashMap}, * implementing the new methods introduced by {@link ConcurrentMap}. * * @author Hayward Chan */ public class ConcurrentHashMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V> { private final Map<K, V> backingMap; public ConcurrentHashMap() { this.backingMap = new HashMap<K, V>(); } public ConcurrentHashMap(int initialCapacity) { this.backingMap = new HashMap<K, V>(initialCapacity); } public ConcurrentHashMap(int initialCapacity, float loadFactor) { this.backingMap = new HashMap<K, V>(initialCapacity, loadFactor); } public ConcurrentHashMap(Map<? extends K, ? extends V> t) { this.backingMap = new HashMap<K, V>(t); } public V putIfAbsent(K key, V value) { if (!containsKey(key)) { return put(key, value); } else { return get(key); } } public boolean remove(Object key, Object value) { if (containsKey(key) && get(key).equals(value)) { remove(key); return true; } else { return false; } } public boolean replace(K key, V oldValue, V newValue) { if (oldValue == null || newValue == null) { throw new NullPointerException(); } else if (containsKey(key) && get(key).equals(oldValue)) { put(key, newValue); return true; } else { return false; } } public V replace(K key, V value) { if (value == null) { throw new NullPointerException(); } else if (containsKey(key)) { return put(key, value); } else { return null; } } @Override public boolean containsKey(Object key) { if (key == null) { throw new NullPointerException(); } return backingMap.containsKey(key); } @Override public V get(Object key) { if (key == null) { throw new NullPointerException(); } return backingMap.get(key); } @Override public V put(K key, V value) { if (key == null || value == null) { throw new NullPointerException(); } return backingMap.put(key, value); } @Override public boolean containsValue(Object value) { if (value == null) { throw new NullPointerException(); } return backingMap.containsValue(value); } @Override public V remove(Object key) { if (key == null) { throw new NullPointerException(); } return backingMap.remove(key); } @Override public Set<Entry<K, V>> entrySet() { return backingMap.entrySet(); } public boolean contains(Object value) { return containsValue(value); } public Enumeration<V> elements() { return Collections.enumeration(values()); } public Enumeration<K> keys() { return Collections.enumeration(keySet()); } }
zzhhhhh-aw4rwer
guava-gwt/src-super/java/util/super/java/util/concurrent/ConcurrentHashMap.java
Java
asf20
3,768
/* * 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 java.nio.charset; /** * GWT emulation of {@link UnsupportedCharsetException}. * * @author Gregory Kick */ public class UnsupportedCharsetException extends IllegalArgumentException { private final String charsetName; public UnsupportedCharsetException(String charsetName) { super(String.valueOf(charsetName)); this.charsetName = charsetName; } public String getCharsetName() { return charsetName; } }
zzhhhhh-aw4rwer
guava-gwt/src-super/java/nio/charset/UnsupportedCharsetException.java
Java
asf20
1,039
/* * 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 java.nio.charset; import java.util.Collections; import java.util.SortedMap; import java.util.TreeMap; /** * A minimal GWT emulation of {@link Charset}. * * @author Gregory Kick */ public abstract class Charset implements Comparable<Charset> { private static final Charset UTF_8 = new Charset("UTF-8") {}; private static final SortedMap<String, Charset> AVAILABLE_CHARSETS = new TreeMap<String, Charset>(); static { AVAILABLE_CHARSETS.put(UTF_8.name(), UTF_8); } public static SortedMap<String, Charset> availableCharsets() { return Collections.unmodifiableSortedMap(AVAILABLE_CHARSETS); } public static Charset forName(String charsetName) { if (charsetName == null) { throw new IllegalArgumentException("Null charset name"); } int length = charsetName.length(); if (length == 0) { throw new IllegalCharsetNameException(charsetName); } for (int i = 0; i < length; i++) { char c = charsetName.charAt(i); if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '-' && i != 0) || (c == ':' && i != 0) || (c == '_' && i != 0) || (c == '.' && i != 0)) { continue; } throw new IllegalCharsetNameException(charsetName); } Charset charset = AVAILABLE_CHARSETS.get(charsetName.toUpperCase()); if (charset != null) { return charset; } throw new UnsupportedCharsetException(charsetName); } private final String name; private Charset(String name) { this.name = name; } public final String name() { return name; } public final int compareTo(Charset that) { return this.name.compareToIgnoreCase(that.name); } public final int hashCode() { return name.hashCode(); } public final boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof Charset) { Charset that = (Charset) o; return this.name.equals(that.name); } else { return false; } } public final String toString() { return name; } }
zzhhhhh-aw4rwer
guava-gwt/src-super/java/nio/charset/Charset.java
Java
asf20
2,724
/* * 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 java.nio.charset; /** * GWT emulation of {@link IllegalCharsetNameException}. * * @author Gregory Kick */ public class IllegalCharsetNameException extends IllegalArgumentException { private final String charsetName; public IllegalCharsetNameException(String charsetName) { super(String.valueOf(charsetName)); this.charsetName = charsetName; } public String getCharsetName() { return charsetName; } }
zzhhhhh-aw4rwer
guava-gwt/src-super/java/nio/charset/IllegalCharsetNameException.java
Java
asf20
1,039
/* * 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; import com.google.gwt.core.client.EntryPoint; /** * A dummy entry point to convince Maven to compile our classes. * * @author Chris Povirk */ public class ForceGuavaCompilationEntryPoint implements EntryPoint { @Override public void onModuleLoad() { } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/ForceGuavaCompilationEntryPoint.java
Java
asf20
893
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@code UnsignedLong}. * * @author Louis Wasserman */ public class UnsignedLong_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, UnsignedLong instance) {} public static UnsignedLong instantiate(SerializationStreamReader reader) throws SerializationException { return UnsignedLong.fromLongBits(reader.readLong()); } public static void serialize(SerializationStreamWriter writer, UnsignedLong instance) throws SerializationException { writer.writeLong(instance.longValue()); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/primitives/UnsignedLong_CustomFieldSerializer.java
Java
asf20
1,439
/* * 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.base; import com.google.common.annotations.GwtCompatible; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * Custom GWT serializer for {@link Absent}. * * <p>GWT can serialize an absent {@code Optional} on its own, but the resulting object is a * different instance than the singleton {@code Absent.INSTANCE}, which breaks equality. We * implement a custom serializer to maintain the singleton property. * * @author Chris Povirk */ @GwtCompatible public class Absent_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, Absent<?> instance) {} public static Absent<?> instantiate(SerializationStreamReader reader) { return Absent.INSTANCE; } public static void serialize(SerializationStreamWriter writer, Absent<?> instance) {} }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/base/Absent_CustomFieldSerializer.java
Java
asf20
1,502
/* * 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.base; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * GWT serialization logic for {@link PairwiseEquivalence}. * * @author Kedar Kanitkar */ public class PairwiseEquivalence_CustomFieldSerializer { private PairwiseEquivalence_CustomFieldSerializer() {} public static void deserialize(SerializationStreamReader reader, PairwiseEquivalence<?> instance) {} public static PairwiseEquivalence<?> instantiate(SerializationStreamReader reader) throws SerializationException { return create((Equivalence<?>) reader.readObject()); } private static <T> PairwiseEquivalence<T> create(Equivalence<T> elementEquivalence) { return new PairwiseEquivalence<T>(elementEquivalence); } public static void serialize(SerializationStreamWriter writer, PairwiseEquivalence<?> instance) throws SerializationException { writer.writeObject(instance.elementEquivalence); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/base/PairwiseEquivalence_CustomFieldSerializer.java
Java
asf20
1,683
/* * 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.base; import com.google.common.annotations.GwtCompatible; import java.util.Set; import javax.annotation.Nullable; /** * Contains dummy collection implementations to convince GWT that part of * serializing a collection is serializing its elements. * * <p>See {@linkplain com.google.common.collect.GwtSerializationDependencies the * com.google.common.collect version} for more details. * * @author Chris Povirk */ @GwtCompatible final class GwtSerializationDependencies { private GwtSerializationDependencies() {} static final class OptionalDependencies<T> extends Optional<T> { T value; OptionalDependencies() { super(); } @Override public boolean isPresent() { throw new AssertionError(); } @Override public T get() { throw new AssertionError(); } @Override public T or(T defaultValue) { throw new AssertionError(); } @Override public Optional<T> or(Optional<? extends T> secondChoice) { throw new AssertionError(); } @Override public T or(Supplier<? extends T> supplier) { throw new AssertionError(); } @Override public T orNull() { throw new AssertionError(); } @Override public Set<T> asSet() { throw new AssertionError(); } @Override public <V> Optional<V> transform( Function<? super T, V> function) { throw new AssertionError(); } @Override public boolean equals(@Nullable Object object) { throw new AssertionError(); } @Override public int hashCode() { throw new AssertionError(); } @Override public String toString() { throw new AssertionError(); } } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/base/GwtSerializationDependencies.java
Java
asf20
2,305
/* * 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.base; import com.google.common.annotations.GwtCompatible; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * Custom GWT serializer for {@link Present}. * * @author Chris Povirk */ @GwtCompatible public class Present_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, Present<?> instance) {} public static Present<Object> instantiate(SerializationStreamReader reader) throws SerializationException { return (Present<Object>) Optional.of(reader.readObject()); } public static void serialize(SerializationStreamWriter writer, Present<?> instance) throws SerializationException { writer.writeObject(instance.get()); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/base/Present_CustomFieldSerializer.java
Java
asf20
1,467
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link SingletonImmutableSet}. * * @author Hayward Chan */ public class SingletonImmutableSet_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, SingletonImmutableSet<?> instance) { } public static SingletonImmutableSet<Object> instantiate( SerializationStreamReader reader) throws SerializationException { Object element = reader.readObject(); return new SingletonImmutableSet<Object>(element); } public static void serialize(SerializationStreamWriter writer, SingletonImmutableSet<?> instance) throws SerializationException { writer.writeObject(instance.element); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/SingletonImmutableSet_CustomFieldSerializer.java
Java
asf20
1,543
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import java.util.Collection; import java.util.Map; /** * This class contains static utility methods for writing {@code Multimap} GWT * field serializers. Serializers should delegate to * {@link #serialize(SerializationStreamWriter, Multimap)} and to either * {@link #instantiate(SerializationStreamReader, ImmutableMultimap.Builder)} or * {@link #populate(SerializationStreamReader, Multimap)}. * * @author Chris Povirk */ public final class Multimap_CustomFieldSerializerBase { static ImmutableMultimap<Object, Object> instantiate( SerializationStreamReader reader, ImmutableMultimap.Builder<Object, Object> builder) throws SerializationException { int keyCount = reader.readInt(); for (int i = 0; i < keyCount; ++i) { Object key = reader.readObject(); int valueCount = reader.readInt(); for (int j = 0; j < valueCount; ++j) { Object value = reader.readObject(); builder.put(key, value); } } return builder.build(); } public static Multimap<Object, Object> populate( SerializationStreamReader reader, Multimap<Object, Object> multimap) throws SerializationException { int keyCount = reader.readInt(); for (int i = 0; i < keyCount; ++i) { Object key = reader.readObject(); int valueCount = reader.readInt(); for (int j = 0; j < valueCount; ++j) { Object value = reader.readObject(); multimap.put(key, value); } } return multimap; } public static void serialize( SerializationStreamWriter writer, Multimap<?, ?> instance) throws SerializationException { writer.writeInt(instance.asMap().size()); for (Map.Entry<?, ? extends Collection<?>> entry : instance.asMap().entrySet()) { writer.writeObject(entry.getKey()); writer.writeInt(entry.getValue().size()); for (Object value : entry.getValue()) { writer.writeObject(value); } } } private Multimap_CustomFieldSerializerBase() {} }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/Multimap_CustomFieldSerializerBase.java
Java
asf20
2,842
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of * {@link ImmutableEntry}. * * @author Kyle Butt */ public class ImmutableEntry_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ImmutableEntry<?, ?> instance) { } public static ImmutableEntry<Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { Object key = reader.readObject(); Object value = reader.readObject(); return new ImmutableEntry<Object, Object>(key, value); } public static void serialize(SerializationStreamWriter writer, ImmutableEntry<?, ?> instance) throws SerializationException { writer.writeObject(instance.getKey()); writer.writeObject(instance.getValue()); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/ImmutableEntry_CustomFieldSerializer.java
Java
asf20
1,606
/* * 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; /** * Even though {@link ImmutableList} cannot be instantiated, we still need * a custom field serializer to unify the type signature of * {@code ImmutableList[]} on server and client side. * * @author Hayward Chan */ public final class ImmutableList_CustomFieldSerializer {}
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/ImmutableList_CustomFieldSerializer.java
Java
asf20
920
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link HashBasedTable}. * * @author Hayward Chan */ public class HashBasedTable_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, HashBasedTable<?, ?, ?> table) { } public static HashBasedTable<Object, Object, Object> instantiate(SerializationStreamReader reader) throws SerializationException { return Table_CustomFieldSerializerBase.populate(reader, HashBasedTable.create()); } public static void serialize(SerializationStreamWriter writer, HashBasedTable<?, ?, ?> table) throws SerializationException { Table_CustomFieldSerializerBase.serialize(writer, table); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/HashBasedTable_CustomFieldSerializer.java
Java
asf20
1,523
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link LinkedHashMultiset}. * * @author Chris Povirk */ public class LinkedHashMultiset_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, LinkedHashMultiset<?> instance) { } public static LinkedHashMultiset<Object> instantiate( SerializationStreamReader reader) throws SerializationException { return (LinkedHashMultiset<Object>) Multiset_CustomFieldSerializerBase.populate( reader, LinkedHashMultiset.create()); } public static void serialize(SerializationStreamWriter writer, LinkedHashMultiset<?> instance) throws SerializationException { Multiset_CustomFieldSerializerBase.serialize(writer, instance); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/LinkedHashMultiset_CustomFieldSerializer.java
Java
asf20
1,598
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import java.util.Map; /** * This class implements the GWT serialization of {@link LinkedListMultimap}. * * @author Chris Povirk */ public class LinkedListMultimap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader in, LinkedListMultimap<?, ?> out) { } public static LinkedListMultimap<Object, Object> instantiate( SerializationStreamReader in) throws SerializationException { LinkedListMultimap<Object, Object> multimap = LinkedListMultimap.create(); int size = in.readInt(); for (int i = 0; i < size; i++) { Object key = in.readObject(); Object value = in.readObject(); multimap.put(key, value); } return multimap; } public static void serialize(SerializationStreamWriter out, LinkedListMultimap<?, ?> multimap) throws SerializationException { out.writeInt(multimap.size()); for (Map.Entry<?, ?> entry : multimap.entries()) { out.writeObject(entry.getKey()); out.writeObject(entry.getValue()); } } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/LinkedListMultimap_CustomFieldSerializer.java
Java
asf20
1,863
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import java.util.Map; import java.util.Map.Entry; /** * This class contains static utility methods for writing {@link Table} GWT field serializers. * Serializers should delegate to {@link #serialize} and {@link #populate}. * * <p>For {@link ImmutableTable}, see {@link ImmutableTable_CustomFieldSerializerBase}. * * @author Chris Povirk */ final class Table_CustomFieldSerializerBase { static <T extends StandardTable<Object, Object, Object>> T populate( SerializationStreamReader reader, T table) throws SerializationException { Map<?, ?> hashMap = (Map<?, ?>) reader.readObject(); for (Entry<?, ?> row : hashMap.entrySet()) { table.row(row.getKey()).putAll((Map<?, ?>) row.getValue()); } return table; } static void serialize(SerializationStreamWriter writer, StandardTable<?, ?, ?> table) throws SerializationException { /* * The backing map of a {Hash,Tree}BasedTable is a {Hash,Tree}Map of {Hash,Tree}Maps. Therefore, * the backing map is serializable (assuming that the row, column and values, along with any * comparators, are all serializable). */ writer.writeObject(table.backingMap); } private Table_CustomFieldSerializerBase() {} }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/Table_CustomFieldSerializerBase.java
Java
asf20
2,050
/* * 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.lang.reflect.Array; // TODO(kevinb): guava javadoc path seems set wrong, doesn't find that last // import /** * Version of {@link GwtPlatform} used in hosted-mode. It includes methods in * {@link Platform} that requires different implementions in web mode and * hosted mode. It is factored out from {@link Platform} because {@code * GwtScriptOnly} (which is applied to the emul version) supports only public * classes and methods. * * @author Hayward Chan */ // TODO(hhchan): Once we start using server-side source in hosted mode, we won't // need this. @GwtCompatible(emulated = true) public final class GwtPlatform { private GwtPlatform() {} /** See {@link Platform#newArray(Object[], int)} */ public static <T> T[] newArray(T[] reference, int length) { Class<?> type = reference.getClass().getComponentType(); // the cast is safe because // result.getClass() == reference.getClass().getComponentType() @SuppressWarnings("unchecked") T[] result = (T[]) Array.newInstance(type, length); return result; } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/GwtPlatform.java
Java
asf20
1,756
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import com.google.gwt.user.client.rpc.core.java.util.Map_CustomFieldSerializerBase; /** * This class contains static utility methods for writing {@link ImmutableTable} GWT field * serializers. Serializers should delegate to {@link #serialize} and {@link #instantiate}. * * @author Chris Povirk */ final class ImmutableTable_CustomFieldSerializerBase { public static ImmutableTable<Object, Object, Object> instantiate(SerializationStreamReader reader) throws SerializationException { ImmutableTable.Builder<Object, Object, Object> builder = ImmutableTable.builder(); int rowCount = reader.readInt(); for (int i = 0; i < rowCount; i++) { Object rowKey = reader.readObject(); int colCount = reader.readInt(); for (int j = 0; j < colCount; j++) { builder.put(rowKey, reader.readObject(), reader.readObject()); } } return builder.build(); } public static void serialize( SerializationStreamWriter writer, ImmutableTable<Object, Object, Object> table) throws SerializationException { writer.writeInt(table.rowKeySet().size()); for (Object rowKey : table.rowKeySet()) { writer.writeObject(rowKey); Map_CustomFieldSerializerBase.serialize(writer, table.row(rowKey)); } } private ImmutableTable_CustomFieldSerializerBase() {} }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/ImmutableTable_CustomFieldSerializerBase.java
Java
asf20
2,155
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; /** * This class implements the GWT serialization of {@link LinkedHashMultimap}. * * @author Chris Povirk */ public class LinkedHashMultimap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader in, LinkedHashMultimap<?, ?> out) { } public static LinkedHashMultimap<Object, Object> instantiate( SerializationStreamReader stream) throws SerializationException { LinkedHashMultimap<Object, Object> multimap = LinkedHashMultimap.create(); multimap.valueSetCapacity = stream.readInt(); int distinctKeys = stream.readInt(); Map<Object, Collection<Object>> map = new LinkedHashMap<Object, Collection<Object>>(Maps.capacity(distinctKeys)); for (int i = 0; i < distinctKeys; i++) { Object key = stream.readObject(); map.put(key, multimap.createCollection(key)); } int entries = stream.readInt(); for (int i = 0; i < entries; i++) { Object key = stream.readObject(); Object value = stream.readObject(); map.get(key).add(value); } multimap.setMap(map); return multimap; } public static void serialize(SerializationStreamWriter stream, LinkedHashMultimap<?, ?> multimap) throws SerializationException { stream.writeInt(multimap.valueSetCapacity); stream.writeInt(multimap.keySet().size()); for (Object key : multimap.keySet()) { stream.writeObject(key); } stream.writeInt(multimap.size()); for (Map.Entry<?, ?> entry : multimap.entries()) { stream.writeObject(entry.getKey()); stream.writeObject(entry.getValue()); } } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/LinkedHashMultimap_CustomFieldSerializer.java
Java
asf20
2,519
/* * 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; /** * Even though {@link ImmutableBiMap} cannot be instantiated, we still need * a custom field serializer to unify the type signature of * {@code ImmutableBiMap[]} on server and client side. * * @author Hayward Chan */ public final class ImmutableBiMap_CustomFieldSerializer {}
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/ImmutableBiMap_CustomFieldSerializer.java
Java
asf20
923
/* * 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.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of * {@link EmptyImmutableSetMultimap}. * * @author Chris Povirk */ public class EmptyImmutableSetMultimap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, EmptyImmutableSetMultimap instance) { } public static EmptyImmutableSetMultimap instantiate( SerializationStreamReader reader) { return EmptyImmutableSetMultimap.INSTANCE; } public static void serialize(SerializationStreamWriter writer, EmptyImmutableSetMultimap instance) { } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/EmptyImmutableSetMultimap_CustomFieldSerializer.java
Java
asf20
1,337
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link ReverseOrdering}. * * @author Chris Povirk */ public class ReverseOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ReverseOrdering<?> instance) { } @SuppressWarnings("unchecked") // deserialization is unsafe public static ReverseOrdering<Object> instantiate( SerializationStreamReader reader) throws SerializationException { return new ReverseOrdering<Object>( (Ordering<Object>) reader.readObject()); } public static void serialize(SerializationStreamWriter writer, ReverseOrdering<?> instance) throws SerializationException { writer.writeObject(instance.forwardOrder); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/ReverseOrdering_CustomFieldSerializer.java
Java
asf20
1,571
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link HashMultimap}. * * @author Jord Sonneveld * */ public class HashMultimap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader in, HashMultimap<?, ?> out) { } public static HashMultimap<Object, Object> instantiate( SerializationStreamReader in) throws SerializationException { return (HashMultimap<Object, Object>) Multimap_CustomFieldSerializerBase.populate(in, HashMultimap.create()); } public static void serialize(SerializationStreamWriter out, HashMultimap<?, ?> multimap) throws SerializationException { Multimap_CustomFieldSerializerBase.serialize(out, multimap); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/HashMultimap_CustomFieldSerializer.java
Java
asf20
1,549
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link * LexicographicalOrdering}. * * @author Chris Povirk */ public class LexicographicalOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, LexicographicalOrdering<?> instance) { } @SuppressWarnings("unchecked") // deserialization is unsafe public static LexicographicalOrdering<Object> instantiate( SerializationStreamReader reader) throws SerializationException { return new LexicographicalOrdering<Object>( (Ordering<Object>) reader.readObject()); } public static void serialize(SerializationStreamWriter writer, LexicographicalOrdering<?> instance) throws SerializationException { writer.writeObject(instance.elementOrder); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/LexicographicalOrdering_CustomFieldSerializer.java
Java
asf20
1,622
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link NullsLastOrdering}. * * @author Chris Povirk */ public class NullsLastOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, NullsLastOrdering<?> instance) { } @SuppressWarnings("unchecked") // deserialization is unsafe public static NullsLastOrdering<Object> instantiate( SerializationStreamReader reader) throws SerializationException { return new NullsLastOrdering<Object>( (Ordering<Object>) reader.readObject()); } public static void serialize(SerializationStreamWriter writer, NullsLastOrdering<?> instance) throws SerializationException { writer.writeObject(instance.ordering); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/NullsLastOrdering_CustomFieldSerializer.java
Java
asf20
1,579
/* * 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.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link UsingToStringOrdering}. * * @author Chris Povirk */ public class UsingToStringOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, UsingToStringOrdering instance) { } public static UsingToStringOrdering instantiate( SerializationStreamReader reader) { return UsingToStringOrdering.INSTANCE; } public static void serialize(SerializationStreamWriter writer, UsingToStringOrdering instance) { } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/UsingToStringOrdering_CustomFieldSerializer.java
Java
asf20
1,310
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link SparseImmutableTable}. * * @author Chris Povirk */ public class SparseImmutableTable_CustomFieldSerializer { public static void deserialize( SerializationStreamReader reader, SparseImmutableTable<?, ?, ?> instance) { } public static SparseImmutableTable<Object, Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { return (SparseImmutableTable<Object, Object, Object>) ImmutableTable_CustomFieldSerializerBase.instantiate(reader); } public static void serialize( SerializationStreamWriter writer, SparseImmutableTable<Object, Object, Object> table) throws SerializationException { ImmutableTable_CustomFieldSerializerBase.serialize(writer, table); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/SparseImmutableTable_CustomFieldSerializer.java
Java
asf20
1,637
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link DenseImmutableTable}. * * @author Chris Povirk */ public class DenseImmutableTable_CustomFieldSerializer { public static void deserialize( SerializationStreamReader reader, DenseImmutableTable<?, ?, ?> instance) { } public static DenseImmutableTable<Object, Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { return (DenseImmutableTable<Object, Object, Object>) ImmutableTable_CustomFieldSerializerBase.instantiate(reader); } public static void serialize( SerializationStreamWriter writer, DenseImmutableTable<Object, Object, Object> table) throws SerializationException { ImmutableTable_CustomFieldSerializerBase.serialize(writer, table); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/DenseImmutableTable_CustomFieldSerializer.java
Java
asf20
1,631
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import com.google.gwt.user.client.rpc.core.java.util.Map_CustomFieldSerializerBase; import java.util.Map; /** * This class implements the GWT serialization of {@link ImmutableEnumMap}. * * @author Louis Wasserman */ public class ImmutableEnumMap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ImmutableEnumMap<?, ?> instance) { } public static <K extends Enum<K>, V> ImmutableEnumMap<?, ?> instantiate( SerializationStreamReader reader) throws SerializationException { Map<K, V> deserialized = Maps.newHashMap(); Map_CustomFieldSerializerBase.deserialize(reader, deserialized); /* * It is safe to cast to ImmutableEnumSet because in order for it to be * serialized as an ImmutableEnumSet, it must be non-empty to start * with. */ return (ImmutableEnumMap<?, ?>) Maps.immutableEnumMap(deserialized); } public static void serialize(SerializationStreamWriter writer, ImmutableEnumMap<?, ?> instance) throws SerializationException { Map_CustomFieldSerializerBase.serialize(writer, instance); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/ImmutableEnumMap_CustomFieldSerializer.java
Java
asf20
1,944
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import com.google.gwt.user.client.rpc.core.java.util.Map_CustomFieldSerializerBase; import java.util.LinkedHashMap; import java.util.Map; /** * This class implements the GWT serialization of {@link RegularImmutableMap}. * * @author Hayward Chan */ public class RegularImmutableMap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, RegularImmutableMap<?, ?> instance) { } public static RegularImmutableMap<Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { Map<Object, Object> entries = new LinkedHashMap<Object, Object>(); Map_CustomFieldSerializerBase.deserialize(reader, entries); /* * For this custom field serializer to be invoked, the map must have been * RegularImmutableMap before it's serialized. Since RegularImmutableMap * always have two or more elements, ImmutableMap.copyOf always return * a RegularImmutableMap back. */ return (RegularImmutableMap<Object, Object>) ImmutableMap.copyOf(entries); } public static void serialize(SerializationStreamWriter writer, RegularImmutableMap<?, ?> instance) throws SerializationException { Map_CustomFieldSerializerBase.serialize(writer, instance); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/RegularImmutableMap_CustomFieldSerializer.java
Java
asf20
2,103
/* * 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; /** * Even though {@link ImmutableMultiset} cannot be instantiated, we still need * a custom field serializer to unify the type signature of * {@code ImmutableMultiset[]} on server and client side. * * @author Chris Povirk */ public class ImmutableMultiset_CustomFieldSerializer {}
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/ImmutableMultiset_CustomFieldSerializer.java
Java
asf20
926
/* * 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; /** * Even though {@link ImmutableSortedSet} cannot be instantiated, we still need * a custom field serializer to unify the type signature of * {@code ImmutableSortedSet[]} on server and client side. * * @author Hayward Chan */ public final class ImmutableSortedSet_CustomFieldSerializer {}
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/ImmutableSortedSet_CustomFieldSerializer.java
Java
asf20
935
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link RegularImmutableSortedMap}. * * @author Chris Povirk */ public class RegularImmutableSortedMap_CustomFieldSerializer { public static void deserialize( SerializationStreamReader reader, RegularImmutableSortedMap<?, ?> instance) { } public static RegularImmutableSortedMap<?, ?> instantiate( SerializationStreamReader reader) throws SerializationException { return (RegularImmutableSortedMap<?, ?>) ImmutableSortedMap_CustomFieldSerializerBase.instantiate(reader); } public static void serialize( SerializationStreamWriter writer, RegularImmutableSortedMap<?, ?> instance) throws SerializationException { ImmutableSortedMap_CustomFieldSerializerBase.serialize(writer, instance); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/RegularImmutableSortedMap_CustomFieldSerializer.java
Java
asf20
1,630
/* * 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.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of * {@link EmptyImmutableBiMap}. * * @author Chris Povirk */ public class EmptyImmutableBiMap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, EmptyImmutableBiMap instance) { } public static EmptyImmutableBiMap instantiate(SerializationStreamReader reader) { return EmptyImmutableBiMap.INSTANCE; } public static void serialize(SerializationStreamWriter writer, EmptyImmutableBiMap instance) { } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/EmptyImmutableBiMap_CustomFieldSerializer.java
Java
asf20
1,280
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.Comparator; import java.util.HashMap; import java.util.TreeMap; /** * Contains dummy collection implementations to convince GWT that part of * serializing a collection is serializing its elements. * * <p>Because of our use of final fields in our collections, GWT's normal * heuristic for determining which classes might be serialized fails. That * heuristic is, roughly speaking, to look at each parameter and return type of * each RPC interface and to assume that implementations of those types might be * serialized. Those types have their own dependencies -- their fields -- which * are analyzed recursively and analogously. * * <p>For classes with final fields, GWT assumes that the class itself might be * serialized but doesn't assume the same about its final fields. To work around * this, we provide dummy implementations of our collections with their * dependencies as non-final fields. Even though these implementations are never * instantiated, they are visible to GWT when it performs its serialization * analysis, and it assumes that their fields may be serialized. * * <p>Currently we provide dummy implementations of all the immutable * collection classes necessary to support declarations like * {@code ImmutableMultiset<String>} in RPC interfaces. Support for * {@code ImmutableMultiset} in the interface is support for {@code Multiset}, * so there is nothing further to be done to support the new collection * interfaces. It is not support, however, for an RPC interface in terms of * {@code HashMultiset}. It is still possible to send a {@code HashMultiset} * over GWT RPC; it is only the declaration of an interface in terms of * {@code HashMultiset} that we haven't tried to support. (We may wish to * revisit this decision in the future.) * * @author Chris Povirk */ @GwtCompatible // None of these classes are instantiated, let alone serialized: @SuppressWarnings("serial") final class GwtSerializationDependencies { private GwtSerializationDependencies() {} static final class ImmutableListMultimapDependencies<K, V> extends ImmutableListMultimap<K, V> { K key; V value; ImmutableListMultimapDependencies() { super(null, 0); } } // ImmutableMap is covered by ImmutableSortedMap/ImmutableBiMap. // ImmutableMultimap is covered by ImmutableSetMultimap/ImmutableListMultimap. static final class ImmutableSetMultimapDependencies<K, V> extends ImmutableSetMultimap<K, V> { K key; V value; ImmutableSetMultimapDependencies() { super(null, 0, null); } } /* * We support an interface declared in terms of LinkedListMultimap because it * supports entry ordering not supported by other implementations. */ static final class LinkedListMultimapDependencies<K, V> extends LinkedListMultimap<K, V> { K key; V value; LinkedListMultimapDependencies() {} } static final class HashBasedTableDependencies<R, C, V> extends HashBasedTable<R, C, V> { HashMap<R, HashMap<C, V>> data; HashBasedTableDependencies() { super(null, null); } } static final class TreeBasedTableDependencies<R, C, V> extends TreeBasedTable<R, C, V> { TreeMap<R, TreeMap<C, V>> data; TreeBasedTableDependencies() { super(null, null); } } /* * We don't normally need "implements Serializable," but we do here. That's * because ImmutableTable itself is not Serializable as of this writing. We * need for GWT to believe that this dummy class is serializable, or else it * won't generate serialization code for R, C, and V. */ static final class ImmutableTableDependencies<R, C, V> extends SingletonImmutableTable<R, C, V> implements Serializable { R rowKey; C columnKey; V value; ImmutableTableDependencies() { super(null, null, null); } } static final class TreeMultimapDependencies<K, V> extends TreeMultimap<K, V> { Comparator<? super K> keyComparator; Comparator<? super V> valueComparator; K key; V value; TreeMultimapDependencies() { super(null, null); } } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/GwtSerializationDependencies.java
Java
asf20
4,880
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link EmptyImmutableSortedMap}. * * @author Chris Povirk */ public class EmptyImmutableSortedMap_CustomFieldSerializer { public static void deserialize( SerializationStreamReader reader, EmptyImmutableSortedMap<?, ?> instance) { } public static EmptyImmutableSortedMap<?, ?> instantiate( SerializationStreamReader reader) throws SerializationException { return (EmptyImmutableSortedMap<?, ?>) ImmutableSortedMap_CustomFieldSerializerBase.instantiate(reader); } public static void serialize( SerializationStreamWriter writer, EmptyImmutableSortedMap<?, ?> instance) throws SerializationException { ImmutableSortedMap_CustomFieldSerializerBase.serialize(writer, instance); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/EmptyImmutableSortedMap_CustomFieldSerializer.java
Java
asf20
1,618
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import java.util.Comparator; /** * This class implements the GWT serialization of {@link TreeBasedTable}. * * @author Hayward Chan */ public class TreeBasedTable_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, TreeBasedTable<?, ?, ?> table) { } public static TreeBasedTable<Object, Object, Object> instantiate(SerializationStreamReader reader) throws SerializationException { @SuppressWarnings("unchecked") // The comparator isn't used statically. Comparator<Object> rowComparator = (Comparator<Object>) reader.readObject(); @SuppressWarnings("unchecked") // The comparator isn't used statically. Comparator<Object> columnComparator = (Comparator<Object>) reader.readObject(); TreeBasedTable<Object, Object, Object> table = TreeBasedTable.create(rowComparator, columnComparator); return Table_CustomFieldSerializerBase.populate(reader, table); } public static void serialize(SerializationStreamWriter writer, TreeBasedTable<?, ?, ?> table) throws SerializationException { writer.writeObject(table.rowComparator()); writer.writeObject(table.columnComparator()); Table_CustomFieldSerializerBase.serialize(writer, table); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/TreeBasedTable_CustomFieldSerializer.java
Java
asf20
2,081
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class contains static utility methods for writing {@code Multiset} GWT * field serializers. Serializers should delegate to * {@link #serialize(SerializationStreamWriter, Multiset)} and * {@link #populate(SerializationStreamReader, Multiset)}. * * @author Chris Povirk */ final class Multiset_CustomFieldSerializerBase { static Multiset<Object> populate( SerializationStreamReader reader, Multiset<Object> multiset) throws SerializationException { int distinctElements = reader.readInt(); for (int i = 0; i < distinctElements; i++) { Object element = reader.readObject(); int count = reader.readInt(); multiset.add(element, count); } return multiset; } static void serialize(SerializationStreamWriter writer, Multiset<?> instance) throws SerializationException { int entryCount = instance.entrySet().size(); writer.writeInt(entryCount); for (Multiset.Entry<?> entry : instance.entrySet()) { writer.writeObject(entry.getElement()); writer.writeInt(entry.getCount()); } } private Multiset_CustomFieldSerializerBase() {} }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/Multiset_CustomFieldSerializerBase.java
Java
asf20
1,963
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import java.util.Comparator; /** * This class implements the GWT serialization of {@link ComparatorOrdering}. * * @author Chris Povirk */ public class ComparatorOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ComparatorOrdering<?> instance) { } @SuppressWarnings("unchecked") // deserialization is unsafe public static ComparatorOrdering<Object> instantiate( SerializationStreamReader reader) throws SerializationException { return new ComparatorOrdering<Object>( (Comparator<Object>) reader.readObject()); } public static void serialize(SerializationStreamWriter writer, ComparatorOrdering<?> instance) throws SerializationException { writer.writeObject(instance.comparator); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/ComparatorOrdering_CustomFieldSerializer.java
Java
asf20
1,619
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import com.google.gwt.user.client.rpc.core.java.util.Collection_CustomFieldSerializerBase; import java.util.ArrayList; import java.util.Comparator; import java.util.List; /** * This class implements the GWT serialization of * {@link RegularImmutableSortedSet}. * * @author Chris Povirk */ public class RegularImmutableSortedSet_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, RegularImmutableSortedSet<?> instance) { } public static RegularImmutableSortedSet<Object> instantiate( SerializationStreamReader reader) throws SerializationException { /* * Nothing we can do, but we're already assuming the serialized form is * correctly typed, anyway. */ @SuppressWarnings("unchecked") Comparator<Object> comparator = (Comparator<Object>) reader.readObject(); List<Object> elements = new ArrayList<Object>(); Collection_CustomFieldSerializerBase.deserialize(reader, elements); /* * For this custom field serializer to be invoked, the set must have been * RegularImmutableSortedSet before it's serialized. Since * RegularImmutableSortedSet always have one or more elements, * ImmutableSortedSet.copyOf always return a RegularImmutableSortedSet back. */ return (RegularImmutableSortedSet<Object>) ImmutableSortedSet.copyOf(comparator, elements); } public static void serialize(SerializationStreamWriter writer, RegularImmutableSortedSet<?> instance) throws SerializationException { writer.writeObject(instance.comparator()); Collection_CustomFieldSerializerBase.serialize(writer, instance); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/RegularImmutableSortedSet_CustomFieldSerializer.java
Java
asf20
2,485
/* * 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.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link EmptyImmutableSet}. * * @author Chris Povirk */ public class EmptyImmutableSet_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, EmptyImmutableSet instance) { } public static EmptyImmutableSet instantiate( SerializationStreamReader reader) { return EmptyImmutableSet.INSTANCE; } public static void serialize(SerializationStreamWriter writer, EmptyImmutableSet instance) { } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/EmptyImmutableSet_CustomFieldSerializer.java
Java
asf20
1,286
/* * 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.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link ArrayListMultimap}. * * @author Chris Povirk */ public class ArrayListMultimap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader in, ArrayListMultimap<?, ?> out) { } public static ArrayListMultimap<Object, Object> instantiate( SerializationStreamReader in) throws SerializationException { return (ArrayListMultimap<Object, Object>) Multimap_CustomFieldSerializerBase.populate( in, ArrayListMultimap.create()); } public static void serialize(SerializationStreamWriter out, ArrayListMultimap<?, ?> multimap) throws SerializationException { Multimap_CustomFieldSerializerBase.serialize(out, multimap); } }
zzhhhhh-aw4rwer
guava-gwt/src/com/google/common/collect/ArrayListMultimap_CustomFieldSerializer.java
Java
asf20
1,591