001/*
002 * Copyright (C) 2009 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkNotNull;
020
021import com.google.common.annotations.Beta;
022import com.google.common.annotations.GwtCompatible;
023import com.google.common.annotations.GwtIncompatible;
024import com.google.common.base.MoreObjects;
025import com.google.errorprone.annotations.CanIgnoreReturnValue;
026import com.google.errorprone.annotations.concurrent.LazyInit;
027import com.google.j2objc.annotations.RetainedWith;
028import com.google.j2objc.annotations.Weak;
029import java.io.IOException;
030import java.io.InvalidObjectException;
031import java.io.ObjectInputStream;
032import java.io.ObjectOutputStream;
033import java.util.Arrays;
034import java.util.Collection;
035import java.util.Comparator;
036import java.util.Map;
037import java.util.Map.Entry;
038import org.checkerframework.checker.nullness.compatqual.MonotonicNonNullDecl;
039import org.checkerframework.checker.nullness.compatqual.NullableDecl;
040
041/**
042 * A {@link SetMultimap} whose contents will never change, with many other important properties
043 * detailed at {@link ImmutableCollection}.
044 *
045 * <p>See the Guava User Guide article on <a href=
046 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained"> immutable collections</a>.
047 *
048 * @author Mike Ward
049 * @since 2.0
050 */
051@GwtCompatible(serializable = true, emulated = true)
052public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V>
053    implements SetMultimap<K, V> {
054
055  /** Returns the empty multimap. */
056  // Casting is safe because the multimap will never hold any elements.
057  @SuppressWarnings("unchecked")
058  public static <K, V> ImmutableSetMultimap<K, V> of() {
059    return (ImmutableSetMultimap<K, V>) EmptyImmutableSetMultimap.INSTANCE;
060  }
061
062  /** Returns an immutable multimap containing a single entry. */
063  public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1) {
064    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
065    builder.put(k1, v1);
066    return builder.build();
067  }
068
069  /**
070   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
071   * an entry (according to {@link Object#equals}) after the first are ignored.
072   */
073  public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2) {
074    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
075    builder.put(k1, v1);
076    builder.put(k2, v2);
077    return builder.build();
078  }
079
080  /**
081   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
082   * an entry (according to {@link Object#equals}) after the first are ignored.
083   */
084  public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
085    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
086    builder.put(k1, v1);
087    builder.put(k2, v2);
088    builder.put(k3, v3);
089    return builder.build();
090  }
091
092  /**
093   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
094   * an entry (according to {@link Object#equals}) after the first are ignored.
095   */
096  public static <K, V> ImmutableSetMultimap<K, V> of(
097      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
098    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
099    builder.put(k1, v1);
100    builder.put(k2, v2);
101    builder.put(k3, v3);
102    builder.put(k4, v4);
103    return builder.build();
104  }
105
106  /**
107   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
108   * an entry (according to {@link Object#equals}) after the first are ignored.
109   */
110  public static <K, V> ImmutableSetMultimap<K, V> of(
111      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
112    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
113    builder.put(k1, v1);
114    builder.put(k2, v2);
115    builder.put(k3, v3);
116    builder.put(k4, v4);
117    builder.put(k5, v5);
118    return builder.build();
119  }
120
121  // looking for of() with > 5 entries? Use the builder instead.
122
123  /** Returns a new {@link Builder}. */
124  public static <K, V> Builder<K, V> builder() {
125    return new Builder<>();
126  }
127
128  /**
129   * A builder for creating immutable {@code SetMultimap} instances, especially {@code public static
130   * final} multimaps ("constant multimaps"). Example:
131   *
132   * <pre>{@code
133   * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
134   *     new ImmutableSetMultimap.Builder<String, Integer>()
135   *         .put("one", 1)
136   *         .putAll("several", 1, 2, 3)
137   *         .putAll("many", 1, 2, 3, 4, 5)
138   *         .build();
139   * }</pre>
140   *
141   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
142   * multiple multimaps in series. Each multimap contains the key-value mappings in the previously
143   * created multimaps.
144   *
145   * @since 2.0
146   */
147  public static final class Builder<K, V> extends ImmutableMultimap.Builder<K, V> {
148    /**
149     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
150     * ImmutableSetMultimap#builder}.
151     */
152    public Builder() {
153      super();
154    }
155
156    @Override
157    Collection<V> newMutableValueCollection() {
158      return Platform.preservesInsertionOrderOnAddsSet();
159    }
160
161    /** Adds a key-value mapping to the built multimap if it is not already present. */
162    @CanIgnoreReturnValue
163    @Override
164    public Builder<K, V> put(K key, V value) {
165      super.put(key, value);
166      return this;
167    }
168
169    /**
170     * Adds an entry to the built multimap if it is not already present.
171     *
172     * @since 11.0
173     */
174    @CanIgnoreReturnValue
175    @Override
176    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
177      super.put(entry);
178      return this;
179    }
180
181    /**
182     * {@inheritDoc}
183     *
184     * @since 19.0
185     */
186    @CanIgnoreReturnValue
187    @Beta
188    @Override
189    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
190      super.putAll(entries);
191      return this;
192    }
193
194    @CanIgnoreReturnValue
195    @Override
196    public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
197      super.putAll(key, values);
198      return this;
199    }
200
201    @CanIgnoreReturnValue
202    @Override
203    public Builder<K, V> putAll(K key, V... values) {
204      return putAll(key, Arrays.asList(values));
205    }
206
207    @CanIgnoreReturnValue
208    @Override
209    public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) {
210      for (Entry<? extends K, ? extends Collection<? extends V>> entry :
211          multimap.asMap().entrySet()) {
212        putAll(entry.getKey(), entry.getValue());
213      }
214      return this;
215    }
216
217    /**
218     * {@inheritDoc}
219     *
220     * @since 8.0
221     */
222    @CanIgnoreReturnValue
223    @Override
224    public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
225      super.orderKeysBy(keyComparator);
226      return this;
227    }
228
229    /**
230     * Specifies the ordering of the generated multimap's values for each key.
231     *
232     * <p>If this method is called, the sets returned by the {@code get()} method of the generated
233     * multimap and its {@link Multimap#asMap()} view are {@link ImmutableSortedSet} instances.
234     * However, serialization does not preserve that property, though it does maintain the key and
235     * value ordering.
236     *
237     * @since 8.0
238     */
239    // TODO: Make serialization behavior consistent.
240    @CanIgnoreReturnValue
241    @Override
242    public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
243      super.orderValuesBy(valueComparator);
244      return this;
245    }
246
247    /** Returns a newly-created immutable set multimap. */
248    @Override
249    public ImmutableSetMultimap<K, V> build() {
250      Collection<Map.Entry<K, Collection<V>>> mapEntries = builderMap.entrySet();
251      if (keyComparator != null) {
252        mapEntries = Ordering.from(keyComparator).<K>onKeys().immutableSortedCopy(mapEntries);
253      }
254      return fromMapEntries(mapEntries, valueComparator);
255    }
256  }
257
258  /**
259   * Returns an immutable set multimap containing the same mappings as {@code multimap}. The
260   * generated multimap's key and value orderings correspond to the iteration ordering of the {@code
261   * multimap.asMap()} view. Repeated occurrences of an entry in the multimap after the first are
262   * ignored.
263   *
264   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
265   * safe to do so. The exact circumstances under which a copy will or will not be performed are
266   * undocumented and subject to change.
267   *
268   * @throws NullPointerException if any key or value in {@code multimap} is null
269   */
270  public static <K, V> ImmutableSetMultimap<K, V> copyOf(
271      Multimap<? extends K, ? extends V> multimap) {
272    return copyOf(multimap, null);
273  }
274
275  private static <K, V> ImmutableSetMultimap<K, V> copyOf(
276      Multimap<? extends K, ? extends V> multimap, Comparator<? super V> valueComparator) {
277    checkNotNull(multimap); // eager for GWT
278    if (multimap.isEmpty() && valueComparator == null) {
279      return of();
280    }
281
282    if (multimap instanceof ImmutableSetMultimap) {
283      @SuppressWarnings("unchecked") // safe since multimap is not writable
284      ImmutableSetMultimap<K, V> kvMultimap = (ImmutableSetMultimap<K, V>) multimap;
285      if (!kvMultimap.isPartialView()) {
286        return kvMultimap;
287      }
288    }
289
290    return fromMapEntries(multimap.asMap().entrySet(), valueComparator);
291  }
292
293  /**
294   * Returns an immutable multimap containing the specified entries. The returned multimap iterates
295   * over keys in the order they were first encountered in the input, and the values for each key
296   * are iterated in the order they were encountered. If two values for the same key are {@linkplain
297   * Object#equals equal}, the first value encountered is used.
298   *
299   * @throws NullPointerException if any key, value, or entry is null
300   * @since 19.0
301   */
302  @Beta
303  public static <K, V> ImmutableSetMultimap<K, V> copyOf(
304      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
305    return new Builder<K, V>().putAll(entries).build();
306  }
307
308  /** Creates an ImmutableSetMultimap from an asMap.entrySet. */
309  static <K, V> ImmutableSetMultimap<K, V> fromMapEntries(
310      Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries,
311      @NullableDecl Comparator<? super V> valueComparator) {
312    if (mapEntries.isEmpty()) {
313      return of();
314    }
315    ImmutableMap.Builder<K, ImmutableSet<V>> builder =
316        new ImmutableMap.Builder<>(mapEntries.size());
317    int size = 0;
318
319    for (Entry<? extends K, ? extends Collection<? extends V>> entry : mapEntries) {
320      K key = entry.getKey();
321      Collection<? extends V> values = entry.getValue();
322      ImmutableSet<V> set = valueSet(valueComparator, values);
323      if (!set.isEmpty()) {
324        builder.put(key, set);
325        size += set.size();
326      }
327    }
328
329    return new ImmutableSetMultimap<>(builder.build(), size, valueComparator);
330  }
331
332  /**
333   * Returned by get() when a missing key is provided. Also holds the comparator, if any, used for
334   * values.
335   */
336  private final transient ImmutableSet<V> emptySet;
337
338  ImmutableSetMultimap(
339      ImmutableMap<K, ImmutableSet<V>> map,
340      int size,
341      @NullableDecl Comparator<? super V> valueComparator) {
342    super(map, size);
343    this.emptySet = emptySet(valueComparator);
344  }
345
346  // views
347
348  /**
349   * Returns an immutable set of the values for the given key. If no mappings in the multimap have
350   * the provided key, an empty immutable set is returned. The values are in the same order as the
351   * parameters used to build this multimap.
352   */
353  @Override
354  public ImmutableSet<V> get(@NullableDecl K key) {
355    // This cast is safe as its type is known in constructor.
356    ImmutableSet<V> set = (ImmutableSet<V>) map.get(key);
357    return MoreObjects.firstNonNull(set, emptySet);
358  }
359
360  @LazyInit @MonotonicNonNullDecl @RetainedWith
361  private transient ImmutableSetMultimap<V, K> inverse;
362
363  /**
364   * {@inheritDoc}
365   *
366   * <p>Because an inverse of a set multimap cannot contain multiple pairs with the same key and
367   * value, this method returns an {@code ImmutableSetMultimap} rather than the {@code
368   * ImmutableMultimap} specified in the {@code ImmutableMultimap} class.
369   */
370  @Override
371  public ImmutableSetMultimap<V, K> inverse() {
372    ImmutableSetMultimap<V, K> result = inverse;
373    return (result == null) ? (inverse = invert()) : result;
374  }
375
376  private ImmutableSetMultimap<V, K> invert() {
377    Builder<V, K> builder = builder();
378    for (Entry<K, V> entry : entries()) {
379      builder.put(entry.getValue(), entry.getKey());
380    }
381    ImmutableSetMultimap<V, K> invertedMultimap = builder.build();
382    invertedMultimap.inverse = this;
383    return invertedMultimap;
384  }
385
386  /**
387   * Guaranteed to throw an exception and leave the multimap unmodified.
388   *
389   * @throws UnsupportedOperationException always
390   * @deprecated Unsupported operation.
391   */
392  @CanIgnoreReturnValue
393  @Deprecated
394  @Override
395  public ImmutableSet<V> removeAll(Object key) {
396    throw new UnsupportedOperationException();
397  }
398
399  /**
400   * Guaranteed to throw an exception and leave the multimap unmodified.
401   *
402   * @throws UnsupportedOperationException always
403   * @deprecated Unsupported operation.
404   */
405  @CanIgnoreReturnValue
406  @Deprecated
407  @Override
408  public ImmutableSet<V> replaceValues(K key, Iterable<? extends V> values) {
409    throw new UnsupportedOperationException();
410  }
411
412  @MonotonicNonNullDecl private transient ImmutableSet<Entry<K, V>> entries;
413
414  /**
415   * Returns an immutable collection of all key-value pairs in the multimap. Its iterator traverses
416   * the values for the first key, the values for the second key, and so on.
417   */
418  @Override
419  public ImmutableSet<Entry<K, V>> entries() {
420    ImmutableSet<Entry<K, V>> result = entries;
421    return result == null ? (entries = new EntrySet<>(this)) : result;
422  }
423
424  private static final class EntrySet<K, V> extends ImmutableSet<Entry<K, V>> {
425    @Weak private final transient ImmutableSetMultimap<K, V> multimap;
426
427    EntrySet(ImmutableSetMultimap<K, V> multimap) {
428      this.multimap = multimap;
429    }
430
431    @Override
432    public boolean contains(@NullableDecl Object object) {
433      if (object instanceof Entry) {
434        Entry<?, ?> entry = (Entry<?, ?>) object;
435        return multimap.containsEntry(entry.getKey(), entry.getValue());
436      }
437      return false;
438    }
439
440    @Override
441    public int size() {
442      return multimap.size();
443    }
444
445    @Override
446    public UnmodifiableIterator<Entry<K, V>> iterator() {
447      return multimap.entryIterator();
448    }
449
450    @Override
451    boolean isPartialView() {
452      return false;
453    }
454  }
455
456  private static <V> ImmutableSet<V> valueSet(
457      @NullableDecl Comparator<? super V> valueComparator, Collection<? extends V> values) {
458    return (valueComparator == null)
459        ? ImmutableSet.copyOf(values)
460        : ImmutableSortedSet.copyOf(valueComparator, values);
461  }
462
463  private static <V> ImmutableSet<V> emptySet(@NullableDecl Comparator<? super V> valueComparator) {
464    return (valueComparator == null)
465        ? ImmutableSet.<V>of()
466        : ImmutableSortedSet.<V>emptySet(valueComparator);
467  }
468
469  private static <V> ImmutableSet.Builder<V> valuesBuilder(
470      @NullableDecl Comparator<? super V> valueComparator) {
471    return (valueComparator == null)
472        ? new ImmutableSet.Builder<V>()
473        : new ImmutableSortedSet.Builder<V>(valueComparator);
474  }
475
476  /**
477   * @serialData number of distinct keys, and then for each distinct key: the key, the number of
478   *     values for that key, and the key's values
479   */
480  @GwtIncompatible // java.io.ObjectOutputStream
481  private void writeObject(ObjectOutputStream stream) throws IOException {
482    stream.defaultWriteObject();
483    stream.writeObject(valueComparator());
484    Serialization.writeMultimap(this, stream);
485  }
486
487  @NullableDecl
488  Comparator<? super V> valueComparator() {
489    return emptySet instanceof ImmutableSortedSet
490        ? ((ImmutableSortedSet<V>) emptySet).comparator()
491        : null;
492  }
493
494  @GwtIncompatible // java serialization
495  private static final class SetFieldSettersHolder {
496    static final Serialization.FieldSetter<ImmutableSetMultimap> EMPTY_SET_FIELD_SETTER =
497        Serialization.getFieldSetter(ImmutableSetMultimap.class, "emptySet");
498  }
499
500  @GwtIncompatible // java.io.ObjectInputStream
501  // Serialization type safety is at the caller's mercy.
502  @SuppressWarnings("unchecked")
503  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
504    stream.defaultReadObject();
505    Comparator<Object> valueComparator = (Comparator<Object>) stream.readObject();
506    int keyCount = stream.readInt();
507    if (keyCount < 0) {
508      throw new InvalidObjectException("Invalid key count " + keyCount);
509    }
510    ImmutableMap.Builder<Object, ImmutableSet<Object>> builder = ImmutableMap.builder();
511    int tmpSize = 0;
512
513    for (int i = 0; i < keyCount; i++) {
514      Object key = stream.readObject();
515      int valueCount = stream.readInt();
516      if (valueCount <= 0) {
517        throw new InvalidObjectException("Invalid value count " + valueCount);
518      }
519
520      ImmutableSet.Builder<Object> valuesBuilder = valuesBuilder(valueComparator);
521      for (int j = 0; j < valueCount; j++) {
522        valuesBuilder.add(stream.readObject());
523      }
524      ImmutableSet<Object> valueSet = valuesBuilder.build();
525      if (valueSet.size() != valueCount) {
526        throw new InvalidObjectException("Duplicate key-value pairs exist for key " + key);
527      }
528      builder.put(key, valueSet);
529      tmpSize += valueCount;
530    }
531
532    ImmutableMap<Object, ImmutableSet<Object>> tmpMap;
533    try {
534      tmpMap = builder.build();
535    } catch (IllegalArgumentException e) {
536      throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
537    }
538
539    FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap);
540    FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize);
541    SetFieldSettersHolder.EMPTY_SET_FIELD_SETTER.set(this, emptySet(valueComparator));
542  }
543
544  @GwtIncompatible // not needed in emulated source.
545  private static final long serialVersionUID = 0;
546}