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