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.Beta;
022import com.google.common.annotations.GwtCompatible;
023import com.google.common.base.MoreObjects;
024import com.google.common.collect.Tables.AbstractCell;
025import com.google.errorprone.annotations.CanIgnoreReturnValue;
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.stream.Collector;
036import org.checkerframework.checker.nullness.compatqual.MonotonicNonNullDecl;
037import org.checkerframework.checker.nullness.compatqual.NullableDecl;
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  @Beta
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);
069    checkNotNull(columnFunction);
070    checkNotNull(valueFunction);
071    return Collector.of(
072        () -> new ImmutableTable.Builder<R, C, V>(),
073        (builder, t) ->
074            builder.put(rowFunction.apply(t), columnFunction.apply(t), valueFunction.apply(t)),
075        (b1, b2) -> b1.combine(b2),
076        b -> b.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);
097    checkNotNull(columnFunction);
098    checkNotNull(valueFunction);
099    checkNotNull(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);
154      this.column = checkNotNull(column);
155      this.value = checkNotNull(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);
175      this.value = checkNotNull(mergeFunction.apply(this.value, value));
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(checkNotNull(rowKey), checkNotNull(columnKey), checkNotNull(value));
237  }
238
239  /**
240   * A builder for creating immutable table instances, especially {@code public static final} tables
241   * ("constant tables"). Example:
242   *
243   * <pre>{@code
244   * static final ImmutableTable<Integer, Character, String> SPREADSHEET =
245   *     new ImmutableTable.Builder<Integer, Character, String>()
246   *         .put(1, 'A', "foo")
247   *         .put(1, 'B', "bar")
248   *         .put(2, 'A', "baz")
249   *         .build();
250   * }</pre>
251   *
252   * <p>By default, the order in which cells are added to the builder determines the iteration
253   * ordering of all views in the returned table, with {@link #putAll} following the {@link
254   * Table#cellSet()} iteration order. However, if {@link #orderRowsBy} or {@link #orderColumnsBy}
255   * is called, the views are sorted by the supplied comparators.
256   *
257   * <p>For empty or single-cell immutable tables, {@link #of()} and {@link #of(Object, Object,
258   * Object)} are even more convenient.
259   *
260   * <p>Builder instances can be reused - it is safe to call {@link #build} multiple times to build
261   * multiple tables in series. Each table is a superset of the tables created before it.
262   *
263   * @since 11.0
264   */
265  public static final class Builder<R, C, V> {
266    private final List<Cell<R, C, V>> cells = Lists.newArrayList();
267    @MonotonicNonNullDecl private Comparator<? super R> rowComparator;
268    @MonotonicNonNullDecl private Comparator<? super C> columnComparator;
269
270    /**
271     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
272     * ImmutableTable#builder}.
273     */
274    public Builder() {}
275
276    /** Specifies the ordering of the generated table's rows. */
277    @CanIgnoreReturnValue
278    public Builder<R, C, V> orderRowsBy(Comparator<? super R> rowComparator) {
279      this.rowComparator = checkNotNull(rowComparator);
280      return this;
281    }
282
283    /** Specifies the ordering of the generated table's columns. */
284    @CanIgnoreReturnValue
285    public Builder<R, C, V> orderColumnsBy(Comparator<? super C> columnComparator) {
286      this.columnComparator = checkNotNull(columnComparator);
287      return this;
288    }
289
290    /**
291     * Associates the ({@code rowKey}, {@code columnKey}) pair with {@code value} in the built
292     * table. Duplicate key pairs are not allowed and will cause {@link #build} to fail.
293     */
294    @CanIgnoreReturnValue
295    public Builder<R, C, V> put(R rowKey, C columnKey, V value) {
296      cells.add(cellOf(rowKey, columnKey, value));
297      return this;
298    }
299
300    /**
301     * Adds the given {@code cell} to the table, making it immutable if necessary. Duplicate key
302     * pairs are not allowed and will cause {@link #build} to fail.
303     */
304    @CanIgnoreReturnValue
305    public Builder<R, C, V> put(Cell<? extends R, ? extends C, ? extends V> cell) {
306      if (cell instanceof Tables.ImmutableCell) {
307        checkNotNull(cell.getRowKey());
308        checkNotNull(cell.getColumnKey());
309        checkNotNull(cell.getValue());
310        @SuppressWarnings("unchecked") // all supported methods are covariant
311        Cell<R, C, V> immutableCell = (Cell<R, C, V>) cell;
312        cells.add(immutableCell);
313      } else {
314        put(cell.getRowKey(), cell.getColumnKey(), cell.getValue());
315      }
316      return this;
317    }
318
319    /**
320     * Associates all of the given table's keys and values in the built table. Duplicate row key
321     * column key pairs are not allowed, and will cause {@link #build} to fail.
322     *
323     * @throws NullPointerException if any key or value in {@code table} is null
324     */
325    @CanIgnoreReturnValue
326    public Builder<R, C, V> putAll(Table<? extends R, ? extends C, ? extends V> table) {
327      for (Cell<? extends R, ? extends C, ? extends V> cell : table.cellSet()) {
328        put(cell);
329      }
330      return this;
331    }
332
333    Builder<R, C, V> combine(Builder<R, C, V> other) {
334      this.cells.addAll(other.cells);
335      return this;
336    }
337
338    /**
339     * Returns a newly-created immutable table.
340     *
341     * @throws IllegalArgumentException if duplicate key pairs were added
342     */
343    public ImmutableTable<R, C, V> build() {
344      int size = cells.size();
345      switch (size) {
346        case 0:
347          return of();
348        case 1:
349          return new SingletonImmutableTable<>(Iterables.getOnlyElement(cells));
350        default:
351          return RegularImmutableTable.forCells(cells, rowComparator, columnComparator);
352      }
353    }
354  }
355
356  ImmutableTable() {}
357
358  @Override
359  public ImmutableSet<Cell<R, C, V>> cellSet() {
360    return (ImmutableSet<Cell<R, C, V>>) super.cellSet();
361  }
362
363  @Override
364  abstract ImmutableSet<Cell<R, C, V>> createCellSet();
365
366  @Override
367  final UnmodifiableIterator<Cell<R, C, V>> cellIterator() {
368    throw new AssertionError("should never be called");
369  }
370
371  @Override
372  final Spliterator<Cell<R, C, V>> cellSpliterator() {
373    throw new AssertionError("should never be called");
374  }
375
376  @Override
377  public ImmutableCollection<V> values() {
378    return (ImmutableCollection<V>) super.values();
379  }
380
381  @Override
382  abstract ImmutableCollection<V> createValues();
383
384  @Override
385  final Iterator<V> valuesIterator() {
386    throw new AssertionError("should never be called");
387  }
388
389  /**
390   * {@inheritDoc}
391   *
392   * @throws NullPointerException if {@code columnKey} is {@code null}
393   */
394  @Override
395  public ImmutableMap<R, V> column(C columnKey) {
396    checkNotNull(columnKey);
397    return MoreObjects.firstNonNull(
398        (ImmutableMap<R, V>) columnMap().get(columnKey), ImmutableMap.<R, V>of());
399  }
400
401  @Override
402  public ImmutableSet<C> columnKeySet() {
403    return columnMap().keySet();
404  }
405
406  /**
407   * {@inheritDoc}
408   *
409   * <p>The value {@code Map<R, V>} instances in the returned map are {@link ImmutableMap} instances
410   * as well.
411   */
412  @Override
413  public abstract ImmutableMap<C, Map<R, V>> columnMap();
414
415  /**
416   * {@inheritDoc}
417   *
418   * @throws NullPointerException if {@code rowKey} is {@code null}
419   */
420  @Override
421  public ImmutableMap<C, V> row(R rowKey) {
422    checkNotNull(rowKey);
423    return MoreObjects.firstNonNull(
424        (ImmutableMap<C, V>) rowMap().get(rowKey), ImmutableMap.<C, V>of());
425  }
426
427  @Override
428  public ImmutableSet<R> rowKeySet() {
429    return rowMap().keySet();
430  }
431
432  /**
433   * {@inheritDoc}
434   *
435   * <p>The value {@code Map<C, V>} instances in the returned map are {@link ImmutableMap} instances
436   * as well.
437   */
438  @Override
439  public abstract ImmutableMap<R, Map<C, V>> rowMap();
440
441  @Override
442  public boolean contains(@NullableDecl Object rowKey, @NullableDecl Object columnKey) {
443    return get(rowKey, columnKey) != null;
444  }
445
446  @Override
447  public boolean containsValue(@NullableDecl Object value) {
448    return values().contains(value);
449  }
450
451  /**
452   * Guaranteed to throw an exception and leave the table unmodified.
453   *
454   * @throws UnsupportedOperationException always
455   * @deprecated Unsupported operation.
456   */
457  @Deprecated
458  @Override
459  public final void clear() {
460    throw new UnsupportedOperationException();
461  }
462
463  /**
464   * Guaranteed to throw an exception and leave the table unmodified.
465   *
466   * @throws UnsupportedOperationException always
467   * @deprecated Unsupported operation.
468   */
469  @CanIgnoreReturnValue
470  @Deprecated
471  @Override
472  public final V put(R rowKey, C columnKey, V value) {
473    throw new UnsupportedOperationException();
474  }
475
476  /**
477   * Guaranteed to throw an exception and leave the table unmodified.
478   *
479   * @throws UnsupportedOperationException always
480   * @deprecated Unsupported operation.
481   */
482  @Deprecated
483  @Override
484  public final void putAll(Table<? extends R, ? extends C, ? extends V> table) {
485    throw new UnsupportedOperationException();
486  }
487
488  /**
489   * Guaranteed to throw an exception and leave the table unmodified.
490   *
491   * @throws UnsupportedOperationException always
492   * @deprecated Unsupported operation.
493   */
494  @CanIgnoreReturnValue
495  @Deprecated
496  @Override
497  public final V remove(Object rowKey, Object columnKey) {
498    throw new UnsupportedOperationException();
499  }
500
501  /** Creates the common serialized form for this table. */
502  abstract SerializedForm createSerializedForm();
503
504  /**
505   * Serialized type for all ImmutableTable instances. It captures the logical contents and
506   * preserves iteration order of all views.
507   */
508  static final class SerializedForm implements Serializable {
509    private final Object[] rowKeys;
510    private final Object[] columnKeys;
511
512    private final Object[] cellValues;
513    private final int[] cellRowIndices;
514    private final int[] cellColumnIndices;
515
516    private SerializedForm(
517        Object[] rowKeys,
518        Object[] columnKeys,
519        Object[] cellValues,
520        int[] cellRowIndices,
521        int[] cellColumnIndices) {
522      this.rowKeys = rowKeys;
523      this.columnKeys = columnKeys;
524      this.cellValues = cellValues;
525      this.cellRowIndices = cellRowIndices;
526      this.cellColumnIndices = cellColumnIndices;
527    }
528
529    static SerializedForm create(
530        ImmutableTable<?, ?, ?> table, int[] cellRowIndices, int[] cellColumnIndices) {
531      return new SerializedForm(
532          table.rowKeySet().toArray(),
533          table.columnKeySet().toArray(),
534          table.values().toArray(),
535          cellRowIndices,
536          cellColumnIndices);
537    }
538
539    Object readResolve() {
540      if (cellValues.length == 0) {
541        return of();
542      }
543      if (cellValues.length == 1) {
544        return of(rowKeys[0], columnKeys[0], cellValues[0]);
545      }
546      ImmutableList.Builder<Cell<Object, Object, Object>> cellListBuilder =
547          new ImmutableList.Builder<>(cellValues.length);
548      for (int i = 0; i < cellValues.length; i++) {
549        cellListBuilder.add(
550            cellOf(rowKeys[cellRowIndices[i]], columnKeys[cellColumnIndices[i]], cellValues[i]));
551      }
552      return RegularImmutableTable.forOrderedComponents(
553          cellListBuilder.build(), ImmutableSet.copyOf(rowKeys), ImmutableSet.copyOf(columnKeys));
554    }
555
556    private static final long serialVersionUID = 0;
557  }
558
559  final Object writeReplace() {
560    return createSerializedForm();
561  }
562}