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.ImmutableCollection;
025import com.google.common.collect.ImmutableMap;
026import com.google.common.collect.Maps;
027import com.google.common.graph.GraphConstants.Presence;
028
029/**
030 * A {@link Graph} whose elements and structural relationships will never change. Instances of this
031 * class may be obtained with {@link #copyOf(Graph)}.
032 *
033 * <p>This class generally provides all of the same guarantees as {@link ImmutableCollection}
034 * (despite not extending {@link ImmutableCollection} itself), including guaranteed thread-safety.
035 *
036 * @author James Sexton
037 * @author Joshua O'Madadhain
038 * @author Omar Darwish
039 * @param <N> Node parameter type
040 * @since 20.0
041 */
042@Beta
043public abstract class ImmutableGraph<N> extends ForwardingGraph<N> {
044
045  /** To ensure the immutability contract is maintained, there must be no public constructors. */
046  ImmutableGraph() {}
047
048  /** Returns an immutable copy of {@code graph}. */
049  public static <N> ImmutableGraph<N> copyOf(Graph<N> graph) {
050    return (graph instanceof ImmutableGraph)
051        ? (ImmutableGraph<N>) graph
052        : new ValueBackedImpl<N, Presence>(
053            GraphBuilder.from(graph), getNodeConnections(graph), graph.edges().size());
054  }
055
056  /**
057   * Simply returns its argument.
058   *
059   * @deprecated no need to use this
060   */
061  @Deprecated
062  public static <N> ImmutableGraph<N> copyOf(ImmutableGraph<N> graph) {
063    return checkNotNull(graph);
064  }
065
066  private static <N> ImmutableMap<N, GraphConnections<N, Presence>> getNodeConnections(
067      Graph<N> graph) {
068    // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have
069    // whatever ordering the graph's nodes do, so ImmutableSortedMap is unnecessary even if the
070    // input nodes are sorted.
071    ImmutableMap.Builder<N, GraphConnections<N, Presence>> nodeConnections = ImmutableMap.builder();
072    for (N node : graph.nodes()) {
073      nodeConnections.put(node, connectionsOf(graph, node));
074    }
075    return nodeConnections.build();
076  }
077
078  private static <N> GraphConnections<N, Presence> connectionsOf(Graph<N> graph, N node) {
079    Function<Object, Presence> edgeValueFn = Functions.constant(Presence.EDGE_EXISTS);
080    return graph.isDirected()
081        ? DirectedGraphConnections.ofImmutable(
082            graph.predecessors(node), Maps.asMap(graph.successors(node), edgeValueFn))
083        : UndirectedGraphConnections.ofImmutable(
084            Maps.asMap(graph.adjacentNodes(node), edgeValueFn));
085  }
086
087  static class ValueBackedImpl<N, V> extends ImmutableGraph<N> {
088    protected final ValueGraph<N, V> backingValueGraph;
089
090    ValueBackedImpl(
091        AbstractGraphBuilder<? super N> builder,
092        ImmutableMap<N, GraphConnections<N, V>> nodeConnections,
093        long edgeCount) {
094      this.backingValueGraph =
095          new ConfigurableValueGraph<N, V>(builder, nodeConnections, edgeCount);
096    }
097
098    @Override
099    protected Graph<N> delegate() {
100      return backingValueGraph;
101    }
102  }
103}