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