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 ConfigurableValueGraph<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 private static <N> ImmutableMap<N, GraphConnections<N, Presence>> getNodeConnections( 076 Graph<N> graph) { 077 // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have 078 // whatever ordering the graph's nodes do, so ImmutableSortedMap is unnecessary even if the 079 // input nodes are sorted. 080 ImmutableMap.Builder<N, GraphConnections<N, Presence>> nodeConnections = ImmutableMap.builder(); 081 for (N node : graph.nodes()) { 082 nodeConnections.put(node, connectionsOf(graph, node)); 083 } 084 return nodeConnections.build(); 085 } 086 087 @SuppressWarnings("unchecked") 088 private static <N> GraphConnections<N, Presence> connectionsOf(Graph<N> graph, N node) { 089 Function<N, Presence> edgeValueFn = 090 (Function<N, Presence>) Functions.constant(Presence.EDGE_EXISTS); 091 return graph.isDirected() 092 ? DirectedGraphConnections.ofImmutable(node, graph.incidentEdges(node), edgeValueFn) 093 : UndirectedGraphConnections.ofImmutable( 094 Maps.asMap(graph.adjacentNodes(node), edgeValueFn)); 095 } 096 097 @Override 098 protected BaseGraph<N> delegate() { 099 return backingGraph; 100 } 101 102 /** 103 * A builder for creating {@link ImmutableGraph} instances, especially {@code static final} 104 * graphs. Example: 105 * 106 * <pre>{@code 107 * static final ImmutableGraph<Country> COUNTRY_ADJACENCY_GRAPH = 108 * GraphBuilder.undirected() 109 * .<Country>immutable() 110 * .putEdge(FRANCE, GERMANY) 111 * .putEdge(FRANCE, BELGIUM) 112 * .putEdge(GERMANY, BELGIUM) 113 * .addNode(ICELAND) 114 * .build(); 115 * }</pre> 116 * 117 * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build 118 * multiple graphs in series. Each new graph contains all the elements of the ones created before 119 * it. 120 * 121 * @since 28.0 122 */ 123 public static class Builder<N> { 124 125 private final MutableGraph<N> mutableGraph; 126 127 Builder(GraphBuilder<N> graphBuilder) { 128 // The incidentEdgeOrder for immutable graphs is always stable. However, we don't want to 129 // modify this builder, so we make a copy instead. 130 this.mutableGraph = graphBuilder.copy().incidentEdgeOrder(ElementOrder.<N>stable()).build(); 131 } 132 133 /** 134 * Adds {@code node} if it is not already present. 135 * 136 * <p><b>Nodes must be unique</b>, just as {@code Map} keys must be. They must also be non-null. 137 * 138 * @return this {@code Builder} object 139 */ 140 @CanIgnoreReturnValue 141 public Builder<N> addNode(N node) { 142 mutableGraph.addNode(node); 143 return this; 144 } 145 146 /** 147 * Adds an edge connecting {@code nodeU} to {@code nodeV} if one is not already present. 148 * 149 * <p>If the graph is directed, the resultant edge will be directed; otherwise, it will be 150 * undirected. 151 * 152 * <p>If {@code nodeU} and {@code nodeV} are not already present in this graph, this method will 153 * silently {@link #addNode(Object) add} {@code nodeU} and {@code nodeV} to the graph. 154 * 155 * @return this {@code Builder} object 156 * @throws IllegalArgumentException if the introduction of the edge would violate {@link 157 * #allowsSelfLoops()} 158 */ 159 @CanIgnoreReturnValue 160 public Builder<N> putEdge(N nodeU, N nodeV) { 161 mutableGraph.putEdge(nodeU, nodeV); 162 return this; 163 } 164 165 /** 166 * Adds an edge connecting {@code endpoints} (in the order, if any, specified by {@code 167 * endpoints}) if one is not already present. 168 * 169 * <p>If this graph is directed, {@code endpoints} must be ordered and the added edge will be 170 * directed; if it is undirected, the added edge will be undirected. 171 * 172 * <p>If this graph is directed, {@code endpoints} must be ordered. 173 * 174 * <p>If either or both endpoints are not already present in this graph, this method will 175 * silently {@link #addNode(Object) add} each missing endpoint to the graph. 176 * 177 * @return this {@code Builder} object 178 * @throws IllegalArgumentException if the introduction of the edge would violate {@link 179 * #allowsSelfLoops()} 180 * @throws IllegalArgumentException if the endpoints are unordered and the graph is directed 181 */ 182 @CanIgnoreReturnValue 183 public Builder<N> putEdge(EndpointPair<N> endpoints) { 184 mutableGraph.putEdge(endpoints); 185 return this; 186 } 187 188 /** 189 * Returns a newly-created {@code ImmutableGraph} based on the contents of this {@code Builder}. 190 */ 191 public ImmutableGraph<N> build() { 192 return ImmutableGraph.copyOf(mutableGraph); 193 } 194 } 195}