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;
020
021import com.google.common.annotations.GwtCompatible;
022import com.google.common.base.MoreObjects;
023import com.google.common.collect.Tables.AbstractCell;
024import com.google.errorprone.annotations.CanIgnoreReturnValue;
025import com.google.errorprone.annotations.DoNotMock;
026import java.io.Serializable;
027import java.util.ArrayList;
028import java.util.Comparator;
029import java.util.Iterator;
030import java.util.List;
031import java.util.Map;
032import java.util.Spliterator;
033import java.util.function.BinaryOperator;
034import java.util.function.Function;
035import java.util.function.Supplier;
036import java.util.stream.Collector;
037import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
038import org.checkerframework.checker.nullness.qual.Nullable;
039
040/**
041 * A {@link Table} whose contents will never change, with many other important properties detailed
042 * at {@link ImmutableCollection}.
043 *
044 * <p>See the Guava User Guide article on <a href=
045 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained"> immutable collections</a>.
046 *
047 * @author Gregory Kick
048 * @since 11.0
049 */
050@GwtCompatible
051public abstract class ImmutableTable<R, C, V> extends AbstractTable<R, C, V>
052    implements Serializable {
053
054  /**
055   * Returns a {@code Collector} that accumulates elements into an {@code ImmutableTable}. Each
056   * input element is mapped to one cell in the returned table, with the rows, columns, and values
057   * generated by applying the specified functions.
058   *
059   * <p>The returned {@code Collector} will throw a {@code NullPointerException} at collection time
060   * if the row, column, or value functions return null on any input.
061   *
062   * @since 21.0
063   */
064  public static <T, R, C, V> Collector<T, ?, ImmutableTable<R, C, V>> toImmutableTable(
065      Function<? super T, ? extends R> rowFunction,
066      Function<? super T, ? extends C> columnFunction,
067      Function<? super T, ? extends V> valueFunction) {
068    checkNotNull(rowFunction, "rowFunction");
069    checkNotNull(columnFunction, "columnFunction");
070    checkNotNull(valueFunction, "valueFunction");
071    return Collector.of(
072        (Supplier<Builder<R, C, V>>) Builder::new,
073        (builder, t) ->
074            builder.put(rowFunction.apply(t), columnFunction.apply(t), valueFunction.apply(t)),
075        Builder::combine,
076        Builder::build);
077  }
078
079  /**
080   * Returns a {@code Collector} that accumulates elements into an {@code ImmutableTable}. Each
081   * input element is mapped to one cell in the returned table, with the rows, columns, and values
082   * generated by applying the specified functions. If multiple inputs are mapped to the same row
083   * and column pair, they will be combined with the specified merging function in encounter order.
084   *
085   * <p>The returned {@code Collector} will throw a {@code NullPointerException} at collection time
086   * if the row, column, value, or merging functions return null on any input.
087   *
088   * @since 21.0
089   */
090  public static <T, R, C, V> Collector<T, ?, ImmutableTable<R, C, V>> toImmutableTable(
091      Function<? super T, ? extends R> rowFunction,
092      Function<? super T, ? extends C> columnFunction,
093      Function<? super T, ? extends V> valueFunction,
094      BinaryOperator<V> mergeFunction) {
095
096    checkNotNull(rowFunction, "rowFunction");
097    checkNotNull(columnFunction, "columnFunction");
098    checkNotNull(valueFunction, "valueFunction");
099    checkNotNull(mergeFunction, "mergeFunction");
100
101    /*
102     * No mutable Table exactly matches the insertion order behavior of ImmutableTable.Builder, but
103     * the Builder can't efficiently support merging of duplicate values.  Getting around this
104     * requires some work.
105     */
106
107    return Collector.of(
108        () -> new CollectorState<R, C, V>()
109        /* GWT isn't currently playing nicely with constructor references? */ ,
110        (state, input) ->
111            state.put(
112                rowFunction.apply(input),
113                columnFunction.apply(input),
114                valueFunction.apply(input),
115                mergeFunction),
116        (s1, s2) -> s1.combine(s2, mergeFunction),
117        state -> state.toTable());
118  }
119
120  private static final class CollectorState<R, C, V> {
121    final List<MutableCell<R, C, V>> insertionOrder = new ArrayList<>();
122    final Table<R, C, MutableCell<R, C, V>> table = HashBasedTable.create();
123
124    void put(R row, C column, V value, BinaryOperator<V> merger) {
125      MutableCell<R, C, V> oldCell = table.get(row, column);
126      if (oldCell == null) {
127        MutableCell<R, C, V> cell = new MutableCell<>(row, column, value);
128        insertionOrder.add(cell);
129        table.put(row, column, cell);
130      } else {
131        oldCell.merge(value, merger);
132      }
133    }
134
135    CollectorState<R, C, V> combine(CollectorState<R, C, V> other, BinaryOperator<V> merger) {
136      for (MutableCell<R, C, V> cell : other.insertionOrder) {
137        put(cell.getRowKey(), cell.getColumnKey(), cell.getValue(), merger);
138      }
139      return this;
140    }
141
142    ImmutableTable<R, C, V> toTable() {
143      return copyOf(insertionOrder);
144    }
145  }
146
147  private static final class MutableCell<R, C, V> extends AbstractCell<R, C, V> {
148    private final R row;
149    private final C column;
150    private V value;
151
152    MutableCell(R row, C column, V value) {
153      this.row = checkNotNull(row, "row");
154      this.column = checkNotNull(column, "column");
155      this.value = checkNotNull(value, "value");
156    }
157
158    @Override
159    public R getRowKey() {
160      return row;
161    }
162
163    @Override
164    public C getColumnKey() {
165      return column;
166    }
167
168    @Override
169    public V getValue() {
170      return value;
171    }
172
173    void merge(V value, BinaryOperator<V> mergeFunction) {
174      checkNotNull(value, "value");
175      this.value = checkNotNull(mergeFunction.apply(this.value, value), "mergeFunction.apply");
176    }
177  }
178
179  /** Returns an empty immutable table. */
180  @SuppressWarnings("unchecked")
181  public static <R, C, V> ImmutableTable<R, C, V> of() {
182    return (ImmutableTable<R, C, V>) SparseImmutableTable.EMPTY;
183  }
184
185  /** Returns an immutable table containing a single cell. */
186  public static <R, C, V> ImmutableTable<R, C, V> of(R rowKey, C columnKey, V value) {
187    return new SingletonImmutableTable<>(rowKey, columnKey, value);
188  }
189
190  /**
191   * Returns an immutable copy of the provided table.
192   *
193   * <p>The {@link Table#cellSet()} iteration order of the provided table determines the iteration
194   * ordering of all views in the returned table. Note that some views of the original table and the
195   * copied table may have different iteration orders. For more control over the ordering, create a
196   * {@link Builder} and call {@link Builder#orderRowsBy}, {@link Builder#orderColumnsBy}, and
197   * {@link Builder#putAll}
198   *
199   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
200   * safe to do so. The exact circumstances under which a copy will or will not be performed are
201   * undocumented and subject to change.
202   */
203  public static <R, C, V> ImmutableTable<R, C, V> copyOf(
204      Table<? extends R, ? extends C, ? extends V> table) {
205    if (table instanceof ImmutableTable) {
206      @SuppressWarnings("unchecked")
207      ImmutableTable<R, C, V> parameterizedTable = (ImmutableTable<R, C, V>) table;
208      return parameterizedTable;
209    } else {
210      return copyOf(table.cellSet());
211    }
212  }
213
214  private static <R, C, V> ImmutableTable<R, C, V> copyOf(
215      Iterable<? extends Cell<? extends R, ? extends C, ? extends V>> cells) {
216    ImmutableTable.Builder<R, C, V> builder = ImmutableTable.builder();
217    for (Cell<? extends R, ? extends C, ? extends V> cell : cells) {
218      builder.put(cell);
219    }
220    return builder.build();
221  }
222
223  /**
224   * Returns a new builder. The generated builder is equivalent to the builder created by the {@link
225   * Builder#Builder() ImmutableTable.Builder()} constructor.
226   */
227  public static <R, C, V> Builder<R, C, V> builder() {
228    return new Builder<>();
229  }
230
231  /**
232   * Verifies that {@code rowKey}, {@code columnKey} and {@code value} are non-null, and returns a
233   * new entry with those values.
234   */
235  static <R, C, V> Cell<R, C, V> cellOf(R rowKey, C columnKey, V value) {
236    return Tables.immutableCell(
237        checkNotNull(rowKey, "rowKey"),
238        checkNotNull(columnKey, "columnKey"),
239        checkNotNull(value, "value"));
240  }
241
242  /**
243   * A builder for creating immutable table instances, especially {@code public static final} tables
244   * ("constant tables"). Example:
245   *
246   * <pre>{@code
247   * static final ImmutableTable<Integer, Character, String> SPREADSHEET =
248   *     new ImmutableTable.Builder<Integer, Character, String>()
249   *         .put(1, 'A', "foo")
250   *         .put(1, 'B', "bar")
251   *         .put(2, 'A', "baz")
252   *         .build();
253   * }</pre>
254   *
255   * <p>By default, the order in which cells are added to the builder determines the iteration
256   * ordering of all views in the returned table, with {@link #putAll} following the {@link
257   * Table#cellSet()} iteration order. However, if {@link #orderRowsBy} or {@link #orderColumnsBy}
258   * is called, the views are sorted by the supplied comparators.
259   *
260   * <p>For empty or single-cell immutable tables, {@link #of()} and {@link #of(Object, Object,
261   * Object)} are even more convenient.
262   *
263   * <p>Builder instances can be reused - it is safe to call {@link #build} multiple times to build
264   * multiple tables in series. Each table is a superset of the tables created before it.
265   *
266   * @since 11.0
267   */
268  @DoNotMock
269  public static final class Builder<R, C, V> {
270    private final List<Cell<R, C, V>> cells = Lists.newArrayList();
271    @MonotonicNonNull private Comparator<? super R> rowComparator;
272    @MonotonicNonNull private Comparator<? super C> columnComparator;
273
274    /**
275     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
276     * ImmutableTable#builder}.
277     */
278    public Builder() {}
279
280    /** Specifies the ordering of the generated table's rows. */
281    @CanIgnoreReturnValue
282    public Builder<R, C, V> orderRowsBy(Comparator<? super R> rowComparator) {
283      this.rowComparator = checkNotNull(rowComparator, "rowComparator");
284      return this;
285    }
286
287    /** Specifies the ordering of the generated table's columns. */
288    @CanIgnoreReturnValue
289    public Builder<R, C, V> orderColumnsBy(Comparator<? super C> columnComparator) {
290      this.columnComparator = checkNotNull(columnComparator, "columnComparator");
291      return this;
292    }
293
294    /**
295     * Associates the ({@code rowKey}, {@code columnKey}) pair with {@code value} in the built
296     * table. Duplicate key pairs are not allowed and will cause {@link #build} to fail.
297     */
298    @CanIgnoreReturnValue
299    public Builder<R, C, V> put(R rowKey, C columnKey, V value) {
300      cells.add(cellOf(rowKey, columnKey, value));
301      return this;
302    }
303
304    /**
305     * Adds the given {@code cell} to the table, making it immutable if necessary. Duplicate key
306     * pairs are not allowed and will cause {@link #build} to fail.
307     */
308    @CanIgnoreReturnValue
309    public Builder<R, C, V> put(Cell<? extends R, ? extends C, ? extends V> cell) {
310      if (cell instanceof Tables.ImmutableCell) {
311        checkNotNull(cell.getRowKey(), "row");
312        checkNotNull(cell.getColumnKey(), "column");
313        checkNotNull(cell.getValue(), "value");
314        @SuppressWarnings("unchecked") // all supported methods are covariant
315        Cell<R, C, V> immutableCell = (Cell<R, C, V>) cell;
316        cells.add(immutableCell);
317      } else {
318        put(cell.getRowKey(), cell.getColumnKey(), cell.getValue());
319      }
320      return this;
321    }
322
323    /**
324     * Associates all of the given table's keys and values in the built table. Duplicate row key
325     * column key pairs are not allowed, and will cause {@link #build} to fail.
326     *
327     * @throws NullPointerException if any key or value in {@code table} is null
328     */
329    @CanIgnoreReturnValue
330    public Builder<R, C, V> putAll(Table<? extends R, ? extends C, ? extends V> table) {
331      for (Cell<? extends R, ? extends C, ? extends V> cell : table.cellSet()) {
332        put(cell);
333      }
334      return this;
335    }
336
337    Builder<R, C, V> combine(Builder<R, C, V> other) {
338      this.cells.addAll(other.cells);
339      return this;
340    }
341
342    /**
343     * Returns a newly-created immutable table.
344     *
345     * @throws IllegalArgumentException if duplicate key pairs were added
346     */
347    public ImmutableTable<R, C, V> build() {
348      int size = cells.size();
349      switch (size) {
350        case 0:
351          return of();
352        case 1:
353          return new SingletonImmutableTable<>(Iterables.getOnlyElement(cells));
354        default:
355          return RegularImmutableTable.forCells(cells, rowComparator, columnComparator);
356      }
357    }
358  }
359
360  ImmutableTable() {}
361
362  @Override
363  public ImmutableSet<Cell<R, C, V>> cellSet() {
364    return (ImmutableSet<Cell<R, C, V>>) super.cellSet();
365  }
366
367  @Override
368  abstract ImmutableSet<Cell<R, C, V>> createCellSet();
369
370  @Override
371  final UnmodifiableIterator<Cell<R, C, V>> cellIterator() {
372    throw new AssertionError("should never be called");
373  }
374
375  @Override
376  final Spliterator<Cell<R, C, V>> cellSpliterator() {
377    throw new AssertionError("should never be called");
378  }
379
380  @Override
381  public ImmutableCollection<V> values() {
382    return (ImmutableCollection<V>) super.values();
383  }
384
385  @Override
386  abstract ImmutableCollection<V> createValues();
387
388  @Override
389  final Iterator<V> valuesIterator() {
390    throw new AssertionError("should never be called");
391  }
392
393  /**
394   * {@inheritDoc}
395   *
396   * @throws NullPointerException if {@code columnKey} is {@code null}
397   */
398  @Override
399  public ImmutableMap<R, V> column(C columnKey) {
400    checkNotNull(columnKey, "columnKey");
401    return MoreObjects.firstNonNull(
402        (ImmutableMap<R, V>) columnMap().get(columnKey), ImmutableMap.<R, V>of());
403  }
404
405  @Override
406  public ImmutableSet<C> columnKeySet() {
407    return columnMap().keySet();
408  }
409
410  /**
411   * {@inheritDoc}
412   *
413   * <p>The value {@code Map<R, V>} instances in the returned map are {@link ImmutableMap} instances
414   * as well.
415   */
416  @Override
417  public abstract ImmutableMap<C, Map<R, V>> columnMap();
418
419  /**
420   * {@inheritDoc}
421   *
422   * @throws NullPointerException if {@code rowKey} is {@code null}
423   */
424  @Override
425  public ImmutableMap<C, V> row(R rowKey) {
426    checkNotNull(rowKey, "rowKey");
427    return MoreObjects.firstNonNull(
428        (ImmutableMap<C, V>) rowMap().get(rowKey), ImmutableMap.<C, V>of());
429  }
430
431  @Override
432  public ImmutableSet<R> rowKeySet() {
433    return rowMap().keySet();
434  }
435
436  /**
437   * {@inheritDoc}
438   *
439   * <p>The value {@code Map<C, V>} instances in the returned map are {@link ImmutableMap} instances
440   * as well.
441   */
442  @Override
443  public abstract ImmutableMap<R, Map<C, V>> rowMap();
444
445  @Override
446  public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) {
447    return get(rowKey, columnKey) != null;
448  }
449
450  @Override
451  public boolean containsValue(@Nullable Object value) {
452    return values().contains(value);
453  }
454
455  /**
456   * Guaranteed to throw an exception and leave the table unmodified.
457   *
458   * @throws UnsupportedOperationException always
459   * @deprecated Unsupported operation.
460   */
461  @Deprecated
462  @Override
463  public final void clear() {
464    throw new UnsupportedOperationException();
465  }
466
467  /**
468   * Guaranteed to throw an exception and leave the table unmodified.
469   *
470   * @throws UnsupportedOperationException always
471   * @deprecated Unsupported operation.
472   */
473  @CanIgnoreReturnValue
474  @Deprecated
475  @Override
476  public final V put(R rowKey, C columnKey, V value) {
477    throw new UnsupportedOperationException();
478  }
479
480  /**
481   * Guaranteed to throw an exception and leave the table unmodified.
482   *
483   * @throws UnsupportedOperationException always
484   * @deprecated Unsupported operation.
485   */
486  @Deprecated
487  @Override
488  public final void putAll(Table<? extends R, ? extends C, ? extends V> table) {
489    throw new UnsupportedOperationException();
490  }
491
492  /**
493   * Guaranteed to throw an exception and leave the table unmodified.
494   *
495   * @throws UnsupportedOperationException always
496   * @deprecated Unsupported operation.
497   */
498  @CanIgnoreReturnValue
499  @Deprecated
500  @Override
501  public final V remove(Object rowKey, Object columnKey) {
502    throw new UnsupportedOperationException();
503  }
504
505  /** Creates the common serialized form for this table. */
506  abstract SerializedForm createSerializedForm();
507
508  /**
509   * Serialized type for all ImmutableTable instances. It captures the logical contents and
510   * preserves iteration order of all views.
511   */
512  static final class SerializedForm implements Serializable {
513    private final Object[] rowKeys;
514    private final Object[] columnKeys;
515
516    private final Object[] cellValues;
517    private final int[] cellRowIndices;
518    private final int[] cellColumnIndices;
519
520    private SerializedForm(
521        Object[] rowKeys,
522        Object[] columnKeys,
523        Object[] cellValues,
524        int[] cellRowIndices,
525        int[] cellColumnIndices) {
526      this.rowKeys = rowKeys;
527      this.columnKeys = columnKeys;
528      this.cellValues = cellValues;
529      this.cellRowIndices = cellRowIndices;
530      this.cellColumnIndices = cellColumnIndices;
531    }
532
533    static SerializedForm create(
534        ImmutableTable<?, ?, ?> table, int[] cellRowIndices, int[] cellColumnIndices) {
535      return new SerializedForm(
536          table.rowKeySet().toArray(),
537          table.columnKeySet().toArray(),
538          table.values().toArray(),
539          cellRowIndices,
540          cellColumnIndices);
541    }
542
543    Object readResolve() {
544      if (cellValues.length == 0) {
545        return of();
546      }
547      if (cellValues.length == 1) {
548        return of(rowKeys[0], columnKeys[0], cellValues[0]);
549      }
550      ImmutableList.Builder<Cell<Object, Object, Object>> cellListBuilder =
551          new ImmutableList.Builder<>(cellValues.length);
552      for (int i = 0; i < cellValues.length; i++) {
553        cellListBuilder.add(
554            cellOf(rowKeys[cellRowIndices[i]], columnKeys[cellColumnIndices[i]], cellValues[i]));
555      }
556      return RegularImmutableTable.forOrderedComponents(
557          cellListBuilder.build(), ImmutableSet.copyOf(rowKeys), ImmutableSet.copyOf(columnKeys));
558    }
559
560    private static final long serialVersionUID = 0;
561  }
562
563  final Object writeReplace() {
564    return createSerializedForm();
565  }
566}