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