code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import java.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> implements Multimap<K, V>, 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 AbstractMultimap<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> * * Builder instances can be reused; it is safe to call {@link #build} multiple * times to build multiple multimaps in series. Each multimap contains the * key-value mappings in the previously created multimaps. * * @since 2.0 (imported from Google Collections Library) */ public static class Builder<K, V> { Multimap<K, V> builderMultimap = new BuilderMultimap<K, V>(); Comparator<? super K> keyComparator; Comparator<? super V> valueComparator; /** * Creates a new builder. The returned builder is equivalent to the builder * generated by {@link ImmutableMultimap#builder}. */ public Builder() {} /** * Adds a key-value mapping to the built multimap. */ public Builder<K, V> put(K key, V value) { builderMultimap.put(checkNotNull(key), checkNotNull(value)); return this; } /** * Adds an entry to the built multimap. * * @since 11.0 */ public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { builderMultimap.put( checkNotNull(entry.getKey()), checkNotNull(entry.getValue())); return this; } /** * Stores a collection of values with the same key in the built multimap. * * @throws NullPointerException if {@code key}, {@code values}, or any * element in {@code values} is null. The builder is left in an invalid * state. */ public Builder<K, V> putAll(K key, Iterable<? extends V> values) { Collection<V> valueList = builderMultimap.get(checkNotNull(key)); for (V value : values) { valueList.add(checkNotNull(value)); } return this; } /** * Stores an array of values with the same key in the built multimap. * * @throws NullPointerException if the key or any value is null. The builder * is left in an invalid state. */ public Builder<K, V> putAll(K key, V... values) { return putAll(key, Arrays.asList(values)); } /** * Stores another multimap's entries in the built multimap. The generated * multimap's key and value orderings correspond to the iteration ordering * of the {@code multimap.asMap()} view, with new keys and values following * any existing keys and values. * * @throws NullPointerException if any key or value in {@code multimap} is * null. The builder is left in an invalid state. */ public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) { for (Entry<? extends K, ? extends Collection<? extends V>> entry : multimap.asMap().entrySet()) { putAll(entry.getKey(), entry.getValue()); } return this; } /** * Specifies the ordering of the generated multimap's keys. * * @since 8.0 */ @Beta 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 */ @Beta 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).onResultOf(new Function<Entry<K, Collection<V>>, K>() { @Override public K apply(Entry<K, Collection<V>> entry) { return entry.getKey(); } })); 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 */ @Beta 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(); } boolean isPartialView() { return map.isPartialView(); } // accessors @Override public boolean containsEntry(@Nullable Object key, @Nullable Object value) { Collection<V> values = map.get(key); return values != null && values.contains(value); } @Override public boolean containsKey(@Nullable Object key) { return map.containsKey(key); } @Override public boolean containsValue(@Nullable Object value) { for (Collection<V> valueCollection : map.values()) { if (valueCollection.contains(value)) { return true; } } return false; } @Override public boolean isEmpty() { return size == 0; } @Override public int size() { return size; } @Override public boolean equals(@Nullable Object object) { if (object instanceof Multimap) { Multimap<?, ?> that = (Multimap<?, ?>) object; return this.map.equals(that.asMap()); } return false; } @Override public int hashCode() { return map.hashCode(); } @Override public String toString() { return map.toString(); } // 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; } private transient ImmutableCollection<Entry<K, V>> entries; /** * Returns an immutable collection of all key-value pairs in the multimap. Its * iterator traverses the values for the first key, the values for the second * key, and so on. */ @Override public ImmutableCollection<Entry<K, V>> entries() { ImmutableCollection<Entry<K, V>> result = entries; return (result == null) ? (entries = new EntryCollection<K, V>(this)) : result; } 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() { final Iterator<? extends Entry<K, ? extends ImmutableCollection<V>>> mapIterator = this.multimap.map.entrySet().iterator(); return new UnmodifiableIterator<Entry<K, V>>() { K key; Iterator<V> valueIterator; @Override public boolean hasNext() { return (key != null && valueIterator.hasNext()) || mapIterator.hasNext(); } @Override public Entry<K, V> next() { if (key == null || !valueIterator.hasNext()) { Entry<K, ? extends ImmutableCollection<V>> entry = mapIterator.next(); key = entry.getKey(); valueIterator = entry.getValue().iterator(); } return Maps.immutableEntry(key, valueIterator.next()); } }; } @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 transient ImmutableMultiset<K> keys; /** * 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() { ImmutableMultiset<K> result = keys; return (result == null) ? (keys = createKeys()) : result; } private 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 ImmutableSet<Entry<K>> createEntrySet() { return new KeysEntrySet(); } private class KeysEntrySet extends ImmutableMultiset<K>.EntrySet { @Override public int size() { return keySet().size(); } @Override public UnmodifiableIterator<Entry<K>> iterator() { return asList().iterator(); } @Override ImmutableList<Entry<K>> createAsList() { final ImmutableList<? extends Map.Entry<K, ? extends Collection<V>>> mapEntries = map.entrySet().asList(); return new ImmutableAsList<Entry<K>>() { @Override public Entry<K> get(int index) { Map.Entry<K, ? extends Collection<V>> entry = mapEntries.get(index); return Multisets.immutableEntry(entry.getKey(), entry.getValue().size()); } @Override ImmutableCollection<Entry<K>> delegateCollection() { return KeysEntrySet.this; } }; } } @Override boolean isPartialView() { return true; } } private transient ImmutableCollection<V> values; /** * 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() { ImmutableCollection<V> result = values; return (result == null) ? (values = new Values<V>(this)) : result; } private static class Values<V> extends ImmutableCollection<V> { final ImmutableMultimap<?, V> multimap; Values(ImmutableMultimap<?, V> multimap) { this.multimap = multimap; } @Override public UnmodifiableIterator<V> iterator() { return Maps.valueIterator(multimap.entries().iterator()); } @Override public int size() { return multimap.size(); } @Override boolean isPartialView() { return true; } private static final long serialVersionUID = 0; } private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import java.io.Serializable; 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> implements Collection<E>, Serializable { static final ImmutableCollection<Object> EMPTY_IMMUTABLE_COLLECTION = new ForwardingImmutableCollection<Object>(Collections.emptyList()); ImmutableCollection() {} public abstract UnmodifiableIterator<E> iterator(); public Object[] toArray() { Object[] newArray = new Object[size()]; return toArray(newArray); } public <T> T[] toArray(T[] other) { int size = size(); if (other.length < size) { other = ObjectArrays.newArray(other, size); } else if (other.length > size) { other[size] = null; } // Writes will produce ArrayStoreException when the toArray() doc requires. Object[] otherAsObjectArray = other; int index = 0; for (E element : this) { otherAsObjectArray[index++] = element; } return other; } public boolean contains(@Nullable Object object) { if (object == null) { return false; } for (E element : this) { if (element.equals(object)) { return true; } } return false; } public boolean containsAll(Collection<?> targets) { for (Object target : targets) { if (!contains(target)) { return false; } } return true; } public boolean isEmpty() { return size() == 0; } @Override public String toString() { return Collections2.toStringImpl(this); } 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(); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.annotations.GwtCompatible; import java.util.EnumMap; import java.util.Iterator; /** * Multiset implementation backed by an {@link EnumMap}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset"> * {@code Multiset}</a>. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class EnumMultiset<E extends Enum<E>> extends AbstractMapBasedMultiset<E> { /** Creates an empty {@code EnumMultiset}. */ public static <E extends Enum<E>> EnumMultiset<E> create(Class<E> type) { return new EnumMultiset<E>(type); } /** * Creates a new {@code EnumMultiset} containing the specified elements. * * <p>This implementation is highly efficient when {@code elements} is itself a {@link * Multiset}. * * @param elements the elements that the multiset should contain * @throws IllegalArgumentException if {@code elements} is empty */ public static <E extends Enum<E>> EnumMultiset<E> create(Iterable<E> elements) { Iterator<E> iterator = elements.iterator(); checkArgument(iterator.hasNext(), "EnumMultiset constructor passed empty Iterable"); EnumMultiset<E> multiset = new EnumMultiset<E>(iterator.next().getDeclaringClass()); Iterables.addAll(multiset, elements); return multiset; } private transient Class<E> type; /** Creates an empty {@code EnumMultiset}. */ private EnumMultiset(Class<E> type) { super(WellBehavedMap.wrap(new EnumMap<E, Count>(type))); this.type = type; } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import 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(); } }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import java.util.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); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.base.Function; import com.google.common.collect.Maps.EntryTransformer; import java.util.SortedMap; import java.util.SortedSet; /** * 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 */ class Platform { static <T> T[] clone(T[] array) { return GwtPlatform.clone(array); } static <T> T[] newArray(T[] reference, int length) { return GwtPlatform.newArray(reference, length); } 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); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.GwtCompatible; import com.google.common.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(Object value) { return inverse.containsKey(value); } // Modification Operations @Override public V put(K key, V value) { return putInBothMaps(key, value, false); } @Override public V forcePut(K key, V value) { return putInBothMaps(key, value, true); } private V putInBothMaps(@Nullable K key, @Nullable V value, boolean force) { checkKey(key); checkValue(value); boolean containedKey = containsKey(key); if (containedKey && Objects.equal(value, get(key))) { return value; } if (force) { inverse().remove(value); } else { checkArgument(!containsValue(value), "value already present: %s", value); } V oldValue = delegate.put(key, value); updateInverseMap(key, containedKey, oldValue, value); return oldValue; } private void updateInverseMap( K key, boolean containedKey, V oldValue, V newValue) { if (containedKey) { removeFromInverseMap(oldValue); } inverse.delegate.put(newValue, key); } @Override public V remove(Object key) { return containsKey(key) ? removeFromBothMaps(key) : null; } private V removeFromBothMaps(Object key) { V oldValue = delegate.remove(key); removeFromInverseMap(oldValue); return oldValue; } private void removeFromInverseMap(V oldValue) { inverse.delegate.remove(oldValue); } // Bulk Operations @Override public void putAll(Map<? extends K, ? extends V> map) { for (Entry<? extends K, ? extends V> entry : map.entrySet()) { put(entry.getKey(), entry.getValue()); } } @Override public void clear() { delegate.clear(); inverse.delegate.clear(); } // Views @Override public BiMap<V, K> inverse() { return inverse; } private transient Set<K> keySet; @Override public Set<K> keySet() { Set<K> result = keySet; return (result == null) ? keySet = new KeySet() : result; } private class KeySet extends ForwardingSet<K> { @Override protected Set<K> delegate() { return delegate.keySet(); } @Override public void clear() { AbstractBiMap.this.clear(); } @Override public boolean remove(Object key) { if (!contains(key)) { return false; } removeFromBothMaps(key); return true; } @Override public boolean removeAll(Collection<?> keysToRemove) { return standardRemoveAll(keysToRemove); } @Override public boolean retainAll(Collection<?> keysToRetain) { return standardRetainAll(keysToRetain); } @Override public Iterator<K> iterator() { return Maps.keyIterator(entrySet().iterator()); } } private transient Set<V> valueSet; @Override public Set<V> values() { /* * We can almost reuse the inverse's keySet, except we have to fix the * iteration order so that it is consistent with the forward map. */ Set<V> result = valueSet; return (result == null) ? valueSet = new ValueSet() : result; } private class ValueSet extends ForwardingSet<V> { final Set<V> valuesDelegate = inverse.keySet(); @Override protected Set<V> delegate() { return valuesDelegate; } @Override public Iterator<V> iterator() { return Maps.valueIterator(entrySet().iterator()); } @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } @Override public String toString() { return standardToString(); } } private transient Set<Entry<K, V>> entrySet; @Override public Set<Entry<K, V>> entrySet() { Set<Entry<K, V>> result = entrySet; return (result == null) ? entrySet = new EntrySet() : result; } private class EntrySet extends ForwardingSet<Entry<K, V>> { final Set<Entry<K, V>> esDelegate = delegate.entrySet(); @Override protected Set<Entry<K, V>> delegate() { return esDelegate; } @Override public void clear() { AbstractBiMap.this.clear(); } @Override public boolean remove(Object object) { if (!esDelegate.contains(object)) { return false; } // safe because esDelgate.contains(object). Entry<?, ?> entry = (Entry<?, ?>) object; inverse.delegate.remove(entry.getValue()); /* * Remove the mapping in inverse before removing from esDelegate because * if entry is part of esDelegate, entry might be invalidated after the * mapping is removed from esDelegate. */ esDelegate.remove(entry); return true; } @Override public Iterator<Entry<K, V>> iterator() { final Iterator<Entry<K, V>> iterator = esDelegate.iterator(); return new Iterator<Entry<K, V>>() { Entry<K, V> entry; @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Entry<K, V> next() { entry = iterator.next(); final Entry<K, V> finalEntry = entry; return new ForwardingMapEntry<K, V>() { @Override protected Entry<K, V> delegate() { return finalEntry; } @Override public V setValue(V value) { // Preconditions keep the map and inverse consistent. checkState(contains(this), "entry no longer in map"); // similar to putInBothMaps, but set via entry if (Objects.equal(value, getValue())) { return value; } checkArgument(!containsValue(value), "value already present: %s", value); V oldValue = finalEntry.setValue(value); checkState(Objects.equal(value, get(getKey())), "entry no longer in map"); updateInverseMap(getKey(), true, oldValue, value); return oldValue; } }; } @Override public void remove() { checkState(entry != null); V value = entry.getValue(); iterator.remove(); removeFromInverseMap(value); } }; } // See java.util.Collections.CheckedEntrySet for details on attacks. @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } @Override public boolean contains(Object o) { return Maps.containsEntryImpl(delegate(), o); } @Override public boolean containsAll(Collection<?> c) { return standardContainsAll(c); } @Override public boolean removeAll(Collection<?> c) { return standardRemoveAll(c); } @Override public boolean retainAll(Collection<?> c) { return standardRetainAll(c); } } /** The inverse of any other {@code AbstractBiMap} subclass. */ private static class Inverse<K, V> extends AbstractBiMap<K, V> { private Inverse(Map<K, V> backward, AbstractBiMap<V, K> forward) { super(backward, forward); } /* * Serialization stores the forward bimap, the inverse of this inverse. * Deserialization calls inverse() on the forward bimap and returns that * inverse. * * If a bimap and its inverse are serialized together, the deserialized * instances have inverse() methods that return the other. */ @Override K checkKey(K key) { return inverse.checkValue(key); } @Override V checkValue(V value) { return inverse.checkKey(value); } } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; /** * 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(); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import 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())); } }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.BoundType.CLOSED; import com.google.common.annotations.GwtCompatible; import 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)) ? range.intersection(other).asSet(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(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; } // copied to make sure not to use the GWT-emulated version @Override public Object[] toArray() { return ObjectArrays.toArrayImpl(this); } // copied to make sure not to use the GWT-emulated version @Override public <T> T[] toArray(T[] other) { return ObjectArrays.toArrayImpl(this, other); } @Override public ContiguousSet<C> intersection(ContiguousSet<C> other) { checkNotNull(other); checkArgument(this.domain.equals(other.domain)); if (other.isEmpty()) { return other; } else { C lowerEndpoint = Ordering.natural().max(this.first(), other.first()); C upperEndpoint = Ordering.natural().min(this.last(), other.last()); return (lowerEndpoint.compareTo(upperEndpoint) < 0) ? Range.closed(lowerEndpoint, upperEndpoint).asSet(domain) : new EmptyContiguousSet<C>(domain); } } @Override public Range<C> range() { return range(CLOSED, CLOSED); } @Override public Range<C> range(BoundType lowerBoundType, BoundType upperBoundType) { return Range.create(range.lowerBound.withLowerBoundType(lowerBoundType, domain), range.upperBound.withUpperBoundType(upperBoundType, domain)); } @Override public boolean equals(Object object) { if (object == this) { return true; } else if (object instanceof RegularContiguousSet) { RegularContiguousSet<?> that = (RegularContiguousSet<?>) object; if (this.domain.equals(that.domain)) { return this.first().equals(that.first()) && this.last().equals(that.last()); } } return super.equals(object); } // copied to make sure not to use the GWT-emulated version @Override public int hashCode() { return Sets.hashCodeImpl(this); } private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import com.google.common.primitives.Ints; 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 row 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. */ private static final class ValueEntry<K, V> extends AbstractMapEntry<K, V> implements ValueSetLink<K, V> { final K key; final V value; final int valueHash; @Nullable ValueEntry<K, V> nextInValueSetHashRow; ValueSetLink<K, V> predecessorInValueSet; ValueSetLink<K, V> successorInValueSet; ValueEntry<K, V> predecessorInMultimap; ValueEntry<K, V> successorInMultimap; ValueEntry(@Nullable K key, @Nullable V value, int valueHash, @Nullable ValueEntry<K, V> nextInValueSetHashRow) { this.key = key; this.value = value; this.valueHash = valueHash; this.nextInValueSetHashRow = nextInValueSetHashRow; } @Override public K getKey() { return key; } @Override public V getValue() { return value; } @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; private static final int MAX_VALUE_SET_TABLE_SIZE = Ints.MAX_POWER_OF_TWO; @VisibleForTesting transient int valueSetCapacity = DEFAULT_VALUE_SET_CAPACITY; private transient ValueEntry<K, V> multimapHeaderEntry; private LinkedHashMultimap(int keyCapacity, int valueSetCapacity) { super(new LinkedHashMap<K, Collection<V>>(keyCapacity)); checkArgument(valueSetCapacity >= 0, "expectedValuesPerKey must be >= 0 but was %s", valueSetCapacity); this.valueSetCapacity = valueSetCapacity; this.multimapHeaderEntry = new ValueEntry<K, V>(null, null, 0, null); succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry); } /** * {@inheritDoc} * * <p>Creates an empty {@code LinkedHashSet} for a collection of values for * one key. * * @return a new {@code LinkedHashSet} containing a collection of values for * one key */ @Override Set<V> createCollection() { return new LinkedHashSet<V>(valueSetCapacity); } /** * {@inheritDoc} * * <p>Creates a decorated insertion-ordered set that also keeps track of the * order in which key-value pairs are added to the multimap. * * @param key key to associate with values in the collection * @return a new decorated set containing a collection of values for one key */ @Override Collection<V> createCollection(K key) { return new ValueSet(key, valueSetCapacity); } /** * {@inheritDoc} * * <p>If {@code values} is not empty and the multimap already contains a * mapping for {@code key}, the {@code keySet()} ordering is unchanged. * However, the provided values always come last in the {@link #entries()} and * {@link #values()} iteration orderings. */ @Override public Set<V> replaceValues(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; private 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 = Integer.highestOneBit(Math.max(expectedValues, 2) - 1) << 1; if (tableSize < 0) { tableSize = MAX_VALUE_SET_TABLE_SIZE; } @SuppressWarnings("unchecked") ValueEntry<K, V>[] hashTable = new ValueEntry[tableSize]; this.hashTable = hashTable; } @Override public ValueSetLink<K, V> getPredecessorInValueSet() { return lastEntry; } @Override public ValueSetLink<K, V> getSuccessorInValueSet() { return firstEntry; } @Override public void setPredecessorInValueSet(ValueSetLink<K, V> entry) { lastEntry = entry; } @Override public void setSuccessorInValueSet(ValueSetLink<K, V> entry) { firstEntry = entry; } @Override public Iterator<V> iterator() { return new Iterator<V>() { ValueSetLink<K, V> nextEntry = firstEntry; ValueEntry<K, V> toRemove; int expectedModCount = modCount; private void checkForComodification() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } @Override public boolean hasNext() { checkForComodification(); return nextEntry != ValueSet.this; } @Override public V next() { if (!hasNext()) { throw new NoSuchElementException(); } ValueEntry<K, V> entry = (ValueEntry<K, V>) nextEntry; V result = entry.getValue(); toRemove = entry; nextEntry = entry.getSuccessorInValueSet(); return result; } @Override public void remove() { checkForComodification(); Iterators.checkRemove(toRemove != null); Object o = toRemove.getValue(); int hash = (o == null) ? 0 : o.hashCode(); int row = Hashing.smear(hash) & (hashTable.length - 1); ValueEntry<K, V> prev = null; for (ValueEntry<K, V> entry = hashTable[row]; entry != null; prev = entry, entry = entry.nextInValueSetHashRow) { if (entry == toRemove) { if (prev == null) { // first entry in row hashTable[row] = entry.nextInValueSetHashRow; } else { prev.nextInValueSetHashRow = entry.nextInValueSetHashRow; } deleteFromValueSet(toRemove); deleteFromMultimap(toRemove); size--; expectedModCount = ++modCount; break; } } toRemove = null; } }; } @Override public int size() { return size; } @Override public boolean contains(@Nullable Object o) { int hash = (o == null) ? 0 : o.hashCode(); int row = Hashing.smear(hash) & (hashTable.length - 1); for (ValueEntry<K, V> entry = hashTable[row]; entry != null; entry = entry.nextInValueSetHashRow) { if (hash == entry.valueHash && Objects.equal(o, entry.getValue())) { return true; } } return false; } /** * The threshold above which the hash table should be rebuilt. */ @VisibleForTesting int threshold() { return hashTable.length; // load factor of 1.0 } @Override public boolean add(@Nullable V value) { int hash = (value == null) ? 0 : value.hashCode(); int row = Hashing.smear(hash) & (hashTable.length - 1); ValueEntry<K, V> rowHead = hashTable[row]; for (ValueEntry<K, V> entry = rowHead; entry != null; entry = entry.nextInValueSetHashRow) { if (hash == entry.valueHash && Objects.equal(value, entry.getValue())) { return false; } } ValueEntry<K, V> newEntry = new ValueEntry<K, V>(key, value, hash, rowHead); succeedsInValueSet(lastEntry, newEntry); succeedsInValueSet(newEntry, this); succeedsInMultimap(multimapHeaderEntry.getPredecessorInMultimap(), newEntry); succeedsInMultimap(newEntry, multimapHeaderEntry); hashTable[row] = newEntry; size++; modCount++; rehashIfNecessary(); return true; } private void rehashIfNecessary() { if (size > threshold() && hashTable.length < MAX_VALUE_SET_TABLE_SIZE) { @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 row = Hashing.smear(valueEntry.valueHash) & mask; valueEntry.nextInValueSetHashRow = hashTable[row]; hashTable[row] = valueEntry; } } } @Override public boolean remove(@Nullable Object o) { int hash = (o == null) ? 0 : o.hashCode(); int row = Hashing.smear(hash) & (hashTable.length - 1); ValueEntry<K, V> prev = null; for (ValueEntry<K, V> entry = hashTable[row]; entry != null; prev = entry, entry = entry.nextInValueSetHashRow) { if (hash == entry.valueHash && Objects.equal(o, entry.getValue())) { if (prev == null) { // first entry in the row hashTable[row] = entry.nextInValueSetHashRow; } else { prev.nextInValueSetHashRow = entry.nextInValueSetHashRow; } 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>> createEntryIterator() { return new Iterator<Map.Entry<K, V>>() { ValueEntry<K, V> nextEntry = multimapHeaderEntry.successorInMultimap; ValueEntry<K, V> toRemove; @Override public boolean hasNext() { return nextEntry != multimapHeaderEntry; } @Override public Map.Entry<K, V> next() { if (!hasNext()) { throw new NoSuchElementException(); } ValueEntry<K, V> result = nextEntry; toRemove = result; nextEntry = nextEntry.successorInMultimap; return result; } @Override public void remove() { Iterators.checkRemove(toRemove != null); LinkedHashMultimap.this.remove(toRemove.getKey(), toRemove.getValue()); toRemove = null; } }; } @Override public void clear() { super.clear(); succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import 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()); } /** @deprecated */ @Deprecated public static <E> ImmutableSet<E> of(E[] elements) { return copyOf(elements); } 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()); } } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.Map.Entry; import javax.annotation.Nullable; /** * {@code keySet()} implementation for {@link ImmutableMap}. * * @author Jesse Wilson * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) abstract class ImmutableMapKeySet<K, V> extends TransformedImmutableSet<Entry<K, V>, K> { ImmutableMapKeySet(ImmutableSet<Entry<K, V>> entrySet) { super(entrySet); } ImmutableMapKeySet(ImmutableSet<Entry<K, V>> entrySet, int hashCode) { super(entrySet, hashCode); } abstract ImmutableMap<K, V> map(); @Override K transform(Entry<K, V> entry) { return entry.getKey(); } @Override public boolean contains(@Nullable Object object) { return map().containsKey(object); } @Override boolean isPartialView() { return true; } @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; } }; } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Collections; /** * GWT emulation of {@link SingletonImmutableMap}. * * @author Hayward Chan */ final class SingletonImmutableMap<K, V> extends ForwardingImmutableMap<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; SingletonImmutableMap(K key, V value) { super(Collections.singletonMap(checkNotNull(key), checkNotNull(value))); this.singleKey = key; this.singleValue = value; } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Joiner; 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() { throw new IllegalStateException(); } }; /** * 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 an unmodifiable view of {@code iterator}. */ static <T> UnmodifiableListIterator<T> unmodifiableListIterator( final ListIterator<T> iterator) { checkNotNull(iterator); if (iterator instanceof UnmodifiableListIterator) { return (UnmodifiableListIterator<T>) iterator; } return new UnmodifiableListIterator<T>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public boolean hasPrevious() { return iterator.hasPrevious(); } @Override public T next() { return iterator.next(); } @Override public T previous() { return iterator.previous(); } @Override public int nextIndex() { return iterator.nextIndex(); } @Override public int previousIndex() { return iterator.previousIndex(); } }; } /** * 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) { if (element == null) { while (iterator.hasNext()) { if (iterator.next() == null) { return true; } } } else { while (iterator.hasNext()) { if (element.equals(iterator.next())) { return true; } } } return false; } /** * 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) { checkNotNull(elementsToRemove); boolean modified = false; while (removeFrom.hasNext()) { if (elementsToRemove.contains(removeFrom.next())) { removeFrom.remove(); modified = true; } } return modified; } /** * 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) { checkNotNull(elementsToRetain); boolean modified = false; while (removeFrom.hasNext()) { if (!elementsToRetain.contains(removeFrom.next())) { removeFrom.remove(); modified = true; } } return modified; } /** * 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 Joiner.on(", ") .useForNull("null") .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); 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) { int result = 0; if (element == null) { while (iterator.hasNext()) { if (iterator.next() == null) { result++; } } } else { while (iterator.hasNext()) { if (element.equals(iterator.next())) { result++; } } } return result; } /** * 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() { checkState(removeFrom != null, "no calls to next() since last call to remove()"); removeFrom.remove(); removeFrom = null; } }; } /** * Returns an iterator that cycles indefinitely over the provided elements. * * <p>The returned iterator supports {@code remove()} if the provided iterator * does. 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. */ @SuppressWarnings("unchecked") public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b) { checkNotNull(a); checkNotNull(b); return concat(Arrays.asList(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. */ @SuppressWarnings("unchecked") public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b, Iterator<? extends T> c) { checkNotNull(a); checkNotNull(b); checkNotNull(c); return concat(Arrays.asList(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. */ @SuppressWarnings("unchecked") public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b, Iterator<? extends T> c, Iterator<? extends T> d) { checkNotNull(a); checkNotNull(b); checkNotNull(c); checkNotNull(d); return concat(Arrays.asList(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() { checkState(removeFrom != null, "no calls to next() since last call to remove()"); 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) { checkNotNull(predicate); while (iterator.hasNext()) { T element = iterator.next(); if (predicate.apply(element)) { return true; } } return false; } /** * 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) { UnmodifiableIterator<? extends T> filteredIterator = filter(iterator, predicate); return filteredIterator.hasNext() ? filteredIterator.next() : 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 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"); int i = 0; while (iterator.hasNext()) { T current = iterator.next(); if (predicate.apply(current)) { return i; } 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 = 0; while (iterator.hasNext()) { T t = iterator.next(); if (skipped++ == position) { return t; } } throw new IndexOutOfBoundsException("position (" + position + ") must be less than the number of elements that remained (" + skipped + ")"); } private 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); try { return get(iterator, position); } catch (IndexOutOfBoundsException e) { return 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, "number to advance cannot be negative"); 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; } }; } // 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) { // TODO(kevinb): compare performance with Arrays.asList(array).iterator(). checkNotNull(array); // eager for GWT. return new AbstractIndexedListIterator<T>(array.length) { @Override protected T get(int index) { return array[index]; } }; } /** * 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); /* * 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> * * 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 AbstractIterator<T> { final Queue<PeekingIterator<T>> queue; final Comparator<? super T> comparator; public MergingIterator(Iterable<? extends Iterator<? extends T>> iterators, Comparator<? super T> itemComparator) { this.comparator = 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 comparator.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 protected T computeNext() { if (queue.isEmpty()) { return endOfData(); } PeekingIterator<T> nextIter = queue.poll(); T next = nextIter.next(); if (nextIter.hasNext()) { queue.add(nextIter); } return next; } } /** * Precondition tester for {@code Iterator.remove()} that throws an exception with a consistent * error message. */ static void checkRemove(boolean canRemove) { checkState(canRemove, "no calls to next() since the last call to remove()"); } /** * 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; } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import 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)); } public UnmodifiableListIterator<E> listIterator() { return Iterators.unmodifiableListIterator(delegateList().listIterator()); } public UnmodifiableListIterator<E> listIterator(int index) { return Iterators.unmodifiableListIterator(delegateList().listIterator(index)); } @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(); } }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import java.util.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); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.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); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.base.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 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, float loadFactor) { this(expirationMillis, null, maximumSize, initialCapacity, loadFactor); } ExpiringComputingMap(long expirationMillis, Function<? super K, ? extends V> computer, int maximumSize, int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor, (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 float loadFactor = 0.75f; 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; } public MapMaker loadFactor(float loadFactor) { if (loadFactor <= 0) { throw new IllegalArgumentException(); } this.loadFactor = loadFactor; 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, loadFactor) : new ConcurrentHashMap<K, V>(initialCapacity, loadFactor); } @Override public <K, V> ConcurrentMap<K, V> makeComputingMap(Function<? super K, ? extends V> computer) { return new ExpiringComputingMap<K, V>( expirationMillis, computer, maximumSize, initialCapacity, loadFactor); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.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.Nullable; /** * {@code FluentIterable} provides a rich interface for manipulating {@code Iterable}s 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> * * 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 */ @Beta @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. */ 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()}. */ 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 */ public <T> FluentIterable<T> transformAndConcat( Function<? super E, ? extends Iterable<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}. */ 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 */ 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()}). */ public final ImmutableList<E> toSortedList(Comparator<? super E> comparator) { return Ordering.from(comparator).immutableSortedCopy(iterable); } /** * Returns an {@code ImmutableSet} containing all of the elements from this fluent iterable with * duplicates removed. * * @since 14.0 (since 12.0 as {@code toImmutableSet()}). */ public final ImmutableSet<E> toSet() { return ImmutableSet.copyOf(iterable); } /** * Returns an {@code ImmutableSortedSet} containing all of the elements from this {@code * FluentIterable} in the order specified by {@code comparator}, with duplicates (determined by * {@code comparator.compare(x, y) == 0}) removed. To produce an {@code ImmutableSortedSet} sorted * by its natural ordering, use {@code toSortedSet(Ordering.natural())}. * * @param comparator the function by which to sort set elements * @throws NullPointerException if any element is null * @since 14.0 (since 12.0 as {@code toImmutableSortedSet()}). */ public final ImmutableSortedSet<E> toSortedSet(Comparator<? super E> comparator) { return ImmutableSortedSet.copyOf(comparator, iterable); } /** * Returns an immutable map for which the elements of this {@code FluentIterable} are the keys in * the same order, mapped to values by the given function. If this iterable contains duplicate * elements, the returned map will contain each distinct element once in the order it first * appears. * * @throws NullPointerException if any element of this iterable is {@code null}, or if {@code * valueFunction} produces {@code null} for any key * @since 14.0 */ public final <V> ImmutableMap<E, V> toMap(Function<? super E, V> valueFunction) { return Maps.toMap(iterable, valueFunction); } /** * Creates an index {@code ImmutableListMultimap} that contains the results of applying a * specified function to each item in this {@code FluentIterable} of values. Each element of this * iterable will be stored as a value in the resulting multimap, yielding a multimap with the same * size as this iterable. The key used to store that value in the multimap will be the result of * calling the function on that value. The resulting multimap is created as an immutable snapshot. * In the returned multimap, keys appear in the order they are first encountered, and the values * corresponding to each key appear in the same order as they are encountered. * * @param keyFunction the function used to produce the key for each value * @throws NullPointerException if any of the following cases is true: * <ul> * <li>{@code keyFunction} is null * <li>An element in this fluent iterable is null * <li>{@code keyFunction} returns {@code null} for any element of this iterable * </ul> * @since 14.0 */ public final <K> ImmutableListMultimap<K, E> index(Function<? super E, K> keyFunction) { return Multimaps.index(iterable, keyFunction); } /** * Returns an immutable map for which the {@link java.util.Map#values} are the elements of this * {@code FluentIterable} in the given order, and each key is the product of invoking a supplied * function on its corresponding value. * * @param keyFunction the function used to produce the key for each value * @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one * value in this fluent iterable * @throws NullPointerException if any element of this fluent iterable is null, or if * {@code keyFunction} produces {@code null} for any value * @since 14.0 */ public final <K> ImmutableMap<K, E> uniqueIndex(Function<? super E, K> keyFunction) { return Maps.uniqueIndex(iterable, keyFunction); } /** * Returns an {@code ImmutableList} containing all of the elements from this * fluent iterable in proper sequence. * * @deprecated Use {@link #toList()} instead. This method is scheduled for removal in Guava 15.0. */ @Deprecated public final ImmutableList<E> toImmutableList() { return toList(); } /** * 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 toSortedImmutableList(Ordering.natural())}. * * @param comparator the function by which to sort list elements * @throws NullPointerException if any element is null * @since 13.0 * @deprecated Use {@link #toSortedList(Comparator)} instead. This method is scheduled for removal * in Guava 15.0. */ @Deprecated public final ImmutableList<E> toSortedImmutableList(Comparator<? super E> comparator) { return toSortedList(comparator); } /** * Returns an {@code ImmutableSet} containing all of the elements from this * fluent iterable with duplicates removed. * * @deprecated Use {@link #toSet()} instead. This method is scheduled for removal in Guava 15.0. */ @Deprecated public final ImmutableSet<E> toImmutableSet() { return toSet(); } /** * 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 toImmutableSortedSet(Ordering.natural())}. * * @param comparator the function by which to sort set elements * @throws NullPointerException if any element is null * @deprecated Use {@link #toSortedSet(Comparator)} instead. This method is scheduled for removal * in Guava 15.0. */ @Deprecated public final ImmutableSortedSet<E> toImmutableSortedSet(Comparator<? super E> comparator) { return toSortedSet(comparator); } /** * Copies all the elements from this fluent iterable to {@code collection}. This is equivalent to * calling {@code Iterables.addAll(collection, this)}. * * @param collection the collection to copy elements to * @return {@code collection}, for convenience * @since 14.0 */ public final <C extends Collection<? super E>> C copyInto(C collection) { checkNotNull(collection); if (iterable instanceof Collection) { collection.addAll(Collections2.cast(iterable)); } else { for (E item : iterable) { collection.add(item); } } return collection; } /** * Returns the element at the specified position in this fluent iterable. * * @param position position of the element to return * @return the element at the specified position in this fluent iterable * @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to * the size of this fluent iterable */ public final E get(int position) { return Iterables.get(iterable, position); } /** * Function that transforms {@code Iterable<E>} into a fluent iterable. */ private static class FromIterableFunction<E> implements Function<Iterable<E>, FluentIterable<E>> { @Override public FluentIterable<E> apply(Iterable<E> fromObject) { return FluentIterable.from(fromObject); } } }
Java
/* * Copyright (C) 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))); } }
Java
/* * 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); }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package 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); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package 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); }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package 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; } }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package 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; } }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.util.concurrent; /** * Emulation of Callable. * * @author Charles Fry */ public interface Callable<V> { V call() throws Exception; }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package 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()); } }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package 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; } }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package 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; } }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package 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; } }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import com.google.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.asUnsigned(reader.readLong()); } public static void serialize(SerializationStreamWriter writer, UnsignedLong instance) throws SerializationException { writer.writeLong(instance.longValue()); } }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.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) {} }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.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); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.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 // None of these classes are instantiated, let alone serialized: @SuppressWarnings("serial") 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(); } } }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.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()); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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() {} }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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()); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; /** * 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 {}
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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 implements the GWT serialization of {@link HashBasedTable}. * * @author Hayward Chan */ public class HashBasedTable_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, HashBasedTable<?, ?, ?> instance) { } public static HashBasedTable<Object, Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { Map<?, ?> hashMap = (Map<?, ?>) reader.readObject(); HashBasedTable<Object, Object, Object> table = HashBasedTable.create(); for (Entry<?, ?> row : hashMap.entrySet()) { table.row(row.getKey()).putAll((Map<?, ?>) row.getValue()); } return table; } public static void serialize(SerializationStreamWriter writer, HashBasedTable<?, ?, ?> instance) throws SerializationException { /* * The backing map of a HashBasedTable is a hash map of hash map. * Therefore, the backing map is serializable (assuming the row, * column and values are all serializable). */ writer.writeObject(instance.backingMap); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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()); } } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.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 SingletonImmutableMap}. * * @author Chris Povirk */ public class SingletonImmutableMap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, SingletonImmutableMap<?, ?> instance) { } public static SingletonImmutableMap<Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { Object key = checkNotNull(reader.readObject()); Object value = checkNotNull(reader.readObject()); return new SingletonImmutableMap<Object, Object>(key, value); } public static void serialize(SerializationStreamWriter writer, SingletonImmutableMap<?, ?> instance) throws SerializationException { writer.writeObject(instance.singleKey); writer.writeObject(instance.singleValue); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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()); } } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; /** * 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 {}
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link EmptyImmutableList}. * * @author Chris Povirk */ public class EmptyImmutableList_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, EmptyImmutableList instance) { } public static EmptyImmutableList instantiate( SerializationStreamReader reader) { return EmptyImmutableList.INSTANCE; } public static void serialize(SerializationStreamWriter writer, EmptyImmutableList instance) { } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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) { } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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) { } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; /** * 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 {}
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; /** * 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 {}
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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) { } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.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() { super(); } } 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); } } 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); } } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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; import java.util.Map; import java.util.Map.Entry; /** * This class implements the GWT serialization of {@link TreeBasedTable}. * * @author Hayward Chan */ public class TreeBasedTable_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, TreeBasedTable<?, ?, ?> instance) { } 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(); Map<?, ?> backingMap = (Map<?, ?>) reader.readObject(); TreeBasedTable<Object, Object, Object> table = TreeBasedTable.create(rowComparator, columnComparator); for (Entry<?, ?> row : backingMap.entrySet()) { table.row(row.getKey()).putAll((Map<?, ?>) row.getValue()); } return table; } public static void serialize(SerializationStreamWriter writer, TreeBasedTable<?, ?, ?> instance) throws SerializationException { /* * The backing map of a TreeBasedTable is a tree map of tree map. * Therefore, the backing map is GWT serializable (assuming the row, * column, value, the row comparator and column comparator are all * serializable). */ writer.writeObject(instance.rowComparator()); writer.writeObject(instance.columnComparator()); writer.writeObject(instance.backingMap); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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() {} }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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) { } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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 NullsFirstOrdering}. * * @author Chris Povirk */ public class NullsFirstOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, NullsFirstOrdering<?> instance) { } @SuppressWarnings("unchecked") // deserialization is unsafe public static NullsFirstOrdering<Object> instantiate( SerializationStreamReader reader) throws SerializationException { return new NullsFirstOrdering<Object>( (Ordering<Object>) reader.readObject()); } public static void serialize(SerializationStreamWriter writer, NullsFirstOrdering<?> instance) throws SerializationException { writer.writeObject(instance.ordering); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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 CompoundOrdering}. * * @author Chris Povirk */ public class CompoundOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, CompoundOrdering<?> instance) { } @SuppressWarnings("unchecked") // deserialization is unsafe public static CompoundOrdering<Object> instantiate( SerializationStreamReader reader) throws SerializationException { return new CompoundOrdering<Object>( (ImmutableList<Comparator<Object>>) reader.readObject()); } public static void serialize(SerializationStreamWriter writer, CompoundOrdering<?> instance) throws SerializationException { writer.writeObject(instance.comparators); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link NaturalOrdering}. * * @author Chris Povirk */ public class NaturalOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, NaturalOrdering instance) { } public static NaturalOrdering instantiate( SerializationStreamReader reader) { return NaturalOrdering.INSTANCE; } public static void serialize(SerializationStreamWriter writer, NaturalOrdering instance) { } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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 SingletonImmutableList}. * * @author Chris Povirk */ public class SingletonImmutableList_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, SingletonImmutableList<?> instance) { } public static SingletonImmutableList<Object> instantiate( SerializationStreamReader reader) throws SerializationException { Object element = reader.readObject(); return new SingletonImmutableList<Object>(element); } public static void serialize(SerializationStreamWriter writer, SingletonImmutableList<?> instance) throws SerializationException { writer.writeObject(instance.element); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; /** * Even though {@link ForwardingImmutableSet} cannot be instantiated, we still * need a custom field serializer. TODO(cpovirk): why? * * @author Hayward Chan */ public final class ForwardingImmutableSet_CustomFieldSerializer {}
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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 ExplicitOrdering}. * * @author Chris Povirk */ public class ExplicitOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ExplicitOrdering<?> instance) { } @SuppressWarnings("unchecked") // deserialization is unsafe public static ExplicitOrdering<Object> instantiate( SerializationStreamReader reader) throws SerializationException { return new ExplicitOrdering<Object>( (ImmutableMap<Object, Integer>) reader.readObject()); } public static void serialize(SerializationStreamWriter writer, ExplicitOrdering<?> instance) throws SerializationException { writer.writeObject(instance.rankMap); } }
Java
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import 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 server-side GWT serialization of * {@link RegularImmutableAsList}. * * @author Hayward Chan */ @GwtCompatible(emulated = true) public class RegularImmutableAsList_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, RegularImmutableAsList<?> instance) { } public static RegularImmutableAsList<Object> instantiate( SerializationStreamReader reader) throws SerializationException { @SuppressWarnings("unchecked") // serialization is necessarily type unsafe ImmutableCollection<Object> delegateCollection = (ImmutableCollection) reader.readObject(); ImmutableList<?> delegateList = (ImmutableList<?>) reader.readObject(); return new RegularImmutableAsList<Object>(delegateCollection, delegateList); } public static void serialize(SerializationStreamWriter writer, RegularImmutableAsList<?> instance) throws SerializationException { writer.writeObject(instance.delegateCollection()); writer.writeObject(instance.delegateList()); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; /** * Even though {@link ForwardingImmutableList} cannot be instantiated, we still * need a custom field serializer. TODO(cpovirk): why? * * @author Hayward Chan */ public final class ForwardingImmutableList_CustomFieldSerializer {}
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of * {@link ReverseNaturalOrdering}. * * @author Chris Povirk */ public class ReverseNaturalOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ReverseNaturalOrdering instance) { } public static ReverseNaturalOrdering instantiate( SerializationStreamReader reader) { return ReverseNaturalOrdering.INSTANCE; } public static void serialize(SerializationStreamWriter writer, ReverseNaturalOrdering instance) { } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; /** * Even though {@link ImmutableSet} cannot be instantiated, we still need * a custom field serializer to unify the type signature of * {@code ImmutableSet[]} on server and client side. * * @author Hayward Chan */ public final class ImmutableSet_CustomFieldSerializer {}
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link AllEqualOrdering}. * * @author Chris Povirk */ public class AllEqualOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, AllEqualOrdering instance) { } public static AllEqualOrdering instantiate(SerializationStreamReader reader) { return AllEqualOrdering.INSTANCE; } public static void serialize(SerializationStreamWriter writer, AllEqualOrdering instance) { } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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 ImmutableListMultimap}. * * @author Chris Povirk */ public class ImmutableListMultimap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ImmutableListMultimap<?, ?> instance) { } public static ImmutableListMultimap<Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { return (ImmutableListMultimap<Object, Object>) Multimap_CustomFieldSerializerBase.instantiate( reader, ImmutableListMultimap.builder()); } public static void serialize(SerializationStreamWriter writer, ImmutableListMultimap<?, ?> instance) throws SerializationException { Multimap_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; /** * Even though {@link ImmutableSortedMap} cannot be instantiated, we still need a custom field * serializer. TODO(cpovirk): why? Does it help if ensure that the GWT and non-GWT classes have the * same fields? Is that worth the trouble? * * @author Chris Povirk */ public final class ImmutableSortedMap_CustomFieldSerializer {}
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of * {@link EmptyImmutableMultiset}. * * @author Chris Povirk */ public class EmptyImmutableMultiset_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, EmptyImmutableMultiset instance) { } public static EmptyImmutableMultiset instantiate( SerializationStreamReader reader) { return EmptyImmutableMultiset.INSTANCE; } public static void serialize(SerializationStreamWriter writer, EmptyImmutableMultiset instance) { } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import com.google.gwt.core.client.GwtScriptOnly; /** * 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> * {@literal @}GwtScriptOnly</code> only supports public classes and methods. * * @author Hayward Chan */ @GwtScriptOnly @GwtCompatible public final class GwtPlatform { private GwtPlatform() {} /** See {@link Platform#clone(Object[])} */ public static <T> T[] clone(T[] array) { return array.clone(); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; /** * Even though {@link ImmutableAsList} cannot be instantiated, we still need * a custom field serializer. TODO(cpovirk): why? * * @author Hayward Chan */ public final class ImmutableAsList_CustomFieldSerializer {}
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of * {@link EmptyImmutableMap}. * * @author Chris Povirk */ public class EmptyImmutableMap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, EmptyImmutableMap instance) { } public static EmptyImmutableMap instantiate( SerializationStreamReader reader) { return EmptyImmutableMap.INSTANCE; } public static void serialize(SerializationStreamWriter writer, EmptyImmutableMap instance) { } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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 TreeMultimap}. * * @author Nikhil Singhal */ public class TreeMultimap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader in, TreeMultimap<?, ?> out) { } @SuppressWarnings("unchecked") public static TreeMultimap<Object, Object> instantiate( SerializationStreamReader in) throws SerializationException { Comparator keyComparator = (Comparator) in.readObject(); Comparator valueComparator = (Comparator) in.readObject(); return (TreeMultimap<Object, Object>) Multimap_CustomFieldSerializerBase.populate( in, TreeMultimap.create(keyComparator, valueComparator)); } public static void serialize(SerializationStreamWriter out, TreeMultimap<?, ?> multimap) throws SerializationException { out.writeObject(multimap.keyComparator()); out.writeObject(multimap.valueComparator()); Multimap_CustomFieldSerializerBase.serialize(out, multimap); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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 ImmutableSetMultimap}. * * @author Chris Povirk */ public class ImmutableSetMultimap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ImmutableSetMultimap<?, ?> instance) { } public static ImmutableSetMultimap<Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { return (ImmutableSetMultimap<Object, Object>) Multimap_CustomFieldSerializerBase.instantiate( reader, ImmutableSetMultimap.builder()); } public static void serialize(SerializationStreamWriter writer, ImmutableSetMultimap<?, ?> instance) throws SerializationException { Multimap_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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.Comparator; import java.util.SortedMap; import java.util.TreeMap; /** * This class contains static utility methods for writing {@code ImmutableSortedMap} GWT field * serializers. * * @author Chris Povirk */ final class ImmutableSortedMap_CustomFieldSerializerBase { static ImmutableSortedMap<Object, 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(); SortedMap<Object, Object> entries = new TreeMap<Object, Object>(comparator); Map_CustomFieldSerializerBase.deserialize(reader, entries); return ImmutableSortedMap.orderedBy(comparator).putAll(entries).build(); } static void serialize(SerializationStreamWriter writer, ImmutableSortedMap<?, ?> instance) throws SerializationException { writer.writeObject(instance.comparator()); Map_CustomFieldSerializerBase.serialize(writer, instance); } private ImmutableSortedMap_CustomFieldSerializerBase() {} }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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.List; /** * This class implements the GWT serialization of {@link RegularImmutableSet}. * * @author Hayward Chan */ public class RegularImmutableSet_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, RegularImmutableSet<?> instance) { } public static RegularImmutableSet<Object> instantiate( SerializationStreamReader reader) throws SerializationException { List<Object> elements = Lists.newArrayList(); Collection_CustomFieldSerializerBase.deserialize(reader, elements); /* * For this custom field serializer to be invoked, the set must have been * RegularImmutableSet before it's serialized. Since RegularImmutableSet * always have two or more elements, ImmutableSet.copyOf always return * a RegularImmutableSet back. */ return (RegularImmutableSet<Object>) ImmutableSet.copyOf(elements); } public static void serialize(SerializationStreamWriter writer, RegularImmutableSet<?> instance) throws SerializationException { Collection_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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 HashMultiset}. * * @author Chris Povirk */ public class HashMultiset_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, HashMultiset<?> instance) { } public static HashMultiset<Object> instantiate( SerializationStreamReader reader) throws SerializationException { return (HashMultiset<Object>) Multiset_CustomFieldSerializerBase.populate( reader, HashMultiset.create()); } public static void serialize(SerializationStreamWriter writer, HashMultiset<?> instance) throws SerializationException { Multiset_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of * {@link EmptyImmutableListMultimap}. * * @author Chris Povirk */ public class EmptyImmutableListMultimap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, EmptyImmutableListMultimap instance) { } public static EmptyImmutableListMultimap instantiate( SerializationStreamReader reader) { return EmptyImmutableListMultimap.INSTANCE; } public static void serialize(SerializationStreamWriter writer, EmptyImmutableListMultimap instance) { } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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 RegularImmutableBiMap}. * * @author Chris Povirk */ public class RegularImmutableBiMap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, RegularImmutableBiMap<?, ?> instance) { } public static RegularImmutableBiMap<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 * RegularImmutableBiMap before it's serialized. Since RegularImmutableBiMap * always have one or more elements, ImmutableBiMap.copyOf always return a * RegularImmutableBiMap back. */ return (RegularImmutableBiMap<Object, Object>) ImmutableBiMap.copyOf(entries); } public static void serialize(SerializationStreamWriter writer, RegularImmutableBiMap<?, ?> instance) throws SerializationException { Map_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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.List; /** * This class implements the GWT serialization of {@link * RegularImmutableList}. * * @author Hayward Chan */ public class RegularImmutableList_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, RegularImmutableList<?> instance) { } public static RegularImmutableList<Object> instantiate( SerializationStreamReader reader) throws SerializationException { List<Object> elements = new ArrayList<Object>(); Collection_CustomFieldSerializerBase.deserialize(reader, elements); /* * For this custom field serializer to be invoked, the list must have been * RegularImmutableList before it's serialized. Since RegularImmutableList * always have one or more elements, ImmutableList.copyOf always return * a RegularImmutableList back. */ return (RegularImmutableList<Object>) ImmutableList.copyOf(elements); } public static void serialize(SerializationStreamWriter writer, RegularImmutableList<?> instance) throws SerializationException { Collection_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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.List; /** * This class implements the GWT serialization of {@link RegularImmutableMultiset}. * * @author Louis Wasserman */ public class RegularImmutableMultiset_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, RegularImmutableMultiset<?> instance) { } public static RegularImmutableMultiset<Object> instantiate( SerializationStreamReader reader) throws SerializationException { List<Object> elements = Lists.newArrayList(); Collection_CustomFieldSerializerBase.deserialize(reader, elements); /* * For this custom field serializer to be invoked, the set must have been * RegularImmutableMultiset before it's serialized. Since * RegularImmutableMultiset always have one or more elements, * ImmutableMultiset.copyOf always return a RegularImmutableMultiset back. */ return (RegularImmutableMultiset<Object>) ImmutableMultiset .copyOf(elements); } public static void serialize(SerializationStreamWriter writer, RegularImmutableMultiset<?> instance) throws SerializationException { Collection_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.base.Function; 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 ByFunctionOrdering}. * * @author Chris Povirk */ public class ByFunctionOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ByFunctionOrdering<?, ?> instance) { } @SuppressWarnings("unchecked") // deserialization is unsafe public static ByFunctionOrdering<Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { return new ByFunctionOrdering<Object, Object>( (Function<Object, Object>) reader.readObject(), (Ordering<Object>) reader.readObject()); } public static void serialize(SerializationStreamWriter writer, ByFunctionOrdering<?, ?> instance) throws SerializationException { writer.writeObject(instance.function); writer.writeObject(instance.ordering); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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.List; /** * This class implements the GWT serialization of {@link ImmutableEnumSet}. * * @author Hayward Chan */ public class ImmutableEnumSet_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ImmutableEnumSet<?> instance) { } public static <E extends Enum<E>> ImmutableEnumSet<?> instantiate( SerializationStreamReader reader) throws SerializationException { List<E> deserialized = Lists.newArrayList(); Collection_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 (ImmutableEnumSet<?>) Sets.immutableEnumSet(deserialized); } public static void serialize(SerializationStreamWriter writer, ImmutableEnumSet<?> instance) throws SerializationException { Collection_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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 EmptyImmutableSortedSet}. * * @author Chris Povirk */ public class EmptyImmutableSortedSet_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, EmptyImmutableSortedSet<?> instance) { } public static EmptyImmutableSortedSet<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(); /* * For this custom field serializer to be invoked, the set must have been * EmptyImmutableSortedSet before it's serialized. Since * EmptyImmutableSortedSet always has no elements, ImmutableSortedSet.copyOf * always return an EmptyImmutableSortedSet back. */ return (EmptyImmutableSortedSet<Object>) ImmutableSortedSet.orderedBy(comparator).build(); } public static void serialize(SerializationStreamWriter writer, EmptyImmutableSortedSet<?> instance) throws SerializationException { writer.writeObject(instance.comparator()); } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import android.graphics.Bitmap; import android.graphics.Canvas; /** * The Canvas version of a sprite. This class keeps a pointer to a bitmap * and draws it at the Sprite's current location. */ public class CanvasSprite extends Renderable { private Bitmap mBitmap; public CanvasSprite(Bitmap bitmap) { mBitmap = bitmap; } public void draw(Canvas canvas) { // The Canvas system uses a screen-space coordinate system, that is, // 0,0 is the top-left point of the canvas. But in order to align // with OpenGL's coordinate space (which places 0,0 and the lower-left), // for this test I flip the y coordinate. canvas.drawBitmap(mBitmap, x, canvas.getHeight() - (y + height), null); } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import android.os.SystemClock; /** * Implements a simple runtime profiler. The profiler records start and stop * times for several different types of profiles and can then return min, max * and average execution times per type. Profile types are independent and may * be nested in calling code. This object is a singleton for convenience. */ public class ProfileRecorder { // A type for recording actual draw command time. public static final int PROFILE_DRAW = 0; // A type for recording the time it takes to display the scene. public static final int PROFILE_PAGE_FLIP = 1; // A type for recording the time it takes to run a single simulation step. public static final int PROFILE_SIM = 2; // A type for recording the total amount of time spent rendering a frame. public static final int PROFILE_FRAME = 3; private static final int PROFILE_COUNT = PROFILE_FRAME + 1; private ProfileRecord[] mProfiles; private int mFrameCount; public static ProfileRecorder sSingleton = new ProfileRecorder(); public ProfileRecorder() { mProfiles = new ProfileRecord[PROFILE_COUNT]; for (int x = 0; x < PROFILE_COUNT; x++) { mProfiles[x] = new ProfileRecord(); } } /** Starts recording execution time for a specific profile type.*/ public void start(int profileType) { if (profileType < PROFILE_COUNT) { mProfiles[profileType].start(SystemClock.uptimeMillis()); } } /** Stops recording time for this profile type. */ public void stop(int profileType) { if (profileType < PROFILE_COUNT) { mProfiles[profileType].stop(SystemClock.uptimeMillis()); } } /** Indicates the end of the frame.*/ public void endFrame() { mFrameCount++; } /* Flushes all recorded timings from the profiler. */ public void resetAll() { for (int x = 0; x < PROFILE_COUNT; x++) { mProfiles[x].reset(); } mFrameCount = 0; } /* Returns the average execution time, in milliseconds, for a given type. */ public long getAverageTime(int profileType) { long time = 0; if (profileType < PROFILE_COUNT) { time = mProfiles[profileType].getAverageTime(mFrameCount); } return time; } /* Returns the minimum execution time in milliseconds for a given type. */ public long getMinTime(int profileType) { long time = 0; if (profileType < PROFILE_COUNT) { time = mProfiles[profileType].getMinTime(); } return time; } /* Returns the maximum execution time in milliseconds for a given type. */ public long getMaxTime(int profileType) { long time = 0; if (profileType < PROFILE_COUNT) { time = mProfiles[profileType].getMaxTime(); } return time; } /** * A simple class for storing timing information about a single profile * type. */ protected class ProfileRecord { private long mStartTime; private long mTotalTime; private long mMinTime; private long mMaxTime; public void start(long time) { mStartTime = time; } public void stop(long time) { final long timeDelta = time - mStartTime; mTotalTime += timeDelta; if (mMinTime == 0 || timeDelta < mMinTime) { mMinTime = timeDelta; } if (mMaxTime == 0 || timeDelta > mMaxTime) { mMaxTime = timeDelta; } } public long getAverageTime(int frameCount) { long time = frameCount > 0 ? mTotalTime / frameCount : 0; return time; } public long getMinTime() { return mMinTime; } public long getMaxTime() { return mMaxTime; } public void startNewProfilePeriod() { mTotalTime = 0; } public void reset() { mTotalTime = 0; mStartTime = 0; mMinTime = 0; mMaxTime = 0; } } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; /** * Implements a surface view which writes updates to the surface's canvas using * a separate rendering thread. This class is based heavily on GLSurfaceView. */ public class CanvasSurfaceView extends SurfaceView implements SurfaceHolder.Callback { private boolean mSizeChanged = true; private SurfaceHolder mHolder; private CanvasThread mCanvasThread; public CanvasSurfaceView(Context context) { super(context); init(); } public CanvasSurfaceView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL); } public SurfaceHolder getSurfaceHolder() { return mHolder; } /** Sets the user's renderer and kicks off the rendering thread. */ public void setRenderer(Renderer renderer) { mCanvasThread = new CanvasThread(mHolder, renderer); mCanvasThread.start(); } public void surfaceCreated(SurfaceHolder holder) { mCanvasThread.surfaceCreated(); } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return mCanvasThread.surfaceDestroyed(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Surface size or format has changed. This should not happen in this // example. mCanvasThread.onWindowResize(w, h); } /** Inform the view that the activity is paused.*/ public void onPause() { mCanvasThread.onPause(); } /** Inform the view that the activity is resumed. */ public void onResume() { mCanvasThread.onResume(); } /** Inform the view that the window focus has changed. */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mCanvasThread.onWindowFocusChanged(hasFocus); } /** * Set an "event" to be run on the rendering thread. * @param r the runnable to be run on the rendering thread. */ public void setEvent(Runnable r) { mCanvasThread.setEvent(r); } /** Clears the runnable event, if any, from the rendering thread. */ public void clearEvent() { mCanvasThread.clearEvent(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mCanvasThread.requestExitAndWait(); } protected void stopDrawing() { mCanvasThread.requestExitAndWait(); } // ---------------------------------------------------------------------- /** A generic renderer interface. */ public interface Renderer { /** * Surface changed size. * Called after the surface is created and whenever * the surface size changes. Set your viewport here. * @param width * @param height */ void sizeChanged(int width, int height); /** * Draw the current frame. * @param canvas The target canvas to draw into. */ void drawFrame(Canvas canvas); } /** * A generic Canvas rendering Thread. Delegates to a Renderer instance to do * the actual drawing. */ class CanvasThread extends Thread { private boolean mDone; private boolean mPaused; private boolean mHasFocus; private boolean mHasSurface; private boolean mContextLost; private int mWidth; private int mHeight; private Renderer mRenderer; private Runnable mEvent; private SurfaceHolder mSurfaceHolder; CanvasThread(SurfaceHolder holder, Renderer renderer) { super(); mDone = false; mWidth = 0; mHeight = 0; mRenderer = renderer; mSurfaceHolder = holder; setName("CanvasThread"); } @Override public void run() { boolean tellRendererSurfaceChanged = true; /* * This is our main activity thread's loop, we go until * asked to quit. */ final ProfileRecorder profiler = ProfileRecorder.sSingleton; while (!mDone) { profiler.start(ProfileRecorder.PROFILE_FRAME); /* * Update the asynchronous state (window size) */ int w; int h; synchronized (this) { // If the user has set a runnable to run in this thread, // execute it and record the amount of time it takes to // run. if (mEvent != null) { profiler.start(ProfileRecorder.PROFILE_SIM); mEvent.run(); profiler.stop(ProfileRecorder.PROFILE_SIM); } if(needToWait()) { while (needToWait()) { try { wait(); } catch (InterruptedException e) { } } } if (mDone) { break; } tellRendererSurfaceChanged = mSizeChanged; w = mWidth; h = mHeight; mSizeChanged = false; } if (tellRendererSurfaceChanged) { mRenderer.sizeChanged(w, h); tellRendererSurfaceChanged = false; } if ((w > 0) && (h > 0)) { // Get ready to draw. // We record both lockCanvas() and unlockCanvasAndPost() // as part of "page flip" time because either may block // until the previous frame is complete. profiler.start(ProfileRecorder.PROFILE_PAGE_FLIP); Canvas canvas = mSurfaceHolder.lockCanvas(); profiler.start(ProfileRecorder.PROFILE_PAGE_FLIP); if (canvas != null) { // Draw a frame! profiler.start(ProfileRecorder.PROFILE_DRAW); mRenderer.drawFrame(canvas); profiler.stop(ProfileRecorder.PROFILE_DRAW); profiler.start(ProfileRecorder.PROFILE_PAGE_FLIP); mSurfaceHolder.unlockCanvasAndPost(canvas); profiler.stop(ProfileRecorder.PROFILE_PAGE_FLIP); } } profiler.stop(ProfileRecorder.PROFILE_FRAME); profiler.endFrame(); } } private boolean needToWait() { return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost) && (! mDone); } public void surfaceCreated() { synchronized(this) { mHasSurface = true; mContextLost = false; notify(); } } public void surfaceDestroyed() { synchronized(this) { mHasSurface = false; notify(); } } public void onPause() { synchronized (this) { mPaused = true; } } public void onResume() { synchronized (this) { mPaused = false; notify(); } } public void onWindowFocusChanged(boolean hasFocus) { synchronized (this) { mHasFocus = hasFocus; if (mHasFocus == true) { notify(); } } } public void onWindowResize(int w, int h) { synchronized (this) { mWidth = w; mHeight = h; mSizeChanged = true; } } public void requestExitAndWait() { // don't call this from CanvasThread thread or it is a guaranteed // deadlock! synchronized(this) { mDone = true; notify(); } try { join(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } /** * Queue an "event" to be run on the rendering thread. * @param r the runnable to be run on the rendering thread. */ public void setEvent(Runnable r) { synchronized(this) { mEvent = r; } } public void clearEvent() { synchronized(this) { mEvent = null; } } } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; /** * Base class defining the core set of information necessary to render (and move * an object on the screen. This is an abstract type and must be derived to * add methods to actually draw (see CanvasSprite and GLSprite). */ public abstract class Renderable { // Position. public float x; public float y; public float z; // Velocity. public float velocityX; public float velocityY; public float velocityZ; // Size. public float width; public float height; }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.util.DisplayMetrics; /** * Activity for testing OpenGL ES drawing speed. This activity sets up sprites * and passes them off to an OpenGLSurfaceView for rendering and movement. */ public class OpenGLTestActivity extends Activity { private final static int SPRITE_WIDTH = 64; private final static int SPRITE_HEIGHT = 64; private GLSurfaceView mGLSurfaceView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mGLSurfaceView = new GLSurfaceView(this); SimpleGLRenderer spriteRenderer = new SimpleGLRenderer(this); // Clear out any old profile results. ProfileRecorder.sSingleton.resetAll(); final Intent callingIntent = getIntent(); // Allocate our sprites and add them to an array. final int robotCount = callingIntent.getIntExtra("spriteCount", 10); final boolean animate = callingIntent.getBooleanExtra("animate", true); final boolean useVerts = callingIntent.getBooleanExtra("useVerts", false); final boolean useHardwareBuffers = callingIntent.getBooleanExtra("useHardwareBuffers", false); // Allocate space for the robot sprites + one background sprite. GLSprite[] spriteArray = new GLSprite[robotCount + 1]; // We need to know the width and height of the display pretty soon, // so grab the information now. DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); GLSprite background = new GLSprite(R.drawable.background); BitmapDrawable backgroundImage = (BitmapDrawable)getResources().getDrawable(R.drawable.background); Bitmap backgoundBitmap = backgroundImage.getBitmap(); background.width = backgoundBitmap.getWidth(); background.height = backgoundBitmap.getHeight(); if (useVerts) { // Setup the background grid. This is just a quad. Grid backgroundGrid = new Grid(2, 2, false); backgroundGrid.set(0, 0, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, null); backgroundGrid.set(1, 0, background.width, 0.0f, 0.0f, 1.0f, 1.0f, null); backgroundGrid.set(0, 1, 0.0f, background.height, 0.0f, 0.0f, 0.0f, null); backgroundGrid.set(1, 1, background.width, background.height, 0.0f, 1.0f, 0.0f, null ); background.setGrid(backgroundGrid); } spriteArray[0] = background; Grid spriteGrid = null; if (useVerts) { // Setup a quad for the sprites to use. All sprites will use the // same sprite grid intance. spriteGrid = new Grid(2, 2, false); spriteGrid.set(0, 0, 0.0f, 0.0f, 0.0f, 0.0f , 1.0f, null); spriteGrid.set(1, 0, SPRITE_WIDTH, 0.0f, 0.0f, 1.0f, 1.0f, null); spriteGrid.set(0, 1, 0.0f, SPRITE_HEIGHT, 0.0f, 0.0f, 0.0f, null); spriteGrid.set(1, 1, SPRITE_WIDTH, SPRITE_HEIGHT, 0.0f, 1.0f, 0.0f, null); } // This list of things to move. It points to the same content as the // sprite list except for the background. Renderable[] renderableArray = new Renderable[robotCount]; final int robotBucketSize = robotCount / 3; for (int x = 0; x < robotCount; x++) { GLSprite robot; // Our robots come in three flavors. Split them up accordingly. if (x < robotBucketSize) { robot = new GLSprite(R.drawable.skate1); } else if (x < robotBucketSize * 2) { robot = new GLSprite(R.drawable.skate2); } else { robot = new GLSprite(R.drawable.skate3); } robot.width = SPRITE_WIDTH; robot.height = SPRITE_HEIGHT; // Pick a random location for this sprite. robot.x = (float)(Math.random() * dm.widthPixels); robot.y = (float)(Math.random() * dm.heightPixels); // All sprites can reuse the same grid. If we're running the // DrawTexture extension test, this is null. robot.setGrid(spriteGrid); // Add this robot to the spriteArray so it gets drawn and to the // renderableArray so that it gets moved. spriteArray[x + 1] = robot; renderableArray[x] = robot; } // Now's a good time to run the GC. Since we won't do any explicit // allocation during the test, the GC should stay dormant and not // influence our results. Runtime r = Runtime.getRuntime(); r.gc(); spriteRenderer.setSprites(spriteArray); spriteRenderer.setVertMode(useVerts, useHardwareBuffers); mGLSurfaceView.setRenderer(spriteRenderer); if (animate) { Mover simulationRuntime = new Mover(); simulationRuntime.setRenderables(renderableArray); simulationRuntime.setViewSize(dm.widthPixels, dm.heightPixels); mGLSurfaceView.setEvent(simulationRuntime); } setContentView(mGLSurfaceView); } }
Java