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