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;
020import static com.google.common.collect.CollectPreconditions.checkNonnegative;
021import static java.util.Objects.requireNonNull;
022
023import com.google.common.annotations.GwtCompatible;
024import com.google.common.annotations.GwtIncompatible;
025import com.google.common.annotations.J2ktIncompatible;
026import com.google.common.base.MoreObjects;
027import com.google.errorprone.annotations.CanIgnoreReturnValue;
028import com.google.errorprone.annotations.DoNotCall;
029import com.google.errorprone.annotations.concurrent.LazyInit;
030import com.google.j2objc.annotations.RetainedWith;
031import com.google.j2objc.annotations.Weak;
032import java.io.IOException;
033import java.io.InvalidObjectException;
034import java.io.ObjectInputStream;
035import java.io.ObjectOutputStream;
036import java.util.Arrays;
037import java.util.Collection;
038import java.util.Comparator;
039import java.util.Map;
040import java.util.Map.Entry;
041import java.util.Set;
042import java.util.function.Function;
043import java.util.stream.Collector;
044import java.util.stream.Stream;
045import javax.annotation.CheckForNull;
046import org.checkerframework.checker.nullness.qual.Nullable;
047
048/**
049 * A {@link SetMultimap} whose contents will never change, with many other important properties
050 * detailed at {@link ImmutableCollection}.
051 *
052 * <p><b>Warning:</b> As in all {@link SetMultimap}s, do not modify either a key <i>or a value</i>
053 * of a {@code ImmutableSetMultimap} in a way that affects its {@link Object#equals} behavior.
054 * Undefined behavior and bugs will result.
055 *
056 * <p>See the Guava User Guide article on <a href=
057 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>.
058 *
059 * @author Mike Ward
060 * @since 2.0
061 */
062@GwtCompatible(serializable = true, emulated = true)
063@ElementTypesAreNonnullByDefault
064public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V>
065    implements SetMultimap<K, V> {
066  /**
067   * Returns a {@link Collector} that accumulates elements into an {@code ImmutableSetMultimap}
068   * whose keys and values are the result of applying the provided mapping functions to the input
069   * elements.
070   *
071   * <p>For streams with defined encounter order (as defined in the Ordering section of the {@link
072   * java.util.stream} Javadoc), that order is preserved, but entries are <a
073   * href="ImmutableMultimap.html#iteration">grouped by key</a>.
074   *
075   * <p>Example:
076   *
077   * <pre>{@code
078   * static final Multimap<Character, String> FIRST_LETTER_MULTIMAP =
079   *     Stream.of("banana", "apple", "carrot", "asparagus", "cherry")
080   *         .collect(toImmutableSetMultimap(str -> str.charAt(0), str -> str.substring(1)));
081   *
082   * // is equivalent to
083   *
084   * static final Multimap<Character, String> FIRST_LETTER_MULTIMAP =
085   *     new ImmutableSetMultimap.Builder<Character, String>()
086   *         .put('b', "anana")
087   *         .putAll('a', "pple", "sparagus")
088   *         .putAll('c', "arrot", "herry")
089   *         .build();
090   * }</pre>
091   *
092   * @since 21.0
093   */
094  public static <T extends @Nullable Object, K, V>
095      Collector<T, ?, ImmutableSetMultimap<K, V>> toImmutableSetMultimap(
096          Function<? super T, ? extends K> keyFunction,
097          Function<? super T, ? extends V> valueFunction) {
098    return CollectCollectors.toImmutableSetMultimap(keyFunction, valueFunction);
099  }
100
101  /**
102   * Returns a {@code Collector} accumulating entries into an {@code ImmutableSetMultimap}. Each
103   * input element is mapped to a key and a stream of values, each of which are put into the
104   * resulting {@code Multimap}, in the encounter order of the stream and the encounter order of the
105   * streams of values.
106   *
107   * <p>Example:
108   *
109   * <pre>{@code
110   * static final ImmutableSetMultimap<Character, Character> FIRST_LETTER_MULTIMAP =
111   *     Stream.of("banana", "apple", "carrot", "asparagus", "cherry")
112   *         .collect(
113   *             flatteningToImmutableSetMultimap(
114   *                  str -> str.charAt(0),
115   *                  str -> str.substring(1).chars().mapToObj(c -> (char) c));
116   *
117   * // is equivalent to
118   *
119   * static final ImmutableSetMultimap<Character, Character> FIRST_LETTER_MULTIMAP =
120   *     ImmutableSetMultimap.<Character, Character>builder()
121   *         .putAll('b', Arrays.asList('a', 'n', 'a', 'n', 'a'))
122   *         .putAll('a', Arrays.asList('p', 'p', 'l', 'e'))
123   *         .putAll('c', Arrays.asList('a', 'r', 'r', 'o', 't'))
124   *         .putAll('a', Arrays.asList('s', 'p', 'a', 'r', 'a', 'g', 'u', 's'))
125   *         .putAll('c', Arrays.asList('h', 'e', 'r', 'r', 'y'))
126   *         .build();
127   *
128   * // after deduplication, the resulting multimap is equivalent to
129   *
130   * static final ImmutableSetMultimap<Character, Character> FIRST_LETTER_MULTIMAP =
131   *     ImmutableSetMultimap.<Character, Character>builder()
132   *         .putAll('b', Arrays.asList('a', 'n'))
133   *         .putAll('a', Arrays.asList('p', 'l', 'e', 's', 'a', 'r', 'g', 'u'))
134   *         .putAll('c', Arrays.asList('a', 'r', 'o', 't', 'h', 'e', 'y'))
135   *         .build();
136   * }
137   * }</pre>
138   *
139   * @since 21.0
140   */
141  public static <T extends @Nullable Object, K, V>
142      Collector<T, ?, ImmutableSetMultimap<K, V>> flatteningToImmutableSetMultimap(
143          Function<? super T, ? extends K> keyFunction,
144          Function<? super T, ? extends Stream<? extends V>> valuesFunction) {
145    return CollectCollectors.flatteningToImmutableSetMultimap(keyFunction, valuesFunction);
146  }
147
148  /**
149   * Returns the empty multimap.
150   *
151   * <p><b>Performance note:</b> the instance returned is a singleton.
152   */
153  // Casting is safe because the multimap will never hold any elements.
154  @SuppressWarnings("unchecked")
155  public static <K, V> ImmutableSetMultimap<K, V> of() {
156    return (ImmutableSetMultimap<K, V>) EmptyImmutableSetMultimap.INSTANCE;
157  }
158
159  /** Returns an immutable multimap containing a single entry. */
160  public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1) {
161    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
162    builder.put(k1, v1);
163    return builder.build();
164  }
165
166  /**
167   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
168   * an entry (according to {@link Object#equals}) after the first are ignored.
169   */
170  public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2) {
171    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
172    builder.put(k1, v1);
173    builder.put(k2, v2);
174    return builder.build();
175  }
176
177  /**
178   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
179   * an entry (according to {@link Object#equals}) after the first are ignored.
180   */
181  public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
182    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
183    builder.put(k1, v1);
184    builder.put(k2, v2);
185    builder.put(k3, v3);
186    return builder.build();
187  }
188
189  /**
190   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
191   * an entry (according to {@link Object#equals}) after the first are ignored.
192   */
193  public static <K, V> ImmutableSetMultimap<K, V> of(
194      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
195    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
196    builder.put(k1, v1);
197    builder.put(k2, v2);
198    builder.put(k3, v3);
199    builder.put(k4, v4);
200    return builder.build();
201  }
202
203  /**
204   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
205   * an entry (according to {@link Object#equals}) after the first are ignored.
206   */
207  public static <K, V> ImmutableSetMultimap<K, V> of(
208      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
209    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
210    builder.put(k1, v1);
211    builder.put(k2, v2);
212    builder.put(k3, v3);
213    builder.put(k4, v4);
214    builder.put(k5, v5);
215    return builder.build();
216  }
217
218  // looking for of() with > 5 entries? Use the builder instead.
219
220  /** Returns a new {@link Builder}. */
221  public static <K, V> Builder<K, V> builder() {
222    return new Builder<>();
223  }
224
225  /**
226   * Returns a new builder with a hint for how many distinct keys are expected to be added. The
227   * generated builder is equivalent to that returned by {@link #builder}, but may perform better if
228   * {@code expectedKeys} is a good estimate.
229   *
230   * @throws IllegalArgumentException if {@code expectedKeys} is negative
231   * @since 33.3.0
232   */
233  public static <K, V> Builder<K, V> builderWithExpectedKeys(int expectedKeys) {
234    checkNonnegative(expectedKeys, "expectedKeys");
235    return new Builder<>(expectedKeys);
236  }
237
238  /**
239   * A builder for creating immutable {@code SetMultimap} instances, especially {@code public static
240   * final} multimaps ("constant multimaps"). Example:
241   *
242   * <pre>{@code
243   * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
244   *     new ImmutableSetMultimap.Builder<String, Integer>()
245   *         .put("one", 1)
246   *         .putAll("several", 1, 2, 3)
247   *         .putAll("many", 1, 2, 3, 4, 5)
248   *         .build();
249   * }</pre>
250   *
251   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
252   * multiple multimaps in series. Each multimap contains the key-value mappings in the previously
253   * created multimaps.
254   *
255   * @since 2.0
256   */
257  public static final class Builder<K, V> extends ImmutableMultimap.Builder<K, V> {
258    /**
259     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
260     * ImmutableSetMultimap#builder}.
261     */
262    public Builder() {
263      super();
264    }
265
266    Builder(int expectedKeys) {
267      super(expectedKeys);
268    }
269
270    @Override
271    ImmutableCollection.Builder<V> newValueCollectionBuilderWithExpectedSize(int expectedSize) {
272      return (valueComparator == null)
273          ? ImmutableSet.builderWithExpectedSize(expectedSize)
274          : new ImmutableSortedSet.Builder<V>(valueComparator, expectedSize);
275    }
276
277    @Override
278    int expectedValueCollectionSize(int defaultExpectedValues, Iterable<?> values) {
279      // Only trust the size of `values` if it is a Set and therefore probably already deduplicated.
280      if (values instanceof Set<?>) {
281        Set<?> collection = (Set<?>) values;
282        return Math.max(defaultExpectedValues, collection.size());
283      } else {
284        return defaultExpectedValues;
285      }
286    }
287
288    /**
289     * {@inheritDoc}
290     *
291     * <p>Note that {@code expectedValuesPerKey} is taken to mean the expected number of
292     * <i>distinct</i> values per key.
293     *
294     * @since 33.3.0
295     */
296    @CanIgnoreReturnValue
297    @Override
298    public Builder<K, V> expectedValuesPerKey(int expectedValuesPerKey) {
299      super.expectedValuesPerKey(expectedValuesPerKey);
300      return this;
301    }
302
303    /** Adds a key-value mapping to the built multimap if it is not already present. */
304    @CanIgnoreReturnValue
305    @Override
306    public Builder<K, V> put(K key, V value) {
307      super.put(key, value);
308      return this;
309    }
310
311    /**
312     * Adds an entry to the built multimap if it is not already present.
313     *
314     * @since 11.0
315     */
316    @CanIgnoreReturnValue
317    @Override
318    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
319      super.put(entry);
320      return this;
321    }
322
323    /**
324     * {@inheritDoc}
325     *
326     * @since 19.0
327     */
328    @CanIgnoreReturnValue
329    @Override
330    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
331      super.putAll(entries);
332      return this;
333    }
334
335    @CanIgnoreReturnValue
336    @Override
337    public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
338      super.putAll(key, values);
339      return this;
340    }
341
342    @CanIgnoreReturnValue
343    @Override
344    public Builder<K, V> putAll(K key, V... values) {
345      return putAll(key, Arrays.asList(values));
346    }
347
348    @CanIgnoreReturnValue
349    @Override
350    public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) {
351      for (Entry<? extends K, ? extends Collection<? extends V>> entry :
352          multimap.asMap().entrySet()) {
353        putAll(entry.getKey(), entry.getValue());
354      }
355      return this;
356    }
357
358    @CanIgnoreReturnValue
359    @Override
360    Builder<K, V> combine(ImmutableMultimap.Builder<K, V> other) {
361      super.combine(other);
362      return this;
363    }
364
365    /**
366     * {@inheritDoc}
367     *
368     * @since 8.0
369     */
370    @CanIgnoreReturnValue
371    @Override
372    public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
373      super.orderKeysBy(keyComparator);
374      return this;
375    }
376
377    /**
378     * Specifies the ordering of the generated multimap's values for each key.
379     *
380     * <p>If this method is called, the sets returned by the {@code get()} method of the generated
381     * multimap and its {@link Multimap#asMap()} view are {@link ImmutableSortedSet} instances.
382     * However, serialization does not preserve that property, though it does maintain the key and
383     * value ordering.
384     *
385     * @since 8.0
386     */
387    // TODO: Make serialization behavior consistent.
388    @CanIgnoreReturnValue
389    @Override
390    public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
391      super.orderValuesBy(valueComparator);
392      return this;
393    }
394
395    /** Returns a newly-created immutable set multimap. */
396    @Override
397    public ImmutableSetMultimap<K, V> build() {
398      if (builderMap == null) {
399        return ImmutableSetMultimap.of();
400      }
401      Collection<Map.Entry<K, ImmutableCollection.Builder<V>>> mapEntries = builderMap.entrySet();
402      if (keyComparator != null) {
403        mapEntries = Ordering.from(keyComparator).<K>onKeys().immutableSortedCopy(mapEntries);
404      }
405      return fromMapBuilderEntries(mapEntries, valueComparator);
406    }
407  }
408
409  /**
410   * Returns an immutable set multimap containing the same mappings as {@code multimap}. The
411   * generated multimap's key and value orderings correspond to the iteration ordering of the {@code
412   * multimap.asMap()} view. Repeated occurrences of an entry in the multimap after the first are
413   * ignored.
414   *
415   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
416   * safe to do so. The exact circumstances under which a copy will or will not be performed are
417   * undocumented and subject to change.
418   *
419   * @throws NullPointerException if any key or value in {@code multimap} is null
420   */
421  public static <K, V> ImmutableSetMultimap<K, V> copyOf(
422      Multimap<? extends K, ? extends V> multimap) {
423    return copyOf(multimap, null);
424  }
425
426  private static <K, V> ImmutableSetMultimap<K, V> copyOf(
427      Multimap<? extends K, ? extends V> multimap,
428      @CheckForNull Comparator<? super V> valueComparator) {
429    checkNotNull(multimap); // eager for GWT
430    if (multimap.isEmpty() && valueComparator == null) {
431      return of();
432    }
433
434    if (multimap instanceof ImmutableSetMultimap) {
435      @SuppressWarnings("unchecked") // safe since multimap is not writable
436      ImmutableSetMultimap<K, V> kvMultimap = (ImmutableSetMultimap<K, V>) multimap;
437      if (!kvMultimap.isPartialView()) {
438        return kvMultimap;
439      }
440    }
441
442    return fromMapEntries(multimap.asMap().entrySet(), valueComparator);
443  }
444
445  /**
446   * Returns an immutable multimap containing the specified entries. The returned multimap iterates
447   * over keys in the order they were first encountered in the input, and the values for each key
448   * are iterated in the order they were encountered. If two values for the same key are {@linkplain
449   * Object#equals equal}, the first value encountered is used.
450   *
451   * @throws NullPointerException if any key, value, or entry is null
452   * @since 19.0
453   */
454  public static <K, V> ImmutableSetMultimap<K, V> copyOf(
455      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
456    return new Builder<K, V>().putAll(entries).build();
457  }
458
459  /** Creates an ImmutableSetMultimap from an asMap.entrySet. */
460  static <K, V> ImmutableSetMultimap<K, V> fromMapEntries(
461      Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries,
462      @CheckForNull Comparator<? super V> valueComparator) {
463    if (mapEntries.isEmpty()) {
464      return of();
465    }
466    ImmutableMap.Builder<K, ImmutableSet<V>> builder =
467        new ImmutableMap.Builder<>(mapEntries.size());
468    int size = 0;
469
470    for (Entry<? extends K, ? extends Collection<? extends V>> entry : mapEntries) {
471      K key = entry.getKey();
472      Collection<? extends V> values = entry.getValue();
473      ImmutableSet<V> set = valueSet(valueComparator, values);
474      if (!set.isEmpty()) {
475        builder.put(key, set);
476        size += set.size();
477      }
478    }
479
480    return new ImmutableSetMultimap<>(builder.buildOrThrow(), size, valueComparator);
481  }
482
483  /** Creates an ImmutableSetMultimap from a map to builders. */
484  static <K, V> ImmutableSetMultimap<K, V> fromMapBuilderEntries(
485      Collection<? extends Map.Entry<K, ImmutableCollection.Builder<V>>> mapEntries,
486      @CheckForNull Comparator<? super V> valueComparator) {
487    if (mapEntries.isEmpty()) {
488      return of();
489    }
490    ImmutableMap.Builder<K, ImmutableSet<V>> builder =
491        new ImmutableMap.Builder<>(mapEntries.size());
492    int size = 0;
493
494    for (Entry<K, ImmutableCollection.Builder<V>> entry : mapEntries) {
495      K key = entry.getKey();
496      ImmutableSet.Builder<? extends V> values = (ImmutableSet.Builder<V>) entry.getValue();
497      // If orderValuesBy got called at the very end, we may need to do the ImmutableSet to
498      // ImmutableSortedSet copy for each of these.
499      ImmutableSet<V> set = valueSet(valueComparator, values.build());
500      if (!set.isEmpty()) {
501        builder.put(key, set);
502        size += set.size();
503      }
504    }
505
506    return new ImmutableSetMultimap<>(builder.buildOrThrow(), size, valueComparator);
507  }
508
509  /**
510   * Returned by get() when a missing key is provided. Also holds the comparator, if any, used for
511   * values.
512   */
513  private final transient ImmutableSet<V> emptySet;
514
515  ImmutableSetMultimap(
516      ImmutableMap<K, ImmutableSet<V>> map,
517      int size,
518      @CheckForNull Comparator<? super V> valueComparator) {
519    super(map, size);
520    this.emptySet = emptySet(valueComparator);
521  }
522
523  // views
524
525  /**
526   * Returns an immutable set of the values for the given key. If no mappings in the multimap have
527   * the provided key, an empty immutable set is returned. The values are in the same order as the
528   * parameters used to build this multimap.
529   */
530  @Override
531  public ImmutableSet<V> get(K key) {
532    // This cast is safe as its type is known in constructor.
533    ImmutableSet<V> set = (ImmutableSet<V>) map.get(key);
534    return MoreObjects.firstNonNull(set, emptySet);
535  }
536
537  @LazyInit @RetainedWith @CheckForNull private transient ImmutableSetMultimap<V, K> inverse;
538
539  /**
540   * {@inheritDoc}
541   *
542   * <p>Because an inverse of a set multimap cannot contain multiple pairs with the same key and
543   * value, this method returns an {@code ImmutableSetMultimap} rather than the {@code
544   * ImmutableMultimap} specified in the {@code ImmutableMultimap} class.
545   */
546  @Override
547  public ImmutableSetMultimap<V, K> inverse() {
548    ImmutableSetMultimap<V, K> result = inverse;
549    return (result == null) ? (inverse = invert()) : result;
550  }
551
552  private ImmutableSetMultimap<V, K> invert() {
553    Builder<V, K> builder = builder();
554    for (Entry<K, V> entry : entries()) {
555      builder.put(entry.getValue(), entry.getKey());
556    }
557    ImmutableSetMultimap<V, K> invertedMultimap = builder.build();
558    invertedMultimap.inverse = this;
559    return invertedMultimap;
560  }
561
562  /**
563   * Guaranteed to throw an exception and leave the multimap unmodified.
564   *
565   * @throws UnsupportedOperationException always
566   * @deprecated Unsupported operation.
567   */
568  @CanIgnoreReturnValue
569  @Deprecated
570  @Override
571  @DoNotCall("Always throws UnsupportedOperationException")
572  public final ImmutableSet<V> removeAll(@CheckForNull Object key) {
573    throw new UnsupportedOperationException();
574  }
575
576  /**
577   * Guaranteed to throw an exception and leave the multimap unmodified.
578   *
579   * @throws UnsupportedOperationException always
580   * @deprecated Unsupported operation.
581   */
582  @CanIgnoreReturnValue
583  @Deprecated
584  @Override
585  @DoNotCall("Always throws UnsupportedOperationException")
586  public final ImmutableSet<V> replaceValues(K key, Iterable<? extends V> values) {
587    throw new UnsupportedOperationException();
588  }
589
590  @LazyInit @RetainedWith @CheckForNull private transient ImmutableSet<Entry<K, V>> entries;
591
592  /**
593   * Returns an immutable collection of all key-value pairs in the multimap. Its iterator traverses
594   * the values for the first key, the values for the second key, and so on.
595   */
596  @Override
597  public ImmutableSet<Entry<K, V>> entries() {
598    ImmutableSet<Entry<K, V>> result = entries;
599    return result == null ? (entries = new EntrySet<>(this)) : result;
600  }
601
602  private static final class EntrySet<K, V> extends ImmutableSet<Entry<K, V>> {
603    @Weak private final transient ImmutableSetMultimap<K, V> multimap;
604
605    EntrySet(ImmutableSetMultimap<K, V> multimap) {
606      this.multimap = multimap;
607    }
608
609    @Override
610    public boolean contains(@CheckForNull Object object) {
611      if (object instanceof Entry) {
612        Entry<?, ?> entry = (Entry<?, ?>) object;
613        return multimap.containsEntry(entry.getKey(), entry.getValue());
614      }
615      return false;
616    }
617
618    @Override
619    public int size() {
620      return multimap.size();
621    }
622
623    @Override
624    public UnmodifiableIterator<Entry<K, V>> iterator() {
625      return multimap.entryIterator();
626    }
627
628    @Override
629    boolean isPartialView() {
630      return false;
631    }
632
633    // redeclare to help optimizers with b/310253115
634    @SuppressWarnings("RedundantOverride")
635    @Override
636    @J2ktIncompatible // serialization
637    @GwtIncompatible // serialization
638    Object writeReplace() {
639      return super.writeReplace();
640    }
641  }
642
643  private static <V> ImmutableSet<V> valueSet(
644      @CheckForNull Comparator<? super V> valueComparator, Collection<? extends V> values) {
645    return (valueComparator == null)
646        ? ImmutableSet.copyOf(values)
647        : ImmutableSortedSet.copyOf(valueComparator, values);
648  }
649
650  private static <V> ImmutableSet<V> emptySet(@CheckForNull Comparator<? super V> valueComparator) {
651    return (valueComparator == null)
652        ? ImmutableSet.<V>of()
653        : ImmutableSortedSet.<V>emptySet(valueComparator);
654  }
655
656  private static <V> ImmutableSet.Builder<V> valuesBuilder(
657      @CheckForNull Comparator<? super V> valueComparator) {
658    return (valueComparator == null)
659        ? new ImmutableSet.Builder<V>()
660        : new ImmutableSortedSet.Builder<V>(valueComparator);
661  }
662
663  /**
664   * @serialData number of distinct keys, and then for each distinct key: the key, the number of
665   *     values for that key, and the key's values
666   */
667  @GwtIncompatible // java.io.ObjectOutputStream
668  @J2ktIncompatible
669  private void writeObject(ObjectOutputStream stream) throws IOException {
670    stream.defaultWriteObject();
671    stream.writeObject(valueComparator());
672    Serialization.writeMultimap(this, stream);
673  }
674
675  @CheckForNull
676  Comparator<? super V> valueComparator() {
677    return emptySet instanceof ImmutableSortedSet
678        ? ((ImmutableSortedSet<V>) emptySet).comparator()
679        : null;
680  }
681
682  @GwtIncompatible // java serialization
683  @J2ktIncompatible
684  private static final class SetFieldSettersHolder {
685    static final Serialization.FieldSetter<? super ImmutableSetMultimap<?, ?>>
686        EMPTY_SET_FIELD_SETTER =
687            Serialization.getFieldSetter(ImmutableSetMultimap.class, "emptySet");
688  }
689
690  @GwtIncompatible // java.io.ObjectInputStream
691  @J2ktIncompatible
692  // Serialization type safety is at the caller's mercy.
693  @SuppressWarnings("unchecked")
694  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
695    stream.defaultReadObject();
696    Comparator<Object> valueComparator = (Comparator<Object>) stream.readObject();
697    int keyCount = stream.readInt();
698    if (keyCount < 0) {
699      throw new InvalidObjectException("Invalid key count " + keyCount);
700    }
701    ImmutableMap.Builder<Object, ImmutableSet<Object>> builder = ImmutableMap.builder();
702    int tmpSize = 0;
703
704    for (int i = 0; i < keyCount; i++) {
705      Object key = requireNonNull(stream.readObject());
706      int valueCount = stream.readInt();
707      if (valueCount <= 0) {
708        throw new InvalidObjectException("Invalid value count " + valueCount);
709      }
710
711      ImmutableSet.Builder<Object> valuesBuilder = valuesBuilder(valueComparator);
712      for (int j = 0; j < valueCount; j++) {
713        valuesBuilder.add(requireNonNull(stream.readObject()));
714      }
715      ImmutableSet<Object> valueSet = valuesBuilder.build();
716      if (valueSet.size() != valueCount) {
717        throw new InvalidObjectException("Duplicate key-value pairs exist for key " + key);
718      }
719      builder.put(key, valueSet);
720      tmpSize += valueCount;
721    }
722
723    ImmutableMap<Object, ImmutableSet<Object>> tmpMap;
724    try {
725      tmpMap = builder.buildOrThrow();
726    } catch (IllegalArgumentException e) {
727      throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
728    }
729
730    FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap);
731    FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize);
732    SetFieldSettersHolder.EMPTY_SET_FIELD_SETTER.set(this, emptySet(valueComparator));
733  }
734
735  @GwtIncompatible // not needed in emulated source.
736  @J2ktIncompatible
737  private static final long serialVersionUID = 0;
738}