001/*
002 * Copyright (C) 2010 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.base;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018
019import com.google.common.annotations.GwtCompatible;
020import com.google.errorprone.annotations.ForOverride;
021import java.io.Serializable;
022import javax.annotation.CheckForNull;
023import org.checkerframework.checker.nullness.qual.Nullable;
024
025/**
026 * A strategy for determining whether two instances are considered equivalent, and for computing
027 * hash codes in a manner consistent with that equivalence. Two examples of equivalences are the
028 * {@linkplain #identity() identity equivalence} and the {@linkplain #equals "equals" equivalence}.
029 *
030 * <p><b>For users targeting Android API level 24 or higher:</b> This class will eventually
031 * implement {@code BiPredicate<T, T>} (as it does in the main Guava artifact), but we currently
032 * target a lower API level. In the meantime, if you have support for method references you can use
033 * an equivalence as a bi-predicate like this: {@code myEquivalence::equivalent}.
034 *
035 * @author Bob Lee
036 * @author Ben Yu
037 * @author Gregory Kick
038 * @since 10.0 (<a href="https://github.com/google/guava/wiki/Compatibility">mostly
039 *     source-compatible</a> since 4.0)
040 */
041@GwtCompatible
042@ElementTypesAreNonnullByDefault
043/*
044 * The type parameter is <T> rather than <T extends @Nullable> so that we can use T in the
045 * doEquivalent and doHash methods to indicate that the parameter cannot be null.
046 */
047public abstract class Equivalence<T> {
048  /** Constructor for use by subclasses. */
049  protected Equivalence() {}
050
051  /**
052   * Returns {@code true} if the given objects are considered equivalent.
053   *
054   * <p>This method describes an <i>equivalence relation</i> on object references, meaning that for
055   * all references {@code x}, {@code y}, and {@code z} (any of which may be null):
056   *
057   * <ul>
058   *   <li>{@code equivalent(x, x)} is true (<i>reflexive</i> property)
059   *   <li>{@code equivalent(x, y)} and {@code equivalent(y, x)} each return the same result
060   *       (<i>symmetric</i> property)
061   *   <li>If {@code equivalent(x, y)} and {@code equivalent(y, z)} are both true, then {@code
062   *       equivalent(x, z)} is also true (<i>transitive</i> property)
063   * </ul>
064   *
065   * <p>Note that all calls to {@code equivalent(x, y)} are expected to return the same result as
066   * long as neither {@code x} nor {@code y} is modified.
067   */
068  public final boolean equivalent(@CheckForNull T a, @CheckForNull T b) {
069    if (a == b) {
070      return true;
071    }
072    if (a == null || b == null) {
073      return false;
074    }
075    return doEquivalent(a, b);
076  }
077
078  /**
079   *
080   * @since 10.0 (previously, subclasses would override equivalent())
081   */
082  @ForOverride
083  protected abstract boolean doEquivalent(T a, T b);
084
085  /**
086   * Returns a hash code for {@code t}.
087   *
088   * <p>The {@code hash} has the following properties:
089   *
090   * <ul>
091   *   <li>It is <i>consistent</i>: for any reference {@code x}, multiple invocations of {@code
092   *       hash(x}} consistently return the same value provided {@code x} remains unchanged
093   *       according to the definition of the equivalence. The hash need not remain consistent from
094   *       one execution of an application to another execution of the same application.
095   *   <li>It is <i>distributable across equivalence</i>: for any references {@code x} and {@code
096   *       y}, if {@code equivalent(x, y)}, then {@code hash(x) == hash(y)}. It is <i>not</i>
097   *       necessary that the hash be distributable across <i>inequivalence</i>. If {@code
098   *       equivalence(x, y)} is false, {@code hash(x) == hash(y)} may still be true.
099   *   <li>{@code hash(null)} is {@code 0}.
100   * </ul>
101   */
102  public final int hash(@CheckForNull T t) {
103    if (t == null) {
104      return 0;
105    }
106    return doHash(t);
107  }
108
109  /**
110   * Implemented by the user to return a hash code for {@code t}, subject to the requirements
111   * specified in {@link #hash}.
112   *
113   * <p>This method should not be called except by {@link #hash}. When {@link #hash} calls this
114   * method, {@code t} is guaranteed to be non-null.
115   *
116   * @since 10.0 (previously, subclasses would override hash())
117   */
118  @ForOverride
119  protected abstract int doHash(T t);
120
121  /**
122   * Returns a new equivalence relation for {@code F} which evaluates equivalence by first applying
123   * {@code function} to the argument, then evaluating using {@code this}. That is, for any pair of
124   * non-null objects {@code x} and {@code y}, {@code equivalence.onResultOf(function).equivalent(a,
125   * b)} is true if and only if {@code equivalence.equivalent(function.apply(a), function.apply(b))}
126   * is true.
127   *
128   * <p>For example:
129   *
130   * <pre>{@code
131   * Equivalence<Person> SAME_AGE = Equivalence.equals().onResultOf(GET_PERSON_AGE);
132   * }</pre>
133   *
134   * <p>{@code function} will never be invoked with a null value.
135   *
136   * <p>Note that {@code function} must be consistent according to {@code this} equivalence
137   * relation. That is, invoking {@link Function#apply} multiple times for a given value must return
138   * equivalent results. For example, {@code
139   * Equivalence.identity().onResultOf(Functions.toStringFunction())} is broken because it's not
140   * guaranteed that {@link Object#toString}) always returns the same string instance.
141   *
142   * @since 10.0
143   */
144  public final <F> Equivalence<F> onResultOf(Function<? super F, ? extends @Nullable T> function) {
145    return new FunctionalEquivalence<>(function, this);
146  }
147
148  /**
149   * Returns a wrapper of {@code reference} that implements {@link Wrapper#equals(Object)
150   * Object.equals()} such that {@code wrap(a).equals(wrap(b))} if and only if {@code equivalent(a,
151   * b)}.
152   *
153   * @since 10.0
154   */
155  public final <S extends @Nullable T> Wrapper<S> wrap(@ParametricNullness S reference) {
156    return new Wrapper<S>(this, reference);
157  }
158
159  /**
160   * Wraps an object so that {@link #equals(Object)} and {@link #hashCode()} delegate to an {@link
161   * Equivalence}.
162   *
163   * <p>For example, given an {@link Equivalence} for {@link String strings} named {@code equiv}
164   * that tests equivalence using their lengths:
165   *
166   * <pre>{@code
167   * equiv.wrap("a").equals(equiv.wrap("b")) // true
168   * equiv.wrap("a").equals(equiv.wrap("hello")) // false
169   * }</pre>
170   *
171   * <p>Note in particular that an equivalence wrapper is never equal to the object it wraps.
172   *
173   * <pre>{@code
174   * equiv.wrap(obj).equals(obj) // always false
175   * }</pre>
176   *
177   * @since 10.0
178   */
179  public static final class Wrapper<T extends @Nullable Object> implements Serializable {
180    private final Equivalence<? super T> equivalence;
181    @ParametricNullness private final T reference;
182
183    private Wrapper(Equivalence<? super T> equivalence, @ParametricNullness T reference) {
184      this.equivalence = checkNotNull(equivalence);
185      this.reference = reference;
186    }
187
188    /** Returns the (possibly null) reference wrapped by this instance. */
189    @ParametricNullness
190    public T get() {
191      return reference;
192    }
193
194    /**
195     * Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} applied to the wrapped
196     * references is {@code true} and both wrappers use the {@link Object#equals(Object) same}
197     * equivalence.
198     */
199    @Override
200    public boolean equals(@CheckForNull Object obj) {
201      if (obj == this) {
202        return true;
203      }
204      if (obj instanceof Wrapper) {
205        Wrapper<?> that = (Wrapper<?>) obj; // note: not necessarily a Wrapper<T>
206
207        if (this.equivalence.equals(that.equivalence)) {
208          /*
209           * We'll accept that as sufficient "proof" that either equivalence should be able to
210           * handle either reference, so it's safe to circumvent compile-time type checking.
211           */
212          @SuppressWarnings("unchecked")
213          Equivalence<Object> equivalence = (Equivalence<Object>) this.equivalence;
214          return equivalence.equivalent(this.reference, that.reference);
215        }
216      }
217      return false;
218    }
219
220    /** Returns the result of {@link Equivalence#hash(Object)} applied to the wrapped reference. */
221    @Override
222    public int hashCode() {
223      return equivalence.hash(reference);
224    }
225
226    /**
227     * Returns a string representation for this equivalence wrapper. The form of this string
228     * representation is not specified.
229     */
230    @Override
231    public String toString() {
232      return equivalence + ".wrap(" + reference + ")";
233    }
234
235    private static final long serialVersionUID = 0;
236  }
237
238  /**
239   * Returns an equivalence over iterables based on the equivalence of their elements. More
240   * specifically, two iterables are considered equivalent if they both contain the same number of
241   * elements, and each pair of corresponding elements is equivalent according to {@code this}. Null
242   * iterables are equivalent to one another.
243   *
244   * <p>Note that this method performs a similar function for equivalences as {@link
245   * com.google.common.collect.Ordering#lexicographical} does for orderings.
246   *
247   * @since 10.0
248   */
249  @GwtCompatible(serializable = true)
250  public final <S extends @Nullable T> Equivalence<Iterable<S>> pairwise() {
251    // Ideally, the returned equivalence would support Iterable<? extends T>. However,
252    // the need for this is so rare that it's not worth making callers deal with the ugly wildcard.
253    return new PairwiseEquivalence<>(this);
254  }
255
256  /**
257   * Returns a predicate that evaluates to true if and only if the input is equivalent to {@code
258   * target} according to this equivalence relation.
259   *
260   * @since 10.0
261   */
262  public final Predicate<@Nullable T> equivalentTo(@CheckForNull T target) {
263    return new EquivalentToPredicate<T>(this, target);
264  }
265
266  private static final class EquivalentToPredicate<T>
267      implements Predicate<@Nullable T>, Serializable {
268
269    private final Equivalence<T> equivalence;
270    @CheckForNull private final T target;
271
272    EquivalentToPredicate(Equivalence<T> equivalence, @CheckForNull T target) {
273      this.equivalence = checkNotNull(equivalence);
274      this.target = target;
275    }
276
277    @Override
278    public boolean apply(@CheckForNull T input) {
279      return equivalence.equivalent(input, target);
280    }
281
282    @Override
283    public boolean equals(@CheckForNull Object obj) {
284      if (this == obj) {
285        return true;
286      }
287      if (obj instanceof EquivalentToPredicate) {
288        EquivalentToPredicate<?> that = (EquivalentToPredicate<?>) obj;
289        return equivalence.equals(that.equivalence) && Objects.equal(target, that.target);
290      }
291      return false;
292    }
293
294    @Override
295    public int hashCode() {
296      return Objects.hashCode(equivalence, target);
297    }
298
299    @Override
300    public String toString() {
301      return equivalence + ".equivalentTo(" + target + ")";
302    }
303
304    private static final long serialVersionUID = 0;
305  }
306
307  /**
308   * Returns an equivalence that delegates to {@link Object#equals} and {@link Object#hashCode}.
309   * {@link Equivalence#equivalent} returns {@code true} if both values are null, or if neither
310   * value is null and {@link Object#equals} returns {@code true}. {@link Equivalence#hash} returns
311   * {@code 0} if passed a null value.
312   *
313   * @since 13.0
314   * @since 8.0 (in Equivalences with null-friendly behavior)
315   * @since 4.0 (in Equivalences)
316   */
317  public static Equivalence<Object> equals() {
318    return Equals.INSTANCE;
319  }
320
321  /**
322   * Returns an equivalence that uses {@code ==} to compare values and {@link
323   * System#identityHashCode(Object)} to compute the hash code. {@link Equivalence#equivalent}
324   * returns {@code true} if {@code a == b}, including in the case that a and b are both null.
325   *
326   * @since 13.0
327   * @since 4.0 (in Equivalences)
328   */
329  public static Equivalence<Object> identity() {
330    return Identity.INSTANCE;
331  }
332
333  static final class Equals extends Equivalence<Object> implements Serializable {
334
335    static final Equals INSTANCE = new Equals();
336
337    @Override
338    protected boolean doEquivalent(Object a, Object b) {
339      return a.equals(b);
340    }
341
342    @Override
343    protected int doHash(Object o) {
344      return o.hashCode();
345    }
346
347    private Object readResolve() {
348      return INSTANCE;
349    }
350
351    private static final long serialVersionUID = 1;
352  }
353
354  static final class Identity extends Equivalence<Object> implements Serializable {
355
356    static final Identity INSTANCE = new Identity();
357
358    @Override
359    protected boolean doEquivalent(Object a, Object b) {
360      return false;
361    }
362
363    @Override
364    protected int doHash(Object o) {
365      return System.identityHashCode(o);
366    }
367
368    private Object readResolve() {
369      return INSTANCE;
370    }
371
372    private static final long serialVersionUID = 1;
373  }
374}