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.CheckForNull;
023import org.checkerframework.checker.nullness.qual.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@ElementTypesAreNonnullByDefault
043/*
044 * The type parameter is <T> rather than <T extends @Nullable> so that we can use T in the
045 * doEquivalent and doHash methods to indicate that the parameter cannot be null.
046 */
047public abstract class Equivalence<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(@CheckForNull T a, @CheckForNull 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   *
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(@CheckForNull 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   * @since 10.0
154   */
155  public final <S extends @Nullable T> Wrapper<S> wrap(@ParametricNullness S reference) {
156    /*
157     * I'm pretty sure that this warning "makes sense" but doesn't indicate a real problem.
158     *
159     * Why it "makes sense": If we pass a `@Nullable Foo`, then we should also pass an
160     * `Equivalence<? super @Nullable Foo>`. And there's no such thing because Equivalence doesn't
161     * permit nullable type arguments.
162     *
163     * Why there's no real problem: Every Equivalence can handle null.
164     *
165     * We could work around this by giving Wrapper 2 type parameters. In the terms of this method,
166     * that would be both the T parameter (from the class) and the S parameter (from this method).
167     * However, such a change would be source-incompatible. (Plus, there's no reason for the S
168     * parameter from the user's perspective, so it would be a wart.)
169     *
170     * We could probably also work around this by making Wrapper non-final and putting the
171     * implementation into a subclass with those 2 type parameters. But we like `final`, if only to
172     * deter users from using mocking frameworks to construct instances. (And could also complicate
173     * serialization, which is discussed more in the next paragraph.)
174     *
175     * We could probably also work around this by having Wrapper accept an instance of a new
176     * WrapperGuts class, which would then be the class that would declare the 2 type parameters.
177     * But that would break deserialization of previously serialized Wrapper instances. And while we
178     * specifically say not to rely on serialization across Guava versions, users sometimes do. So
179     * we'd rather not break them without a good enough reason.
180     *
181     * (We could work around the serialization problem by writing custom serialization code. But
182     * even that helps only the case of serializing with an old version and deserializing with a
183     * new, not vice versa -- unless we introduce WrapperGuts and the logic to handle it today, wait
184     * until "everyone" has picked up a version of Guava with that code, and *then* change to use
185     * WrapperGuts.)
186     *
187     * Anyway, a suppression isn't really a big deal. But I have tried to do some due diligence on
188     * avoiding it :)
189     */
190    @SuppressWarnings("nullness")
191    Wrapper<S> w = new Wrapper<>(this, reference);
192    return w;
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   * <pre>{@code
203   * equiv.wrap("a").equals(equiv.wrap("b")) // true
204   * equiv.wrap("a").equals(equiv.wrap("hello")) // false
205   * }</pre>
206   *
207   * <p>Note in particular that an equivalence wrapper is never equal to the object it wraps.
208   *
209   * <pre>{@code
210   * equiv.wrap(obj).equals(obj) // always false
211   * }</pre>
212   *
213   * @since 10.0
214   */
215  public static final class Wrapper<T extends @Nullable Object> implements Serializable {
216    private final Equivalence<? super T> equivalence;
217    @ParametricNullness private final T reference;
218
219    private Wrapper(Equivalence<? super T> equivalence, @ParametricNullness T reference) {
220      this.equivalence = checkNotNull(equivalence);
221      this.reference = reference;
222    }
223
224    /** Returns the (possibly null) reference wrapped by this instance. */
225    @ParametricNullness
226    public T get() {
227      return reference;
228    }
229
230    /**
231     * Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} applied to the wrapped
232     * references is {@code true} and both wrappers use the {@link Object#equals(Object) same}
233     * equivalence.
234     */
235    @Override
236    public boolean equals(@CheckForNull Object obj) {
237      if (obj == this) {
238        return true;
239      }
240      if (obj instanceof Wrapper) {
241        Wrapper<?> that = (Wrapper<?>) obj; // note: not necessarily a Wrapper<T>
242
243        if (this.equivalence.equals(that.equivalence)) {
244          /*
245           * We'll accept that as sufficient "proof" that either equivalence should be able to
246           * handle either reference, so it's safe to circumvent compile-time type checking.
247           */
248          @SuppressWarnings("unchecked")
249          Equivalence<Object> equivalence = (Equivalence<Object>) this.equivalence;
250          return equivalence.equivalent(this.reference, that.reference);
251        }
252      }
253      return false;
254    }
255
256    /** Returns the result of {@link Equivalence#hash(Object)} applied to the wrapped reference. */
257    @Override
258    public int hashCode() {
259      return equivalence.hash(reference);
260    }
261
262    /**
263     * Returns a string representation for this equivalence wrapper. The form of this string
264     * representation is not specified.
265     */
266    @Override
267    public String toString() {
268      return equivalence + ".wrap(" + reference + ")";
269    }
270
271    private static final long serialVersionUID = 0;
272  }
273
274  /**
275   * Returns an equivalence over iterables based on the equivalence of their elements. More
276   * specifically, two iterables are considered equivalent if they both contain the same number of
277   * elements, and each pair of corresponding elements is equivalent according to {@code this}. Null
278   * iterables are equivalent to one another.
279   *
280   * <p>Note that this method performs a similar function for equivalences as {@link
281   * com.google.common.collect.Ordering#lexicographical} does for orderings.
282   *
283   * @since 10.0
284   */
285  @GwtCompatible(serializable = true)
286  public final <S extends @Nullable T> Equivalence<Iterable<S>> pairwise() {
287    // Ideally, the returned equivalence would support Iterable<? extends T>. However,
288    // the need for this is so rare that it's not worth making callers deal with the ugly wildcard.
289    return new PairwiseEquivalence<>(this);
290  }
291
292  /**
293   * Returns a predicate that evaluates to true if and only if the input is equivalent to {@code
294   * target} according to this equivalence relation.
295   *
296   * @since 10.0
297   */
298  public final Predicate<@Nullable T> equivalentTo(@CheckForNull T target) {
299    return new EquivalentToPredicate<T>(this, target);
300  }
301
302  private static final class EquivalentToPredicate<T>
303      implements Predicate<@Nullable T>, Serializable {
304
305    private final Equivalence<T> equivalence;
306    @CheckForNull private final T target;
307
308    EquivalentToPredicate(Equivalence<T> equivalence, @CheckForNull T target) {
309      this.equivalence = checkNotNull(equivalence);
310      this.target = target;
311    }
312
313    @Override
314    public boolean apply(@CheckForNull T input) {
315      return equivalence.equivalent(input, target);
316    }
317
318    @Override
319    public boolean equals(@CheckForNull Object obj) {
320      if (this == obj) {
321        return true;
322      }
323      if (obj instanceof EquivalentToPredicate) {
324        EquivalentToPredicate<?> that = (EquivalentToPredicate<?>) obj;
325        return equivalence.equals(that.equivalence) && Objects.equal(target, that.target);
326      }
327      return false;
328    }
329
330    @Override
331    public int hashCode() {
332      return Objects.hashCode(equivalence, target);
333    }
334
335    @Override
336    public String toString() {
337      return equivalence + ".equivalentTo(" + target + ")";
338    }
339
340    private static final long serialVersionUID = 0;
341  }
342
343  /**
344   * Returns an equivalence that delegates to {@link Object#equals} and {@link Object#hashCode}.
345   * {@link Equivalence#equivalent} returns {@code true} if both values are null, or if neither
346   * value is null and {@link Object#equals} returns {@code true}. {@link Equivalence#hash} returns
347   * {@code 0} if passed a null value.
348   *
349   * @since 13.0
350   * @since 8.0 (in Equivalences with null-friendly behavior)
351   * @since 4.0 (in Equivalences)
352   */
353  public static Equivalence<Object> equals() {
354    return Equals.INSTANCE;
355  }
356
357  /**
358   * Returns an equivalence that uses {@code ==} to compare values and {@link
359   * System#identityHashCode(Object)} to compute the hash code. {@link Equivalence#equivalent}
360   * returns {@code true} if {@code a == b}, including in the case that a and b are both null.
361   *
362   * @since 13.0
363   * @since 4.0 (in Equivalences)
364   */
365  public static Equivalence<Object> identity() {
366    return Identity.INSTANCE;
367  }
368
369  static final class Equals extends Equivalence<Object> implements Serializable {
370
371    static final Equals INSTANCE = new Equals();
372
373    @Override
374    protected boolean doEquivalent(Object a, Object b) {
375      return a.equals(b);
376    }
377
378    @Override
379    protected int doHash(Object o) {
380      return o.hashCode();
381    }
382
383    private Object readResolve() {
384      return INSTANCE;
385    }
386
387    private static final long serialVersionUID = 1;
388  }
389
390  static final class Identity extends Equivalence<Object> implements Serializable {
391
392    static final Identity INSTANCE = new Identity();
393
394    @Override
395    protected boolean doEquivalent(Object a, Object b) {
396      return false;
397    }
398
399    @Override
400    protected int doHash(Object o) {
401      return System.identityHashCode(o);
402    }
403
404    private Object readResolve() {
405      return INSTANCE;
406    }
407
408    private static final long serialVersionUID = 1;
409  }
410}