001/*
002 * Copyright (C) 2014 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.graph;
018
019import static com.google.common.base.Preconditions.checkNotNull;
020
021import com.google.common.annotations.Beta;
022import com.google.common.base.Function;
023import com.google.common.base.Functions;
024import com.google.common.collect.ImmutableMap;
025import com.google.common.collect.Maps;
026import com.google.common.graph.GraphConstants.Presence;
027import com.google.errorprone.annotations.CanIgnoreReturnValue;
028import com.google.errorprone.annotations.Immutable;
029
030/**
031 * A {@link Graph} whose elements and structural relationships will never change. Instances of this
032 * class may be obtained with {@link #copyOf(Graph)}.
033 *
034 * <p>See the Guava User's Guide's <a
035 * href="https://github.com/google/guava/wiki/GraphsExplained#immutable-implementations">discussion
036 * of the {@code Immutable*} types</a> for more information on the properties and guarantees
037 * provided by this class.
038 *
039 * @author James Sexton
040 * @author Joshua O'Madadhain
041 * @author Omar Darwish
042 * @author Jens Nyman
043 * @param <N> Node parameter type
044 * @since 20.0
045 */
046@Beta
047@Immutable(containerOf = {"N"})
048public class ImmutableGraph<N> extends ForwardingGraph<N> {
049  @SuppressWarnings("Immutable") // The backing graph must be immutable.
050  private final BaseGraph<N> backingGraph;
051
052  ImmutableGraph(BaseGraph<N> backingGraph) {
053    this.backingGraph = backingGraph;
054  }
055
056  /** Returns an immutable copy of {@code graph}. */
057  public static <N> ImmutableGraph<N> copyOf(Graph<N> graph) {
058    return (graph instanceof ImmutableGraph)
059        ? (ImmutableGraph<N>) graph
060        : new ImmutableGraph<N>(
061            new StandardValueGraph<N, Presence>(
062                GraphBuilder.from(graph), getNodeConnections(graph), graph.edges().size()));
063  }
064
065  /**
066   * Simply returns its argument.
067   *
068   * @deprecated no need to use this
069   */
070  @Deprecated
071  public static <N> ImmutableGraph<N> copyOf(ImmutableGraph<N> graph) {
072    return checkNotNull(graph);
073  }
074
075  @Override
076  public ElementOrder<N> incidentEdgeOrder() {
077    return ElementOrder.stable();
078  }
079
080  private static <N> ImmutableMap<N, GraphConnections<N, Presence>> getNodeConnections(
081      Graph<N> graph) {
082    // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have
083    // whatever ordering the graph's nodes do, so ImmutableSortedMap is unnecessary even if the
084    // input nodes are sorted.
085    ImmutableMap.Builder<N, GraphConnections<N, Presence>> nodeConnections = ImmutableMap.builder();
086    for (N node : graph.nodes()) {
087      nodeConnections.put(node, connectionsOf(graph, node));
088    }
089    return nodeConnections.build();
090  }
091
092  @SuppressWarnings("unchecked")
093  private static <N> GraphConnections<N, Presence> connectionsOf(Graph<N> graph, N node) {
094    Function<N, Presence> edgeValueFn =
095        (Function<N, Presence>) Functions.constant(Presence.EDGE_EXISTS);
096    return graph.isDirected()
097        ? DirectedGraphConnections.ofImmutable(node, graph.incidentEdges(node), edgeValueFn)
098        : UndirectedGraphConnections.ofImmutable(
099            Maps.asMap(graph.adjacentNodes(node), edgeValueFn));
100  }
101
102  @Override
103  protected BaseGraph<N> delegate() {
104    return backingGraph;
105  }
106
107  /**
108   * A builder for creating {@link ImmutableGraph} instances, especially {@code static final}
109   * graphs. Example:
110   *
111   * <pre>{@code
112   * static final ImmutableGraph<Country> COUNTRY_ADJACENCY_GRAPH =
113   *     GraphBuilder.undirected()
114   *         .<Country>immutable()
115   *         .putEdge(FRANCE, GERMANY)
116   *         .putEdge(FRANCE, BELGIUM)
117   *         .putEdge(GERMANY, BELGIUM)
118   *         .addNode(ICELAND)
119   *         .build();
120   * }</pre>
121   *
122   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
123   * multiple graphs in series. Each new graph contains all the elements of the ones created before
124   * it.
125   *
126   * @since 28.0
127   */
128  public static class Builder<N> {
129
130    private final MutableGraph<N> mutableGraph;
131
132    Builder(GraphBuilder<N> graphBuilder) {
133      // The incidentEdgeOrder for immutable graphs is always stable. However, we don't want to
134      // modify this builder, so we make a copy instead.
135      this.mutableGraph = graphBuilder.copy().incidentEdgeOrder(ElementOrder.<N>stable()).build();
136    }
137
138    /**
139     * Adds {@code node} if it is not already present.
140     *
141     * <p><b>Nodes must be unique</b>, just as {@code Map} keys must be. They must also be non-null.
142     *
143     * @return this {@code Builder} object
144     */
145    @CanIgnoreReturnValue
146    public Builder<N> addNode(N node) {
147      mutableGraph.addNode(node);
148      return this;
149    }
150
151    /**
152     * Adds an edge connecting {@code nodeU} to {@code nodeV} if one is not already present.
153     *
154     * <p>If the graph is directed, the resultant edge will be directed; otherwise, it will be
155     * undirected.
156     *
157     * <p>If {@code nodeU} and {@code nodeV} are not already present in this graph, this method will
158     * silently {@link #addNode(Object) add} {@code nodeU} and {@code nodeV} to the graph.
159     *
160     * @return this {@code Builder} object
161     * @throws IllegalArgumentException if the introduction of the edge would violate {@link
162     *     #allowsSelfLoops()}
163     */
164    @CanIgnoreReturnValue
165    public Builder<N> putEdge(N nodeU, N nodeV) {
166      mutableGraph.putEdge(nodeU, nodeV);
167      return this;
168    }
169
170    /**
171     * Adds an edge connecting {@code endpoints} (in the order, if any, specified by {@code
172     * endpoints}) if one is not already present.
173     *
174     * <p>If this graph is directed, {@code endpoints} must be ordered and the added edge will be
175     * directed; if it is undirected, the added edge will be undirected.
176     *
177     * <p>If this graph is directed, {@code endpoints} must be ordered.
178     *
179     * <p>If either or both endpoints are not already present in this graph, this method will
180     * silently {@link #addNode(Object) add} each missing endpoint to the graph.
181     *
182     * @return this {@code Builder} object
183     * @throws IllegalArgumentException if the introduction of the edge would violate {@link
184     *     #allowsSelfLoops()}
185     * @throws IllegalArgumentException if the endpoints are unordered and the graph is directed
186     */
187    @CanIgnoreReturnValue
188    public Builder<N> putEdge(EndpointPair<N> endpoints) {
189      mutableGraph.putEdge(endpoints);
190      return this;
191    }
192
193    /**
194     * Returns a newly-created {@code ImmutableGraph} based on the contents of this {@code Builder}.
195     */
196    public ImmutableGraph<N> build() {
197      return ImmutableGraph.copyOf(mutableGraph);
198    }
199  }
200}