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
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  @CanIgnoreReturnValue
132  public ValueGraphBuilder<N, V> allowsSelfLoops(boolean allowsSelfLoops) {
133    this.allowsSelfLoops = allowsSelfLoops;
134    return this;
135  }
136
137  /**
138   * Specifies the expected number of nodes in the graph.
139   *
140   * @throws IllegalArgumentException if {@code expectedNodeCount} is negative
141   */
142  @CanIgnoreReturnValue
143  public ValueGraphBuilder<N, V> expectedNodeCount(int expectedNodeCount) {
144    this.expectedNodeCount = Optional.of(checkNonNegative(expectedNodeCount));
145    return this;
146  }
147
148  /**
149   * Specifies the order of iteration for the elements of {@link Graph#nodes()}.
150   *
151   * <p>The default value is {@link ElementOrder#insertion() insertion order}.
152   */
153  public <N1 extends N> ValueGraphBuilder<N1, V> nodeOrder(ElementOrder<N1> nodeOrder) {
154    ValueGraphBuilder<N1, V> newBuilder = cast();
155    newBuilder.nodeOrder = checkNotNull(nodeOrder);
156    return newBuilder;
157  }
158
159  /**
160   * Specifies the order of iteration for the elements of {@link ValueGraph#edges()}, {@link
161   * ValueGraph#adjacentNodes(Object)}, {@link ValueGraph#predecessors(Object)}, {@link
162   * ValueGraph#successors(Object)} and {@link ValueGraph#incidentEdges(Object)}.
163   *
164   * <p>The default value is {@link ElementOrder#unordered() unordered} for mutable graphs. For
165   * immutable graphs, this value is ignored; they always have a {@link ElementOrder#stable()
166   * stable} order.
167   *
168   * @throws IllegalArgumentException if {@code incidentEdgeOrder} is not either {@code
169   *     ElementOrder.unordered()} or {@code ElementOrder.stable()}.
170   * @since 29.0
171   */
172  public <N1 extends N> ValueGraphBuilder<N1, V> incidentEdgeOrder(
173      ElementOrder<N1> incidentEdgeOrder) {
174    checkArgument(
175        incidentEdgeOrder.type() == ElementOrder.Type.UNORDERED
176            || incidentEdgeOrder.type() == ElementOrder.Type.STABLE,
177        "The given elementOrder (%s) is unsupported. incidentEdgeOrder() only supports"
178            + " ElementOrder.unordered() and ElementOrder.stable().",
179        incidentEdgeOrder);
180    ValueGraphBuilder<N1, V> newBuilder = cast();
181    newBuilder.incidentEdgeOrder = checkNotNull(incidentEdgeOrder);
182    return newBuilder;
183  }
184  /**
185   * Returns an empty {@link MutableValueGraph} with the properties of this {@link
186   * ValueGraphBuilder}.
187   */
188  public <N1 extends N, V1 extends V> MutableValueGraph<N1, V1> build() {
189    return new StandardMutableValueGraph<>(this);
190  }
191
192  ValueGraphBuilder<N, V> copy() {
193    ValueGraphBuilder<N, V> newBuilder = new ValueGraphBuilder<>(directed);
194    newBuilder.allowsSelfLoops = allowsSelfLoops;
195    newBuilder.nodeOrder = nodeOrder;
196    newBuilder.expectedNodeCount = expectedNodeCount;
197    newBuilder.incidentEdgeOrder = incidentEdgeOrder;
198    return newBuilder;
199  }
200
201  @SuppressWarnings("unchecked")
202  private <N1 extends N, V1 extends V> ValueGraphBuilder<N1, V1> cast() {
203    return (ValueGraphBuilder<N1, V1>) this;
204  }
205}