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 java.util.Objects.requireNonNull; 021 022import com.google.common.annotations.Beta; 023import com.google.common.base.Function; 024import com.google.common.collect.ImmutableMap; 025import com.google.common.collect.Maps; 026import com.google.errorprone.annotations.CanIgnoreReturnValue; 027import com.google.errorprone.annotations.Immutable; 028import com.google.errorprone.annotations.InlineMe; 029 030/** 031 * A {@link ValueGraph} whose elements and structural relationships will never change. Instances of 032 * this class may be obtained with {@link #copyOf(ValueGraph)}. 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 Jens Nyman 041 * @param <N> Node parameter type 042 * @param <V> Value parameter type 043 * @since 20.0 044 */ 045@Beta 046@Immutable(containerOf = {"N", "V"}) 047@SuppressWarnings("Immutable") // Extends StandardValueGraph but uses ImmutableMaps. 048public final class ImmutableValueGraph<N, V> extends StandardValueGraph<N, V> { 049 050 private ImmutableValueGraph(ValueGraph<N, V> graph) { 051 super(ValueGraphBuilder.from(graph), getNodeConnections(graph), graph.edges().size()); 052 } 053 054 /** Returns an immutable copy of {@code graph}. */ 055 public static <N, V> ImmutableValueGraph<N, V> copyOf(ValueGraph<N, V> graph) { 056 return (graph instanceof ImmutableValueGraph) 057 ? (ImmutableValueGraph<N, V>) graph 058 : new ImmutableValueGraph<N, V>(graph); 059 } 060 061 /** 062 * Simply returns its argument. 063 * 064 * @deprecated no need to use this 065 */ 066 @InlineMe( 067 replacement = "checkNotNull(graph)", 068 staticImports = "com.google.common.base.Preconditions.checkNotNull") 069 @Deprecated 070 public static <N, V> ImmutableValueGraph<N, V> copyOf(ImmutableValueGraph<N, V> graph) { 071 return checkNotNull(graph); 072 } 073 074 @Override 075 public ElementOrder<N> incidentEdgeOrder() { 076 return ElementOrder.stable(); 077 } 078 079 @Override 080 public ImmutableGraph<N> asGraph() { 081 return new ImmutableGraph<>(this); // safe because the view is effectively immutable 082 } 083 084 private static <N, V> ImmutableMap<N, GraphConnections<N, V>> getNodeConnections( 085 ValueGraph<N, V> 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, V>> nodeConnections = ImmutableMap.builder(); 090 for (N node : graph.nodes()) { 091 nodeConnections.put(node, connectionsOf(graph, node)); 092 } 093 return nodeConnections.buildOrThrow(); 094 } 095 096 private static <N, V> GraphConnections<N, V> connectionsOf(ValueGraph<N, V> graph, N node) { 097 Function<N, V> successorNodeToValueFn = 098 (N successorNode) -> 099 // requireNonNull is safe because the endpoint pair comes from the graph. 100 requireNonNull(graph.edgeValueOrDefault(node, successorNode, null)); 101 return graph.isDirected() 102 ? DirectedGraphConnections.ofImmutable( 103 node, graph.incidentEdges(node), successorNodeToValueFn) 104 : UndirectedGraphConnections.ofImmutable( 105 Maps.asMap(graph.adjacentNodes(node), successorNodeToValueFn)); 106 } 107 108 /** 109 * A builder for creating {@link ImmutableValueGraph} instances, especially {@code static final} 110 * graphs. Example: 111 * 112 * <pre>{@code 113 * static final ImmutableValueGraph<City, Distance> CITY_ROAD_DISTANCE_GRAPH = 114 * ValueGraphBuilder.undirected() 115 * .<City, Distance>immutable() 116 * .putEdgeValue(PARIS, BERLIN, kilometers(1060)) 117 * .putEdgeValue(PARIS, BRUSSELS, kilometers(317)) 118 * .putEdgeValue(BERLIN, BRUSSELS, kilometers(764)) 119 * .addNode(REYKJAVIK) 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, V> { 130 131 private final MutableValueGraph<N, V> mutableValueGraph; 132 133 Builder(ValueGraphBuilder<N, V> 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.mutableValueGraph = 137 graphBuilder.copy().incidentEdgeOrder(ElementOrder.<N>stable()).build(); 138 } 139 140 /** 141 * Adds {@code node} if it is not already present. 142 * 143 * <p><b>Nodes must be unique</b>, just as {@code Map} keys must be. They must also be non-null. 144 * 145 * @return this {@code Builder} object 146 */ 147 @CanIgnoreReturnValue 148 public ImmutableValueGraph.Builder<N, V> addNode(N node) { 149 mutableValueGraph.addNode(node); 150 return this; 151 } 152 153 /** 154 * Adds an edge connecting {@code nodeU} to {@code nodeV} if one is not already present, and 155 * sets a value for that edge to {@code value} (overwriting the existing value, if any). 156 * 157 * <p>If the graph is directed, the resultant edge will be directed; otherwise, it will be 158 * undirected. 159 * 160 * <p>Values do not have to be unique. However, values must be non-null. 161 * 162 * <p>If {@code nodeU} and {@code nodeV} are not already present in this graph, this method will 163 * silently {@link #addNode(Object) add} {@code nodeU} and {@code nodeV} to the graph. 164 * 165 * @return this {@code Builder} object 166 * @throws IllegalArgumentException if the introduction of the edge would violate {@link 167 * #allowsSelfLoops()} 168 */ 169 @CanIgnoreReturnValue 170 public ImmutableValueGraph.Builder<N, V> putEdgeValue(N nodeU, N nodeV, V value) { 171 mutableValueGraph.putEdgeValue(nodeU, nodeV, value); 172 return this; 173 } 174 175 /** 176 * Adds an edge connecting {@code endpoints} if one is not already present, and sets a value for 177 * that edge to {@code value} (overwriting the existing value, if any). 178 * 179 * <p>If the graph is directed, the resultant edge will be directed; otherwise, it will be 180 * undirected. 181 * 182 * <p>If this graph is directed, {@code endpoints} must be ordered. 183 * 184 * <p>Values do not have to be unique. However, values must be non-null. 185 * 186 * <p>If either or both endpoints are not already present in this graph, this method will 187 * silently {@link #addNode(Object) add} each missing endpoint to the graph. 188 * 189 * @return this {@code Builder} object 190 * @throws IllegalArgumentException if the introduction of the edge would violate {@link 191 * #allowsSelfLoops()} 192 * @throws IllegalArgumentException if the endpoints are unordered and the graph is directed 193 */ 194 @CanIgnoreReturnValue 195 public ImmutableValueGraph.Builder<N, V> putEdgeValue(EndpointPair<N> endpoints, V value) { 196 mutableValueGraph.putEdgeValue(endpoints, value); 197 return this; 198 } 199 200 /** 201 * Returns a newly-created {@code ImmutableValueGraph} based on the contents of this {@code 202 * Builder}. 203 */ 204 public ImmutableValueGraph<N, V> build() { 205 return ImmutableValueGraph.copyOf(mutableValueGraph); 206 } 207 } 208}