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.checkArgument;
020import static com.google.common.base.Preconditions.checkNotNull;
021import static com.google.common.graph.Graphs.checkNonNegative;
022
023import com.google.common.annotations.Beta;
024import com.google.common.base.Optional;
025import com.google.errorprone.annotations.CanIgnoreReturnValue;
026import com.google.errorprone.annotations.DoNotMock;
027
028/**
029 * A builder for constructing instances of {@link MutableGraph} or {@link ImmutableGraph} with
030 * user-defined properties.
031 *
032 * <p>A {@code Graph} built by this class has the following default properties:
033 *
034 * <ul>
035 *   <li>does not allow self-loops
036 *   <li>orders {@link Graph#nodes()} in the order in which the elements were added (insertion
037 *       order)
038 * </ul>
039 *
040 * <p>{@code Graph}s built by this class also guarantee that each collection-returning accessor
041 * returns a <b>(live) unmodifiable view</b>; see <a
042 * href="https://github.com/google/guava/wiki/GraphsExplained#accessor-behavior">the external
043 * documentation</a> for details.
044 *
045 * <p>Examples of use:
046 *
047 * <pre>{@code
048 * // Building a mutable graph
049 * MutableGraph<String> graph = GraphBuilder.undirected().allowsSelfLoops(true).build();
050 * graph.putEdge("bread", "bread");
051 * graph.putEdge("chocolate", "peanut butter");
052 * graph.putEdge("peanut butter", "jelly");
053 *
054 * // Building an immutable graph
055 * ImmutableGraph<String> immutableGraph =
056 *     GraphBuilder.undirected()
057 *         .allowsSelfLoops(true)
058 *         .<String>immutable()
059 *         .putEdge("bread", "bread")
060 *         .putEdge("chocolate", "peanut butter")
061 *         .putEdge("peanut butter", "jelly")
062 *         .build();
063 * }</pre>
064 *
065 * @author James Sexton
066 * @author Joshua O'Madadhain
067 * @param <N> The most general node type this builder will support. This is normally {@code Object}
068 *     unless it is constrained by using a method like {@link #nodeOrder}, or the builder is
069 *     constructed based on an existing {@code Graph} using {@link #from(Graph)}.
070 * @since 20.0
071 */
072@Beta
073@DoNotMock
074@ElementTypesAreNonnullByDefault
075public final class GraphBuilder<N> extends AbstractGraphBuilder<N> {
076
077  /** Creates a new instance with the specified edge directionality. */
078  private GraphBuilder(boolean directed) {
079    super(directed);
080  }
081
082  /** Returns a {@link GraphBuilder} for building directed graphs. */
083  public static GraphBuilder<Object> directed() {
084    return new GraphBuilder<>(true);
085  }
086
087  /** Returns a {@link GraphBuilder} for building undirected graphs. */
088  public static GraphBuilder<Object> undirected() {
089    return new GraphBuilder<>(false);
090  }
091
092  /**
093   * Returns a {@link GraphBuilder} initialized with all properties queryable from {@code graph}.
094   *
095   * <p>The "queryable" properties are those that are exposed through the {@link Graph} interface,
096   * such as {@link Graph#isDirected()}. Other properties, such as {@link #expectedNodeCount(int)},
097   * are not set in the new builder.
098   */
099  public static <N> GraphBuilder<N> from(Graph<N> graph) {
100    return new GraphBuilder<N>(graph.isDirected())
101        .allowsSelfLoops(graph.allowsSelfLoops())
102        .nodeOrder(graph.nodeOrder())
103        .incidentEdgeOrder(graph.incidentEdgeOrder());
104  }
105
106  /**
107   * Returns an {@link ImmutableGraph.Builder} with the properties of this {@link GraphBuilder}.
108   *
109   * <p>The returned builder can be used for populating an {@link ImmutableGraph}.
110   *
111   * <p>Note that the returned builder will always have {@link #incidentEdgeOrder} set to {@link
112   * ElementOrder#stable()}, regardless of the value that was set in this builder.
113   *
114   * @since 28.0
115   */
116  public <N1 extends N> ImmutableGraph.Builder<N1> immutable() {
117    GraphBuilder<N1> castBuilder = cast();
118    return new ImmutableGraph.Builder<>(castBuilder);
119  }
120
121  /**
122   * Specifies whether the graph will allow self-loops (edges that connect a node to itself).
123   * Attempting to add a self-loop to a graph that does not allow them will throw an {@link
124   * UnsupportedOperationException}.
125   *
126   * <p>The default value is {@code false}.
127   */
128  @CanIgnoreReturnValue
129  public GraphBuilder<N> allowsSelfLoops(boolean allowsSelfLoops) {
130    this.allowsSelfLoops = allowsSelfLoops;
131    return this;
132  }
133
134  /**
135   * Specifies the expected number of nodes in the graph.
136   *
137   * @throws IllegalArgumentException if {@code expectedNodeCount} is negative
138   */
139  @CanIgnoreReturnValue
140  public GraphBuilder<N> expectedNodeCount(int expectedNodeCount) {
141    this.expectedNodeCount = Optional.of(checkNonNegative(expectedNodeCount));
142    return this;
143  }
144
145  /**
146   * Specifies the order of iteration for the elements of {@link Graph#nodes()}.
147   *
148   * <p>The default value is {@link ElementOrder#insertion() insertion order}.
149   */
150  public <N1 extends N> GraphBuilder<N1> nodeOrder(ElementOrder<N1> nodeOrder) {
151    GraphBuilder<N1> newBuilder = cast();
152    newBuilder.nodeOrder = checkNotNull(nodeOrder);
153    return newBuilder;
154  }
155
156  /**
157   * Specifies the order of iteration for the elements of {@link Graph#edges()}, {@link
158   * Graph#adjacentNodes(Object)}, {@link Graph#predecessors(Object)}, {@link
159   * Graph#successors(Object)} and {@link Graph#incidentEdges(Object)}.
160   *
161   * <p>The default value is {@link ElementOrder#unordered() unordered} for mutable graphs. For
162   * immutable graphs, this value is ignored; they always have a {@link ElementOrder#stable()
163   * stable} order.
164   *
165   * @throws IllegalArgumentException if {@code incidentEdgeOrder} is not either {@code
166   *     ElementOrder.unordered()} or {@code ElementOrder.stable()}.
167   * @since 29.0
168   */
169  public <N1 extends N> GraphBuilder<N1> incidentEdgeOrder(ElementOrder<N1> incidentEdgeOrder) {
170    checkArgument(
171        incidentEdgeOrder.type() == ElementOrder.Type.UNORDERED
172            || incidentEdgeOrder.type() == ElementOrder.Type.STABLE,
173        "The given elementOrder (%s) is unsupported. incidentEdgeOrder() only supports"
174            + " ElementOrder.unordered() and ElementOrder.stable().",
175        incidentEdgeOrder);
176    GraphBuilder<N1> newBuilder = cast();
177    newBuilder.incidentEdgeOrder = checkNotNull(incidentEdgeOrder);
178    return newBuilder;
179  }
180
181  /** Returns an empty {@link MutableGraph} with the properties of this {@link GraphBuilder}. */
182  public <N1 extends N> MutableGraph<N1> build() {
183    return new StandardMutableGraph<>(this);
184  }
185
186  GraphBuilder<N> copy() {
187    GraphBuilder<N> newBuilder = new GraphBuilder<>(directed);
188    newBuilder.allowsSelfLoops = allowsSelfLoops;
189    newBuilder.nodeOrder = nodeOrder;
190    newBuilder.expectedNodeCount = expectedNodeCount;
191    newBuilder.incidentEdgeOrder = incidentEdgeOrder;
192    return newBuilder;
193  }
194
195  @SuppressWarnings("unchecked")
196  private <N1 extends N> GraphBuilder<N1> cast() {
197    return (GraphBuilder<N1>) this;
198  }
199}