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