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