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"})
048@ElementTypesAreNonnullByDefault
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  @Deprecated
072  public static <N> ImmutableGraph<N> copyOf(ImmutableGraph<N> graph) {
073    return checkNotNull(graph);
074  }
075
076  @Override
077  public ElementOrder<N> incidentEdgeOrder() {
078    return ElementOrder.stable();
079  }
080
081  private static <N> ImmutableMap<N, GraphConnections<N, Presence>> getNodeConnections(
082      Graph<N> graph) {
083    // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have
084    // whatever ordering the graph's nodes do, so ImmutableSortedMap is unnecessary even if the
085    // input nodes are sorted.
086    ImmutableMap.Builder<N, GraphConnections<N, Presence>> nodeConnections = ImmutableMap.builder();
087    for (N node : graph.nodes()) {
088      nodeConnections.put(node, connectionsOf(graph, node));
089    }
090    return nodeConnections.build();
091  }
092
093  @SuppressWarnings("unchecked")
094  private static <N> GraphConnections<N, Presence> connectionsOf(Graph<N> graph, N node) {
095    Function<N, Presence> edgeValueFn =
096        (Function<N, Presence>) Functions.constant(Presence.EDGE_EXISTS);
097    return graph.isDirected()
098        ? DirectedGraphConnections.ofImmutable(node, graph.incidentEdges(node), edgeValueFn)
099        : UndirectedGraphConnections.ofImmutable(
100            Maps.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   * <pre>{@code
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   * }</pre>
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.<N>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 ImmutableGraph.copyOf(mutableGraph);
199    }
200  }
201}