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