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 java.io.Serializable;
024import org.jspecify.annotations.NonNull;
025import org.jspecify.annotations.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 * <p><b>For users targeting Android API level 24 or higher:</b> This class will eventually
033 * implement {@code BiPredicate<T, T>} (as it does in the main Guava artifact), but we currently
034 * target a lower API level. In the meantime, if you have support for method references you can use
035 * an equivalence as a bi-predicate like this: {@code myEquivalence::equivalent}.
036 *
037 * @author Bob Lee
038 * @author Ben Yu
039 * @author Gregory Kick
040 * @since 10.0 (<a href="https://github.com/google/guava/wiki/Compatibility">mostly
041 *     source-compatible</a> since 4.0)
042 */
043@GwtCompatible
044/*
045 * The type parameter is <T> rather than <T extends @Nullable> so that we can use T in the
046 * doEquivalent and doHash methods to indicate that the parameter cannot be null.
047 */
048public abstract class Equivalence<T> {
049  /** Constructor for use by subclasses. */
050  protected Equivalence() {}
051
052  /**
053   * Returns {@code true} if the given objects are considered equivalent.
054   *
055   * <p>This method describes an <i>equivalence relation</i> on object references, meaning that for
056   * all references {@code x}, {@code y}, and {@code z} (any of which may be null):
057   *
058   * <ul>
059   *   <li>{@code equivalent(x, x)} is true (<i>reflexive</i> property)
060   *   <li>{@code equivalent(x, y)} and {@code equivalent(y, x)} each return the same result
061   *       (<i>symmetric</i> property)
062   *   <li>If {@code equivalent(x, y)} and {@code equivalent(y, z)} are both true, then {@code
063   *       equivalent(x, z)} is also true (<i>transitive</i> property)
064   * </ul>
065   *
066   * <p>Note that all calls to {@code equivalent(x, y)} are expected to return the same result as
067   * long as neither {@code x} nor {@code y} is modified.
068   */
069  public final boolean equivalent(@Nullable T a, @Nullable T b) {
070    if (a == b) {
071      return true;
072    }
073    if (a == null || b == null) {
074      return false;
075    }
076    return doEquivalent(a, b);
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(@Nullable 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   * <p>The returned object is serializable if both this {@code Equivalence} and {@code reference}
154   * are serializable (including when {@code reference} is null).
155   *
156   * @since 10.0
157   */
158  public final <S extends @Nullable T> Wrapper<S> wrap(@ParametricNullness S reference) {
159    return new Wrapper<>(this, reference);
160  }
161
162  /**
163   * Wraps an object so that {@link #equals(Object)} and {@link #hashCode()} delegate to an {@link
164   * Equivalence}.
165   *
166   * <p>For example, given an {@link Equivalence} for {@link String strings} named {@code equiv}
167   * that tests equivalence using their lengths:
168   *
169   * <pre>{@code
170   * equiv.wrap("a").equals(equiv.wrap("b")) // true
171   * equiv.wrap("a").equals(equiv.wrap("hello")) // false
172   * }</pre>
173   *
174   * <p>Note in particular that an equivalence wrapper is never equal to the object it wraps.
175   *
176   * <pre>{@code
177   * equiv.wrap(obj).equals(obj) // always false
178   * }</pre>
179   *
180   * @since 10.0
181   */
182  public static final class Wrapper<T extends @Nullable Object> implements Serializable {
183    /*
184     * Equivalence's type argument is always non-nullable: Equivalence<Number>, never
185     * Equivalence<@Nullable Number>. That can still produce wrappers of various types --
186     * Wrapper<Number>, Wrapper<Integer>, Wrapper<@Nullable Integer>, etc. If we used just
187     * Equivalence<? super T> below, no type could satisfy both that bound and T's own
188     * bound. With this type, they have some overlap: in our example, Equivalence<Number>
189     * and Equivalence<Object>.
190     */
191    private final Equivalence<? super @NonNull T> equivalence;
192
193    @ParametricNullness private final T reference;
194
195    private Wrapper(Equivalence<? super @NonNull T> equivalence, @ParametricNullness T reference) {
196      this.equivalence = checkNotNull(equivalence);
197      this.reference = reference;
198    }
199
200    /** Returns the (possibly null) reference wrapped by this instance. */
201    @ParametricNullness
202    public T get() {
203      return reference;
204    }
205
206    /**
207     * Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} applied to the wrapped
208     * references is {@code true} and both wrappers use the {@link Object#equals(Object) same}
209     * equivalence.
210     */
211    @Override
212    public boolean equals(@Nullable Object obj) {
213      if (obj == this) {
214        return true;
215      }
216      if (obj instanceof Wrapper) {
217        Wrapper<?> that = (Wrapper<?>) obj; // note: not necessarily a Wrapper<T>
218
219        if (this.equivalence.equals(that.equivalence)) {
220          /*
221           * We'll accept that as sufficient "proof" that either equivalence should be able to
222           * handle either reference, so it's safe to circumvent compile-time type checking.
223           */
224          @SuppressWarnings("unchecked")
225          Equivalence<Object> equivalence = (Equivalence<Object>) this.equivalence;
226          return equivalence.equivalent(this.reference, that.reference);
227        }
228      }
229      return false;
230    }
231
232    /** Returns the result of {@link Equivalence#hash(Object)} applied to the wrapped reference. */
233    @Override
234    public int hashCode() {
235      return equivalence.hash(reference);
236    }
237
238    /**
239     * Returns a string representation for this equivalence wrapper. The form of this string
240     * representation is not specified.
241     */
242    @Override
243    public String toString() {
244      return equivalence + ".wrap(" + reference + ")";
245    }
246
247    @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
248  }
249
250  /**
251   * Returns an equivalence over iterables based on the equivalence of their elements. More
252   * specifically, two iterables are considered equivalent if they both contain the same number of
253   * elements, and each pair of corresponding elements is equivalent according to {@code this}. Null
254   * iterables are equivalent to one another.
255   *
256   * <p>Note that this method performs a similar function for equivalences as {@link
257   * com.google.common.collect.Ordering#lexicographical} does for orderings.
258   *
259   * <p>The returned object is serializable if this object is serializable.
260   *
261   * @since 10.0
262   */
263  @GwtCompatible(serializable = true)
264  public final <S extends @Nullable T> Equivalence<Iterable<S>> pairwise() {
265    // Ideally, the returned equivalence would support Iterable<? extends T>. However,
266    // the need for this is so rare that it's not worth making callers deal with the ugly wildcard.
267    return new PairwiseEquivalence<>(this);
268  }
269
270  /**
271   * Returns a predicate that evaluates to true if and only if the input is equivalent to {@code
272   * target} according to this equivalence relation.
273   *
274   * @since 10.0
275   */
276  public final Predicate<@Nullable T> equivalentTo(@Nullable T target) {
277    return new EquivalentToPredicate<>(this, target);
278  }
279
280  private static final class EquivalentToPredicate<T>
281      implements Predicate<@Nullable T>, Serializable {
282
283    private final Equivalence<T> equivalence;
284    private final @Nullable T target;
285
286    EquivalentToPredicate(Equivalence<T> equivalence, @Nullable T target) {
287      this.equivalence = checkNotNull(equivalence);
288      this.target = target;
289    }
290
291    @Override
292    public boolean apply(@Nullable T input) {
293      return equivalence.equivalent(input, target);
294    }
295
296    @Override
297    public boolean equals(@Nullable Object obj) {
298      if (this == obj) {
299        return true;
300      }
301      if (obj instanceof EquivalentToPredicate) {
302        EquivalentToPredicate<?> that = (EquivalentToPredicate<?>) obj;
303        return equivalence.equals(that.equivalence) && Objects.equal(target, that.target);
304      }
305      return false;
306    }
307
308    @Override
309    public int hashCode() {
310      return Objects.hashCode(equivalence, target);
311    }
312
313    @Override
314    public String toString() {
315      return equivalence + ".equivalentTo(" + target + ")";
316    }
317
318    @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
319  }
320
321  /**
322   * Returns an equivalence that delegates to {@link Object#equals} and {@link Object#hashCode}.
323   * {@link Equivalence#equivalent} returns {@code true} if both values are null, or if neither
324   * value is null and {@link Object#equals} returns {@code true}. {@link Equivalence#hash} returns
325   * {@code 0} if passed a null value.
326   *
327   * @since 13.0
328   * @since 8.0 (in Equivalences with null-friendly behavior)
329   * @since 4.0 (in Equivalences)
330   */
331  public static Equivalence<Object> equals() {
332    return Equals.INSTANCE;
333  }
334
335  /**
336   * Returns an equivalence that uses {@code ==} to compare values and {@link
337   * System#identityHashCode(Object)} to compute the hash code. {@link Equivalence#equivalent}
338   * returns {@code true} if {@code a == b}, including in the case that a and b are both null.
339   *
340   * @since 13.0
341   * @since 4.0 (in Equivalences)
342   */
343  public static Equivalence<Object> identity() {
344    return Identity.INSTANCE;
345  }
346
347  static final class Equals extends Equivalence<Object> implements Serializable {
348
349    static final Equals INSTANCE = new Equals();
350
351    @Override
352    protected boolean doEquivalent(Object a, Object b) {
353      return a.equals(b);
354    }
355
356    @Override
357    protected int doHash(Object o) {
358      return o.hashCode();
359    }
360
361    private Object readResolve() {
362      return INSTANCE;
363    }
364
365    @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 1;
366  }
367
368  static final class Identity extends Equivalence<Object> implements Serializable {
369
370    static final Identity INSTANCE = new Identity();
371
372    @Override
373    protected boolean doEquivalent(Object a, Object b) {
374      return false;
375    }
376
377    @Override
378    protected int doHash(Object o) {
379      return System.identityHashCode(o);
380    }
381
382    private Object readResolve() {
383      return INSTANCE;
384    }
385
386    @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 1;
387  }
388}