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;
020import static com.google.common.graph.Graphs.checkNonNegative;
021
022import com.google.common.annotations.Beta;
023import com.google.common.base.Optional;
024
025/**
026 * A builder for constructing instances of {@link MutableGraph} with user-defined properties.
027 *
028 * <p>A graph built by this class will have the following properties by default:
029 *
030 * <ul>
031 *   <li>does not allow self-loops
032 *   <li>orders {@link Graph#nodes()} in the order in which the elements were added
033 * </ul>
034 *
035 * <p>Example of use:
036 *
037 * <pre>{@code
038 * MutableGraph<String> graph = GraphBuilder.undirected().allowsSelfLoops(true).build();
039 * graph.putEdge("bread", "bread");
040 * graph.putEdge("chocolate", "peanut butter");
041 * graph.putEdge("peanut butter", "jelly");
042 * }</pre>
043 *
044 * @author James Sexton
045 * @author Joshua O'Madadhain
046 * @param <N> The most general node type this builder will support. This is normally {@code Object}
047 *     unless it is constrained by using a method like {@link #nodeOrder}, or the builder is
048 *     constructed based on an existing {@code Graph} using {@link #from(Graph)}.
049 * @since 20.0
050 */
051@Beta
052public final class GraphBuilder<N> extends AbstractGraphBuilder<N> {
053
054  /** Creates a new instance with the specified edge directionality. */
055  private GraphBuilder(boolean directed) {
056    super(directed);
057  }
058
059  /** Returns a {@link GraphBuilder} for building directed graphs. */
060  public static GraphBuilder<Object> directed() {
061    return new GraphBuilder<>(true);
062  }
063
064  /** Returns a {@link GraphBuilder} for building undirected graphs. */
065  public static GraphBuilder<Object> undirected() {
066    return new GraphBuilder<>(false);
067  }
068
069  /**
070   * Returns a {@link GraphBuilder} initialized with all properties queryable from {@code graph}.
071   *
072   * <p>The "queryable" properties are those that are exposed through the {@link Graph} interface,
073   * such as {@link Graph#isDirected()}. Other properties, such as {@link #expectedNodeCount(int)},
074   * are not set in the new builder.
075   */
076  public static <N> GraphBuilder<N> from(Graph<N> graph) {
077    return new GraphBuilder<N>(graph.isDirected())
078        .allowsSelfLoops(graph.allowsSelfLoops())
079        .nodeOrder(graph.nodeOrder());
080  }
081
082  /**
083   * Specifies whether the graph will allow self-loops (edges that connect a node to itself).
084   * Attempting to add a self-loop to a graph that does not allow them will throw an {@link
085   * UnsupportedOperationException}.
086   */
087  public GraphBuilder<N> allowsSelfLoops(boolean allowsSelfLoops) {
088    this.allowsSelfLoops = allowsSelfLoops;
089    return this;
090  }
091
092  /**
093   * Specifies the expected number of nodes in the graph.
094   *
095   * @throws IllegalArgumentException if {@code expectedNodeCount} is negative
096   */
097  public GraphBuilder<N> expectedNodeCount(int expectedNodeCount) {
098    this.expectedNodeCount = Optional.of(checkNonNegative(expectedNodeCount));
099    return this;
100  }
101
102  /** Specifies the order of iteration for the elements of {@link Graph#nodes()}. */
103  public <N1 extends N> GraphBuilder<N1> nodeOrder(ElementOrder<N1> nodeOrder) {
104    GraphBuilder<N1> newBuilder = cast();
105    newBuilder.nodeOrder = checkNotNull(nodeOrder);
106    return newBuilder;
107  }
108
109  /** Returns an empty {@link MutableGraph} with the properties of this {@link GraphBuilder}. */
110  public <N1 extends N> MutableGraph<N1> build() {
111    return new ConfigurableMutableGraph<N1>(this);
112  }
113
114  @SuppressWarnings("unchecked")
115  private <N1 extends N> GraphBuilder<N1> cast() {
116    return (GraphBuilder<N1>) this;
117  }
118}