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