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