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