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.Immutable;
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>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 Joshua O'Madadhain
040 * @author Omar Darwish
041 * @param <N> Node parameter type
042 * @since 20.0
043 */
044@Beta
045public abstract class ImmutableGraph<N> extends ForwardingGraph<N> {
046
047  /** To ensure the immutability contract is maintained, there must be no public constructors. */
048  ImmutableGraph() {}
049
050  /** Returns an immutable copy of {@code graph}. */
051  public static <N> ImmutableGraph<N> copyOf(Graph<N> graph) {
052    return (graph instanceof ImmutableGraph)
053        ? (ImmutableGraph<N>) graph
054        : new ValueBackedImpl<N, Presence>(
055            GraphBuilder.from(graph), getNodeConnections(graph), graph.edges().size());
056  }
057
058  /**
059   * Simply returns its argument.
060   *
061   * @deprecated no need to use this
062   */
063  @Deprecated
064  public static <N> ImmutableGraph<N> copyOf(ImmutableGraph<N> graph) {
065    return checkNotNull(graph);
066  }
067
068  private static <N> ImmutableMap<N, GraphConnections<N, Presence>> getNodeConnections(
069      Graph<N> graph) {
070    // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have
071    // whatever ordering the graph's nodes do, so ImmutableSortedMap is unnecessary even if the
072    // input nodes are sorted.
073    ImmutableMap.Builder<N, GraphConnections<N, Presence>> nodeConnections = ImmutableMap.builder();
074    for (N node : graph.nodes()) {
075      nodeConnections.put(node, connectionsOf(graph, node));
076    }
077    return nodeConnections.build();
078  }
079
080  private static <N> GraphConnections<N, Presence> connectionsOf(Graph<N> graph, N node) {
081    Function<Object, Presence> edgeValueFn = Functions.constant(Presence.EDGE_EXISTS);
082    return graph.isDirected()
083        ? DirectedGraphConnections.ofImmutable(
084            graph.predecessors(node), Maps.asMap(graph.successors(node), edgeValueFn))
085        : UndirectedGraphConnections.ofImmutable(
086            Maps.asMap(graph.adjacentNodes(node), edgeValueFn));
087  }
088
089  static class ValueBackedImpl<N, V> extends ImmutableGraph<N> {
090    protected final ValueGraph<N, V> backingValueGraph;
091
092    ValueBackedImpl(
093        AbstractGraphBuilder<? super N> builder,
094        ImmutableMap<N, GraphConnections<N, V>> nodeConnections,
095        long edgeCount) {
096      this.backingValueGraph =
097          new ConfigurableValueGraph<N, V>(builder, nodeConnections, edgeCount);
098    }
099
100    @Override
101    protected Graph<N> delegate() {
102      return backingValueGraph;
103    }
104  }
105}