001/* 002 * Copyright (C) 2016 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; 021import static java.util.Objects.requireNonNull; 022 023import com.google.common.base.Function; 024import com.google.common.collect.ImmutableMap; 025import com.google.errorprone.annotations.CanIgnoreReturnValue; 026import com.google.errorprone.annotations.Immutable; 027import com.google.errorprone.annotations.InlineMe; 028 029/** 030 * A {@link ValueGraph} whose elements and structural relationships will never change. Instances of 031 * this class may be obtained with {@link #copyOf(ValueGraph)}. 032 * 033 * <p>See the Guava User's Guide's <a 034 * href="https://github.com/google/guava/wiki/GraphsExplained#immutable-implementations">discussion 035 * of the {@code Immutable*} types</a> for more information on the properties and guarantees 036 * provided by this class. 037 * 038 * @author James Sexton 039 * @author Jens Nyman 040 * @param <N> Node parameter type 041 * @param <V> Value parameter type 042 * @since 20.0 043 */ 044@Immutable(containerOf = {"N", "V"}) 045@SuppressWarnings("Immutable") // Extends StandardValueGraph but uses ImmutableMaps. 046public final class ImmutableValueGraph<N, V> extends StandardValueGraph<N, V> { 047 048 private ImmutableValueGraph(ValueGraph<N, V> graph) { 049 super(ValueGraphBuilder.from(graph), getNodeConnections(graph), graph.edges().size()); 050 } 051 052 /** Returns an immutable copy of {@code graph}. */ 053 public static <N, V> ImmutableValueGraph<N, V> copyOf(ValueGraph<N, V> graph) { 054 return (graph instanceof ImmutableValueGraph) 055 ? (ImmutableValueGraph<N, V>) graph 056 : new ImmutableValueGraph<N, V>(graph); 057 } 058 059 /** 060 * Simply returns its argument. 061 * 062 * @deprecated no need to use this 063 */ 064 @InlineMe( 065 replacement = "checkNotNull(graph)", 066 staticImports = "com.google.common.base.Preconditions.checkNotNull") 067 @Deprecated 068 public static <N, V> ImmutableValueGraph<N, V> copyOf(ImmutableValueGraph<N, V> graph) { 069 return checkNotNull(graph); 070 } 071 072 @Override 073 public ElementOrder<N> incidentEdgeOrder() { 074 return ElementOrder.stable(); 075 } 076 077 @Override 078 public ImmutableGraph<N> asGraph() { 079 return new ImmutableGraph<>(this); // safe because the view is effectively immutable 080 } 081 082 private static <N, V> ImmutableMap<N, GraphConnections<N, V>> getNodeConnections( 083 ValueGraph<N, V> 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, V>> nodeConnections = ImmutableMap.builder(); 088 for (N node : graph.nodes()) { 089 nodeConnections.put(node, connectionsOf(graph, node)); 090 } 091 return nodeConnections.buildOrThrow(); 092 } 093 094 private static <N, V> GraphConnections<N, V> connectionsOf(ValueGraph<N, V> graph, N node) { 095 Function<N, V> successorNodeToValueFn = 096 (N successorNode) -> 097 // requireNonNull is safe because the endpoint pair comes from the graph. 098 requireNonNull(graph.edgeValueOrDefault(node, successorNode, null)); 099 return graph.isDirected() 100 ? DirectedGraphConnections.ofImmutable( 101 node, graph.incidentEdges(node), successorNodeToValueFn) 102 : UndirectedGraphConnections.ofImmutable( 103 asMap(graph.adjacentNodes(node), successorNodeToValueFn)); 104 } 105 106 /** 107 * A builder for creating {@link ImmutableValueGraph} instances, especially {@code static final} 108 * graphs. Example: 109 * 110 * {@snippet : 111 * static final ImmutableValueGraph<City, Distance> CITY_ROAD_DISTANCE_GRAPH = 112 * ValueGraphBuilder.undirected() 113 * .<City, Distance>immutable() 114 * .putEdgeValue(PARIS, BERLIN, kilometers(1060)) 115 * .putEdgeValue(PARIS, BRUSSELS, kilometers(317)) 116 * .putEdgeValue(BERLIN, BRUSSELS, kilometers(764)) 117 * .addNode(REYKJAVIK) 118 * .build(); 119 * } 120 * 121 * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build 122 * multiple graphs in series. Each new graph contains all the elements of the ones created before 123 * it. 124 * 125 * @since 28.0 126 */ 127 public static class Builder<N, V> { 128 129 private final MutableValueGraph<N, V> mutableValueGraph; 130 131 Builder(ValueGraphBuilder<N, V> graphBuilder) { 132 // The incidentEdgeOrder for immutable graphs is always stable. However, we don't want to 133 // modify this builder, so we make a copy instead. 134 this.mutableValueGraph = graphBuilder.copy().incidentEdgeOrder(ElementOrder.stable()).build(); 135 } 136 137 /** 138 * Adds {@code node} if it is not already present. 139 * 140 * <p><b>Nodes must be unique</b>, just as {@code Map} keys must be. They must also be non-null. 141 * 142 * @return this {@code Builder} object 143 */ 144 @CanIgnoreReturnValue 145 public ImmutableValueGraph.Builder<N, V> addNode(N node) { 146 mutableValueGraph.addNode(node); 147 return this; 148 } 149 150 /** 151 * Adds an edge connecting {@code nodeU} to {@code nodeV} if one is not already present, and 152 * sets a value for that edge to {@code value} (overwriting the existing value, if any). 153 * 154 * <p>If the graph is directed, the resultant edge will be directed; otherwise, it will be 155 * undirected. 156 * 157 * <p>Values do not have to be unique. However, values must be non-null. 158 * 159 * <p>If {@code nodeU} and {@code nodeV} are not already present in this graph, this method will 160 * silently {@link #addNode(Object) add} {@code nodeU} and {@code nodeV} to the graph. 161 * 162 * @return this {@code Builder} object 163 * @throws IllegalArgumentException if the introduction of the edge would violate {@link 164 * #allowsSelfLoops()} 165 */ 166 @CanIgnoreReturnValue 167 public ImmutableValueGraph.Builder<N, V> putEdgeValue(N nodeU, N nodeV, V value) { 168 mutableValueGraph.putEdgeValue(nodeU, nodeV, value); 169 return this; 170 } 171 172 /** 173 * Adds an edge connecting {@code endpoints} if one is not already present, and sets a value for 174 * that edge to {@code value} (overwriting the existing value, if any). 175 * 176 * <p>If the graph is directed, the resultant edge will be directed; otherwise, it will be 177 * undirected. 178 * 179 * <p>If this graph is directed, {@code endpoints} must be ordered. 180 * 181 * <p>Values do not have to be unique. However, values must be non-null. 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 ImmutableValueGraph.Builder<N, V> putEdgeValue(EndpointPair<N> endpoints, V value) { 193 mutableValueGraph.putEdgeValue(endpoints, value); 194 return this; 195 } 196 197 /** 198 * Returns a newly-created {@code ImmutableValueGraph} based on the contents of this {@code 199 * Builder}. 200 */ 201 public ImmutableValueGraph<N, V> build() { 202 return copyOf(mutableValueGraph); 203 } 204 } 205}