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