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