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; 020 021import com.google.common.annotations.Beta; 022import com.google.common.base.Function; 023import com.google.common.collect.ImmutableMap; 024import com.google.common.collect.Maps; 025import com.google.errorprone.annotations.CanIgnoreReturnValue; 026import com.google.errorprone.annotations.Immutable; 027 028/** 029 * A {@link ValueGraph} whose elements and structural relationships will never change. Instances of 030 * this class may be obtained with {@link #copyOf(ValueGraph)}. 031 * 032 * <p>See the Guava User's Guide's <a 033 * href="https://github.com/google/guava/wiki/GraphsExplained#immutable-implementations">discussion 034 * of the {@code Immutable*} types</a> for more information on the properties and guarantees 035 * provided by this class. 036 * 037 * @author James Sexton 038 * @author Jens Nyman 039 * @param <N> Node parameter type 040 * @param <V> Value parameter type 041 * @since 20.0 042 */ 043@Beta 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 @Deprecated 065 public static <N, V> ImmutableValueGraph<N, V> copyOf(ImmutableValueGraph<N, V> graph) { 066 return checkNotNull(graph); 067 } 068 069 @Override 070 public ElementOrder<N> incidentEdgeOrder() { 071 return ElementOrder.stable(); 072 } 073 074 @Override 075 public ImmutableGraph<N> asGraph() { 076 return new ImmutableGraph<N>(this); // safe because the view is effectively immutable 077 } 078 079 private static <N, V> ImmutableMap<N, GraphConnections<N, V>> getNodeConnections( 080 ValueGraph<N, V> graph) { 081 // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have 082 // whatever ordering the graph's nodes do, so ImmutableSortedMap is unnecessary even if the 083 // input nodes are sorted. 084 ImmutableMap.Builder<N, GraphConnections<N, V>> nodeConnections = ImmutableMap.builder(); 085 for (N node : graph.nodes()) { 086 nodeConnections.put(node, connectionsOf(graph, node)); 087 } 088 return nodeConnections.build(); 089 } 090 091 private static <N, V> GraphConnections<N, V> connectionsOf( 092 final ValueGraph<N, V> graph, final N node) { 093 Function<N, V> successorNodeToValueFn = 094 new Function<N, V>() { 095 @Override 096 public V apply(N successorNode) { 097 return graph.edgeValueOrDefault(node, successorNode, null); 098 } 099 }; 100 return graph.isDirected() 101 ? DirectedGraphConnections.ofImmutable( 102 node, graph.incidentEdges(node), successorNodeToValueFn) 103 : UndirectedGraphConnections.ofImmutable( 104 Maps.asMap(graph.adjacentNodes(node), successorNodeToValueFn)); 105 } 106 107 /** 108 * A builder for creating {@link ImmutableValueGraph} instances, especially {@code static final} 109 * graphs. Example: 110 * 111 * <pre>{@code 112 * static final ImmutableValueGraph<City, Distance> CITY_ROAD_DISTANCE_GRAPH = 113 * ValueGraphBuilder.undirected() 114 * .<City, Distance>immutable() 115 * .putEdgeValue(PARIS, BERLIN, kilometers(1060)) 116 * .putEdgeValue(PARIS, BRUSSELS, kilometers(317)) 117 * .putEdgeValue(BERLIN, BRUSSELS, kilometers(764)) 118 * .addNode(REYKJAVIK) 119 * .build(); 120 * }</pre> 121 * 122 * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build 123 * multiple graphs in series. Each new graph contains all the elements of the ones created before 124 * it. 125 * 126 * @since 28.0 127 */ 128 public static class Builder<N, V> { 129 130 private final MutableValueGraph<N, V> mutableValueGraph; 131 132 Builder(ValueGraphBuilder<N, V> graphBuilder) { 133 // The incidentEdgeOrder for immutable graphs is always stable. However, we don't want to 134 // modify this builder, so we make a copy instead. 135 this.mutableValueGraph = 136 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 ImmutableValueGraph.Builder<N, V> addNode(N node) { 148 mutableValueGraph.addNode(node); 149 return this; 150 } 151 152 /** 153 * Adds an edge connecting {@code nodeU} to {@code nodeV} if one is not already present, and 154 * sets a value for that edge to {@code value} (overwriting the existing value, if any). 155 * 156 * <p>If the graph is directed, the resultant edge will be directed; otherwise, it will be 157 * undirected. 158 * 159 * <p>Values do not have to be unique. However, values must be non-null. 160 * 161 * <p>If {@code nodeU} and {@code nodeV} are not already present in this graph, this method will 162 * silently {@link #addNode(Object) add} {@code nodeU} and {@code nodeV} to the graph. 163 * 164 * @return this {@code Builder} object 165 * @throws IllegalArgumentException if the introduction of the edge would violate {@link 166 * #allowsSelfLoops()} 167 */ 168 @CanIgnoreReturnValue 169 public ImmutableValueGraph.Builder<N, V> putEdgeValue(N nodeU, N nodeV, V value) { 170 mutableValueGraph.putEdgeValue(nodeU, nodeV, value); 171 return this; 172 } 173 174 /** 175 * Adds an edge connecting {@code endpoints} if one is not already present, and sets a value for 176 * that edge to {@code value} (overwriting the existing value, if any). 177 * 178 * <p>If the graph is directed, the resultant edge will be directed; otherwise, it will be 179 * undirected. 180 * 181 * <p>If this graph is directed, {@code endpoints} must be ordered. 182 * 183 * <p>Values do not have to be unique. However, values must be non-null. 184 * 185 * <p>If either or both endpoints are not already present in this graph, this method will 186 * silently {@link #addNode(Object) add} each missing endpoint to the graph. 187 * 188 * @return this {@code Builder} object 189 * @throws IllegalArgumentException if the introduction of the edge would violate {@link 190 * #allowsSelfLoops()} 191 * @throws IllegalArgumentException if the endpoints are unordered and the graph is directed 192 */ 193 @CanIgnoreReturnValue 194 public ImmutableValueGraph.Builder<N, V> putEdgeValue(EndpointPair<N> endpoints, V value) { 195 mutableValueGraph.putEdgeValue(endpoints, value); 196 return this; 197 } 198 199 /** 200 * Returns a newly-created {@code ImmutableValueGraph} based on the contents of this {@code 201 * Builder}. 202 */ 203 public ImmutableValueGraph<N, V> build() { 204 return ImmutableValueGraph.copyOf(mutableValueGraph); 205 } 206 } 207}