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 java.io.IOException;
034import java.io.InvalidObjectException;
035import java.io.ObjectInputStream;
036import java.io.ObjectOutputStream;
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 org.jspecify.annotations.Nullable;
046
047/**
048 * A {@link SetMultimap} whose contents will never change, with many other important properties
049 * detailed at {@link ImmutableCollection}.
050 *
051 * <p><b>Warning:</b> As in all {@link SetMultimap}s, do not modify either a key <i>or a value</i>
052 * of a {@code ImmutableSetMultimap} in a way that affects its {@link Object#equals} behavior.
053 * Undefined behavior and bugs will result.
054 *
055 * <p>See the Guava User Guide article on <a href=
056 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>.
057 *
058 * @author Mike Ward
059 * @since 2.0
060 */
061@SuppressWarnings("TooManyParameters")
062@GwtCompatible
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   * {@snippet :
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   * }
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   * {@snippet :
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   *
137   * }
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 = 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 = 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 = 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 = 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 = 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   * {@snippet :
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   * }
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
264    Builder(int expectedKeys) {
265      super(expectedKeys);
266    }
267
268    @Override
269    ImmutableCollection.Builder<V> newValueCollectionBuilderWithExpectedSize(int expectedSize) {
270      return (valueComparator == null)
271          ? ImmutableSet.builderWithExpectedSize(expectedSize)
272          : new ImmutableSortedSet.Builder<V>(valueComparator, expectedSize);
273    }
274
275    @Override
276    int expectedValueCollectionSize(int defaultExpectedValues, Iterable<?> values) {
277      // Only trust the size of `values` if it is a Set and therefore probably already deduplicated.
278      if (values instanceof Set<?>) {
279        Set<?> collection = (Set<?>) values;
280        return max(defaultExpectedValues, collection.size());
281      } else {
282        return defaultExpectedValues;
283      }
284    }
285
286    /**
287     * {@inheritDoc}
288     *
289     * <p>Note that {@code expectedValuesPerKey} is taken to mean the expected number of
290     * <i>distinct</i> values per key.
291     *
292     * @since 33.3.0
293     */
294    @CanIgnoreReturnValue
295    @Override
296    public Builder<K, V> expectedValuesPerKey(int expectedValuesPerKey) {
297      super.expectedValuesPerKey(expectedValuesPerKey);
298      return this;
299    }
300
301    /** Adds a key-value mapping to the built multimap if it is not already present. */
302    @CanIgnoreReturnValue
303    @Override
304    public Builder<K, V> put(K key, V value) {
305      super.put(key, value);
306      return this;
307    }
308
309    /**
310     * Adds an entry to the built multimap if it is not already present.
311     *
312     * @since 11.0
313     */
314    @CanIgnoreReturnValue
315    @Override
316    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
317      super.put(entry);
318      return this;
319    }
320
321    /**
322     * {@inheritDoc}
323     *
324     * @since 19.0
325     */
326    @CanIgnoreReturnValue
327    @Override
328    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
329      super.putAll(entries);
330      return this;
331    }
332
333    @CanIgnoreReturnValue
334    @Override
335    public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
336      super.putAll(key, values);
337      return this;
338    }
339
340    @CanIgnoreReturnValue
341    @Override
342    public Builder<K, V> putAll(K key, V... values) {
343      return putAll(key, asList(values));
344    }
345
346    @CanIgnoreReturnValue
347    @Override
348    public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) {
349      for (Entry<? extends K, ? extends Collection<? extends V>> entry :
350          multimap.asMap().entrySet()) {
351        putAll(entry.getKey(), entry.getValue());
352      }
353      return this;
354    }
355
356    @CanIgnoreReturnValue
357    @Override
358    Builder<K, V> combine(ImmutableMultimap.Builder<K, V> other) {
359      super.combine(other);
360      return this;
361    }
362
363    /**
364     * {@inheritDoc}
365     *
366     * @since 8.0
367     */
368    @CanIgnoreReturnValue
369    @Override
370    public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
371      super.orderKeysBy(keyComparator);
372      return this;
373    }
374
375    /**
376     * Specifies the ordering of the generated multimap's values for each key.
377     *
378     * <p>If this method is called, the sets returned by the {@code get()} method of the generated
379     * multimap and its {@link Multimap#asMap()} view are {@link ImmutableSortedSet} instances.
380     * However, serialization does not preserve that property, though it does maintain the key and
381     * value ordering.
382     *
383     * @since 8.0
384     */
385    // TODO: Make serialization behavior consistent.
386    @CanIgnoreReturnValue
387    @Override
388    public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
389      super.orderValuesBy(valueComparator);
390      return this;
391    }
392
393    /** Returns a newly-created immutable set multimap. */
394    @Override
395    public ImmutableSetMultimap<K, V> build() {
396      if (builderMap == null) {
397        return of();
398      }
399      Collection<Map.Entry<K, ImmutableCollection.Builder<V>>> mapEntries = builderMap.entrySet();
400      if (keyComparator != null) {
401        mapEntries = Ordering.from(keyComparator).<K>onKeys().immutableSortedCopy(mapEntries);
402      }
403      return fromMapBuilderEntries(mapEntries, valueComparator);
404    }
405  }
406
407  /**
408   * Returns an immutable set multimap containing the same mappings as {@code multimap}. The
409   * generated multimap's key and value orderings correspond to the iteration ordering of the {@code
410   * multimap.asMap()} view. Repeated occurrences of an entry in the multimap after the first are
411   * ignored.
412   *
413   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
414   * safe to do so. The exact circumstances under which a copy will or will not be performed are
415   * undocumented and subject to change.
416   *
417   * @throws NullPointerException if any key or value in {@code multimap} is null
418   */
419  public static <K, V> ImmutableSetMultimap<K, V> copyOf(
420      Multimap<? extends K, ? extends V> multimap) {
421    checkNotNull(multimap); // eager for GWT
422
423    /*
424     * TODO(cpovirk): When given an ImmutableSetMultimap that has a non-null valueComparator, should
425     * we always return a new instance with a null valueComparator, as we already do if the input is
426     * empty or a partial view?
427     *
428     * Related: Should methods that do accept a comparator (like fromMapEntries, or like this one if
429     * we were to choose to *preserve* an input comparator) return not the generic empty of()
430     * instance but instead an empty ImmutableSetMultimap instance with the requested
431     * valueComparator, since the comparator is visible when users call `get` on a key that's not
432     * present?
433     */
434
435    if (multimap.isEmpty()) {
436      return of();
437    }
438
439    if (multimap instanceof ImmutableSetMultimap) {
440      @SuppressWarnings("unchecked") // safe since multimap is not writable
441      ImmutableSetMultimap<K, V> kvMultimap = (ImmutableSetMultimap<K, V>) multimap;
442      if (!kvMultimap.isPartialView()) {
443        return kvMultimap;
444      }
445    }
446
447    return fromMapEntries(multimap.asMap().entrySet(), /* valueComparator= */ null);
448  }
449
450  /**
451   * Returns an immutable multimap containing the specified entries. The returned multimap iterates
452   * over keys in the order they were first encountered in the input, and the values for each key
453   * are iterated in the order they were encountered. If two values for the same key are {@linkplain
454   * Object#equals equal}, the first value encountered is used.
455   *
456   * @throws NullPointerException if any key, value, or entry is null
457   * @since 19.0
458   */
459  public static <K, V> ImmutableSetMultimap<K, V> copyOf(
460      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
461    return new Builder<K, V>().putAll(entries).build();
462  }
463
464  /** Creates an ImmutableSetMultimap from an asMap.entrySet. */
465  static <K, V> ImmutableSetMultimap<K, V> fromMapEntries(
466      Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries,
467      @Nullable Comparator<? super V> valueComparator) {
468    if (mapEntries.isEmpty()) {
469      return of();
470    }
471    ImmutableMap.Builder<K, ImmutableSet<V>> builder =
472        new ImmutableMap.Builder<>(mapEntries.size());
473    int size = 0;
474
475    for (Entry<? extends K, ? extends Collection<? extends V>> entry : mapEntries) {
476      K key = entry.getKey();
477      Collection<? extends V> values = entry.getValue();
478      ImmutableSet<V> set = valueSet(valueComparator, values);
479      if (!set.isEmpty()) {
480        builder.put(key, set);
481        size += set.size();
482      }
483    }
484
485    return new ImmutableSetMultimap<>(builder.buildOrThrow(), size, valueComparator);
486  }
487
488  /** Creates an ImmutableSetMultimap from a map to builders. */
489  static <K, V> ImmutableSetMultimap<K, V> fromMapBuilderEntries(
490      Collection<? extends Map.Entry<K, ImmutableCollection.Builder<V>>> mapEntries,
491      @Nullable Comparator<? super V> valueComparator) {
492    if (mapEntries.isEmpty()) {
493      return of();
494    }
495    ImmutableMap.Builder<K, ImmutableSet<V>> builder =
496        new ImmutableMap.Builder<>(mapEntries.size());
497    int size = 0;
498
499    for (Entry<K, ImmutableCollection.Builder<V>> entry : mapEntries) {
500      K key = entry.getKey();
501      ImmutableSet.Builder<? extends V> values = (ImmutableSet.Builder<V>) entry.getValue();
502      // If orderValuesBy got called at the very end, we may need to do the ImmutableSet to
503      // ImmutableSortedSet copy for each of these.
504      ImmutableSet<V> set = valueSet(valueComparator, values.build());
505      if (!set.isEmpty()) {
506        builder.put(key, set);
507        size += set.size();
508      }
509    }
510
511    return new ImmutableSetMultimap<>(builder.buildOrThrow(), size, valueComparator);
512  }
513
514  /**
515   * Returned by get() when a missing key is provided. Also holds the comparator, if any, used for
516   * values.
517   */
518  private final transient ImmutableSet<V> emptySet;
519
520  /**
521   * An instance created in {@link #readObject} to be returned from {@link #readResolve}. This field
522   * is used only by those methods, and it is never set in a "normal" instance.
523   *
524   * <p>For more background, see {@code ConcurrentHashMultiset.deserializationReplacement}.
525   */
526  private transient @Nullable ImmutableSetMultimap<?, ?> deserializationReplacement;
527
528  ImmutableSetMultimap(
529      ImmutableMap<K, ImmutableSet<V>> map,
530      int size,
531      @Nullable Comparator<? super V> valueComparator) {
532    super(map, size);
533    this.emptySet = emptySet(valueComparator);
534  }
535
536  // views
537
538  /**
539   * Returns an immutable set of the values for the given key. If no mappings in the multimap have
540   * the provided key, an empty immutable set is returned. The values are in the same order as the
541   * parameters used to build this multimap.
542   */
543  @Override
544  public final ImmutableSet<V> get(K key) {
545    // This cast is safe as its type is known in constructor.
546    ImmutableSet<V> set = (ImmutableSet<V>) map.get(key);
547    return MoreObjects.firstNonNull(set, emptySet);
548  }
549
550  @LazyInit @RetainedWith private transient @Nullable ImmutableSetMultimap<V, K> inverse;
551
552  /**
553   * {@inheritDoc}
554   *
555   * <p>Because an inverse of a set multimap cannot contain multiple pairs with the same key and
556   * value, this method returns an {@code ImmutableSetMultimap} rather than the {@code
557   * ImmutableMultimap} specified in the {@code ImmutableMultimap} class.
558   *
559   * @since 11.0
560   */
561  @Override
562  public final ImmutableSetMultimap<V, K> inverse() {
563    ImmutableSetMultimap<V, K> result = inverse;
564    if (result == null) {
565      result = inverse = invert();
566    }
567    return result;
568  }
569
570  private ImmutableSetMultimap<V, K> invert() {
571    Builder<V, K> builder = builder();
572    for (Entry<K, V> entry : entries()) {
573      builder.put(entry.getValue(), entry.getKey());
574    }
575    ImmutableSetMultimap<V, K> invertedMultimap = builder.build();
576    invertedMultimap.inverse = this;
577    return invertedMultimap;
578  }
579
580  /**
581   * Guaranteed to throw an exception and leave the multimap unmodified.
582   *
583   * @throws UnsupportedOperationException always
584   * @deprecated Unsupported operation.
585   */
586  @CanIgnoreReturnValue
587  @Deprecated
588  @Override
589  @DoNotCall("Always throws UnsupportedOperationException")
590  public final ImmutableSet<V> removeAll(@Nullable Object key) {
591    throw new UnsupportedOperationException();
592  }
593
594  /**
595   * Guaranteed to throw an exception and leave the multimap unmodified.
596   *
597   * @throws UnsupportedOperationException always
598   * @deprecated Unsupported operation.
599   */
600  @CanIgnoreReturnValue
601  @Deprecated
602  @Override
603  @DoNotCall("Always throws UnsupportedOperationException")
604  public final ImmutableSet<V> replaceValues(K key, Iterable<? extends V> values) {
605    throw new UnsupportedOperationException();
606  }
607
608  /**
609   * Returns an immutable collection of all key-value pairs in the multimap. Its iterator traverses
610   * the values for the first key, the values for the second key, and so on.
611   */
612  @Override
613  public final ImmutableSet<Entry<K, V>> entries() {
614    return new EntrySet<>(this);
615  }
616
617  private static final class EntrySet<K, V> extends ImmutableSet<Entry<K, V>> {
618    private final transient ImmutableSetMultimap<K, V> multimap;
619
620    EntrySet(ImmutableSetMultimap<K, V> multimap) {
621      this.multimap = multimap;
622    }
623
624    @Override
625    public boolean contains(@Nullable Object object) {
626      if (object instanceof Entry) {
627        Entry<?, ?> entry = (Entry<?, ?>) object;
628        return multimap.containsEntry(entry.getKey(), entry.getValue());
629      }
630      return false;
631    }
632
633    @Override
634    public int size() {
635      return multimap.size();
636    }
637
638    @Override
639    public UnmodifiableIterator<Entry<K, V>> iterator() {
640      return multimap.entryIterator();
641    }
642
643    @Override
644    boolean isPartialView() {
645      return false;
646    }
647
648    // redeclare to help optimizers with b/310253115
649    @SuppressWarnings("RedundantOverride")
650    @Override
651    @J2ktIncompatible
652    @GwtIncompatible
653        Object writeReplace() {
654      return super.writeReplace();
655    }
656  }
657
658  private static <V> ImmutableSet<V> valueSet(
659      @Nullable Comparator<? super V> valueComparator, Collection<? extends V> values) {
660    return (valueComparator == null)
661        ? ImmutableSet.copyOf(values)
662        : ImmutableSortedSet.copyOf(valueComparator, values);
663  }
664
665  private static <V> ImmutableSet<V> emptySet(@Nullable Comparator<? super V> valueComparator) {
666    return (valueComparator == null)
667        ? ImmutableSet.of()
668        : ImmutableSortedSet.emptySet(valueComparator);
669  }
670
671  private static <V> ImmutableSet.Builder<V> valuesBuilder(
672      @Nullable Comparator<? super V> valueComparator) {
673    return (valueComparator == null)
674        ? new ImmutableSet.Builder<>()
675        : new ImmutableSortedSet.Builder<>(valueComparator);
676  }
677
678  /**
679   * @serialData number of distinct keys, and then for each distinct key: the key, the number of
680   *     values for that key, and the key's values
681   */
682  @GwtIncompatible
683  @J2ktIncompatible
684    private void writeObject(ObjectOutputStream stream) throws IOException {
685    stream.defaultWriteObject();
686    stream.writeObject(valueComparator());
687    Serialization.writeMultimap(this, stream);
688  }
689
690  private @Nullable Comparator<? super V> valueComparator() {
691    return emptySet instanceof ImmutableSortedSet
692        ? ((ImmutableSortedSet<V>) emptySet).comparator()
693        : null;
694  }
695
696  @GwtIncompatible
697  @J2ktIncompatible
698    private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
699    stream.defaultReadObject();
700    @SuppressWarnings("unchecked") // reading data stored by writeObject
701    Comparator<Object> valueComparator = (Comparator<Object>) stream.readObject();
702    int keyCount = stream.readInt();
703    if (keyCount < 0) {
704      throw new InvalidObjectException("Invalid key count " + keyCount);
705    }
706    ImmutableMap.Builder<Object, ImmutableSet<Object>> builder = ImmutableMap.builder();
707    int tmpSize = 0;
708
709    for (int i = 0; i < keyCount; i++) {
710      Object key = requireNonNull(stream.readObject());
711      int valueCount = stream.readInt();
712      if (valueCount <= 0) {
713        throw new InvalidObjectException("Invalid value count " + valueCount);
714      }
715
716      ImmutableSet.Builder<Object> valuesBuilder = valuesBuilder(valueComparator);
717      for (int j = 0; j < valueCount; j++) {
718        valuesBuilder.add(requireNonNull(stream.readObject()));
719      }
720      ImmutableSet<Object> valueSet = valuesBuilder.build();
721      if (valueSet.size() != valueCount) {
722        throw new InvalidObjectException("Duplicate key-value pairs exist for key " + key);
723      }
724      builder.put(key, valueSet);
725      tmpSize += valueCount;
726    }
727
728    ImmutableMap<Object, ImmutableSet<Object>> tmpMap;
729    try {
730      tmpMap = builder.buildOrThrow();
731    } catch (IllegalArgumentException e) {
732      throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
733    }
734
735    deserializationReplacement = new ImmutableSetMultimap<>(tmpMap, tmpSize, valueComparator);
736  }
737
738  @GwtIncompatible
739  @J2ktIncompatible
740    private Object readResolve() {
741    return requireNonNull(deserializationReplacement); // set by readObject
742  }
743
744  @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
745}