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