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