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.base.Preconditions.checkState;
021
022import com.google.common.annotations.Beta;
023import com.google.common.base.MoreObjects;
024import com.google.common.base.MoreObjects.ToStringHelper;
025import com.google.common.base.Objects;
026import com.google.common.collect.Maps;
027import com.google.common.collect.Ordering;
028import com.google.errorprone.annotations.Immutable;
029import java.util.Comparator;
030import java.util.Map;
031import org.checkerframework.checker.nullness.qual.Nullable;
032
033/**
034 * Used to represent the order of elements in a data structure that supports different options for
035 * iteration order guarantees.
036 *
037 * <p>Example usage:
038 *
039 * <pre>{@code
040 * MutableGraph<Integer> graph =
041 *     GraphBuilder.directed().nodeOrder(ElementOrder.<Integer>natural()).build();
042 * }</pre>
043 *
044 * @author Joshua O'Madadhain
045 * @since 20.0
046 */
047@Beta
048@Immutable
049public final class ElementOrder<T> {
050  private final Type type;
051
052  @SuppressWarnings("Immutable") // Hopefully the comparator provided is immutable!
053  private final @Nullable Comparator<T> comparator;
054
055  /**
056   * The type of ordering that this object specifies.
057   *
058   * <ul>
059   *   <li>UNORDERED: no order is guaranteed.
060   *   <li>STABLE: ordering is guaranteed to follow a pattern that won't change between releases.
061   *       Some methods may have stronger guarantees.
062   *   <li>INSERTION: insertion ordering is guaranteed.
063   *   <li>SORTED: ordering according to a supplied comparator is guaranteed.
064   * </ul>
065   */
066  public enum Type {
067    UNORDERED,
068    STABLE,
069    INSERTION,
070    SORTED
071  }
072
073  private ElementOrder(Type type, @Nullable Comparator<T> comparator) {
074    this.type = checkNotNull(type);
075    this.comparator = comparator;
076    checkState((type == Type.SORTED) == (comparator != null));
077  }
078
079  /** Returns an instance which specifies that no ordering is guaranteed. */
080  public static <S> ElementOrder<S> unordered() {
081    return new ElementOrder<S>(Type.UNORDERED, null);
082  }
083
084  /**
085   * Returns an instance which specifies that ordering is guaranteed to be always be the same across
086   * iterations, and across releases. Some methods may have stronger guarantees.
087   *
088   * <p>This instance is only useful in combination with {@code incidentEdgeOrder}, e.g. {@code
089   * graphBuilder.incidentEdgeOrder(ElementOrder.stable())}.
090   *
091   * <h3>In combination with {@code incidentEdgeOrder}</h3>
092   *
093   * <p>{@code incidentEdgeOrder(ElementOrder.stable())} guarantees the ordering of the returned
094   * collections of the following methods:
095   *
096   * <ul>
097   *   <li>For {@link Graph} and {@link ValueGraph}:
098   *       <ul>
099   *         <li>{@code edges()}: Stable order
100   *         <li>{@code adjacentNodes(node)}: Connecting edge insertion order
101   *         <li>{@code predecessors(node)}: Connecting edge insertion order
102   *         <li>{@code successors(node)}: Connecting edge insertion order
103   *         <li>{@code incidentEdges(node)}: Edge insertion order
104   *       </ul>
105   *   <li>For {@link Network}:
106   *       <ul>
107   *         <li>{@code adjacentNodes(node)}: Stable order
108   *         <li>{@code predecessors(node)}: Connecting edge insertion order
109   *         <li>{@code successors(node)}: Connecting edge insertion order
110   *         <li>{@code incidentEdges(node)}: Stable order
111   *         <li>{@code inEdges(node)}: Edge insertion order
112   *         <li>{@code outEdges(node)}: Edge insertion order
113   *         <li>{@code adjacentEdges(edge)}: Stable order
114   *         <li>{@code edgesConnecting(nodeU, nodeV)}: Edge insertion order
115   *       </ul>
116   * </ul>
117   */
118  public static <S> ElementOrder<S> stable() {
119    return new ElementOrder<S>(Type.STABLE, null);
120  }
121
122  /** Returns an instance which specifies that insertion ordering is guaranteed. */
123  public static <S> ElementOrder<S> insertion() {
124    return new ElementOrder<S>(Type.INSERTION, null);
125  }
126
127  /**
128   * Returns an instance which specifies that the natural ordering of the elements is guaranteed.
129   */
130  public static <S extends Comparable<? super S>> ElementOrder<S> natural() {
131    return new ElementOrder<S>(Type.SORTED, Ordering.<S>natural());
132  }
133
134  /**
135   * Returns an instance which specifies that the ordering of the elements is guaranteed to be
136   * determined by {@code comparator}.
137   */
138  public static <S> ElementOrder<S> sorted(Comparator<S> comparator) {
139    return new ElementOrder<S>(Type.SORTED, comparator);
140  }
141
142  /** Returns the type of ordering used. */
143  public Type type() {
144    return type;
145  }
146
147  /**
148   * Returns the {@link Comparator} used.
149   *
150   * @throws UnsupportedOperationException if comparator is not defined
151   */
152  public Comparator<T> comparator() {
153    if (comparator != null) {
154      return comparator;
155    }
156    throw new UnsupportedOperationException("This ordering does not define a comparator.");
157  }
158
159  @Override
160  public boolean equals(@Nullable Object obj) {
161    if (obj == this) {
162      return true;
163    }
164    if (!(obj instanceof ElementOrder)) {
165      return false;
166    }
167
168    ElementOrder<?> other = (ElementOrder<?>) obj;
169    return (type == other.type) && Objects.equal(comparator, other.comparator);
170  }
171
172  @Override
173  public int hashCode() {
174    return Objects.hashCode(type, comparator);
175  }
176
177  @Override
178  public String toString() {
179    ToStringHelper helper = MoreObjects.toStringHelper(this).add("type", type);
180    if (comparator != null) {
181      helper.add("comparator", comparator);
182    }
183    return helper.toString();
184  }
185
186  /** Returns an empty mutable map whose keys will respect this {@link ElementOrder}. */
187  <K extends T, V> Map<K, V> createMap(int expectedSize) {
188    switch (type) {
189      case UNORDERED:
190        return Maps.newHashMapWithExpectedSize(expectedSize);
191      case INSERTION:
192      case STABLE:
193        return Maps.newLinkedHashMapWithExpectedSize(expectedSize);
194      case SORTED:
195        return Maps.newTreeMap(comparator());
196      default:
197        throw new AssertionError();
198    }
199  }
200
201  @SuppressWarnings("unchecked")
202  <T1 extends T> ElementOrder<T1> cast() {
203    return (ElementOrder<T1>) this;
204  }
205}