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