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