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