001/*
002 * Copyright (C) 2007 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 java.io.Serializable;
023import java.util.ArrayList;
024import java.util.Arrays;
025import java.util.Collection;
026import java.util.List;
027import java.util.regex.Pattern;
028import javax.annotation.CheckForNull;
029import org.checkerframework.checker.nullness.qual.Nullable;
030
031/**
032 * Static utility methods pertaining to {@code Predicate} instances.
033 *
034 * <p>All methods return serializable predicates as long as they're given serializable parameters.
035 *
036 * <p>See the Guava User Guide article on <a
037 * href="https://github.com/google/guava/wiki/FunctionalExplained">the use of {@code Predicate}</a>.
038 *
039 * @author Kevin Bourrillion
040 * @since 2.0
041 */
042@GwtCompatible(emulated = true)
043@ElementTypesAreNonnullByDefault
044public final class Predicates {
045  private Predicates() {}
046
047  // TODO(kevinb): considering having these implement a VisitablePredicate
048  // interface which specifies an accept(PredicateVisitor) method.
049
050  /** Returns a predicate that always evaluates to {@code true}. */
051  @GwtCompatible(serializable = true)
052  public static <T extends @Nullable Object> Predicate<T> alwaysTrue() {
053    return ObjectPredicate.ALWAYS_TRUE.withNarrowedType();
054  }
055
056  /** Returns a predicate that always evaluates to {@code false}. */
057  @GwtCompatible(serializable = true)
058  public static <T extends @Nullable Object> Predicate<T> alwaysFalse() {
059    return ObjectPredicate.ALWAYS_FALSE.withNarrowedType();
060  }
061
062  /**
063   * Returns a predicate that evaluates to {@code true} if the object reference being tested is
064   * null.
065   */
066  @GwtCompatible(serializable = true)
067  public static <T extends @Nullable Object> Predicate<T> isNull() {
068    return ObjectPredicate.IS_NULL.withNarrowedType();
069  }
070
071  /**
072   * Returns a predicate that evaluates to {@code true} if the object reference being tested is not
073   * null.
074   */
075  @GwtCompatible(serializable = true)
076  public static <T extends @Nullable Object> Predicate<T> notNull() {
077    return ObjectPredicate.NOT_NULL.withNarrowedType();
078  }
079
080  /**
081   * Returns a predicate that evaluates to {@code true} if the given predicate evaluates to {@code
082   * false}.
083   */
084  public static <T extends @Nullable Object> Predicate<T> not(Predicate<T> predicate) {
085    return new NotPredicate<>(predicate);
086  }
087
088  /**
089   * Returns a predicate that evaluates to {@code true} if each of its components evaluates to
090   * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited"
091   * as soon as a false predicate is found. It defensively copies the iterable passed in, so future
092   * changes to it won't alter the behavior of this predicate. If {@code components} is empty, the
093   * returned predicate will always evaluate to {@code true}.
094   */
095  public static <T extends @Nullable Object> Predicate<T> and(
096      Iterable<? extends Predicate<? super T>> components) {
097    return new AndPredicate<>(defensiveCopy(components));
098  }
099
100  /**
101   * Returns a predicate that evaluates to {@code true} if each of its components evaluates to
102   * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited"
103   * as soon as a false predicate is found. It defensively copies the array passed in, so future
104   * changes to it won't alter the behavior of this predicate. If {@code components} is empty, the
105   * returned predicate will always evaluate to {@code true}.
106   */
107  @SafeVarargs
108  public static <T extends @Nullable Object> Predicate<T> and(Predicate<? super T>... components) {
109    return new AndPredicate<T>(defensiveCopy(components));
110  }
111
112  /**
113   * Returns a predicate that evaluates to {@code true} if both of its components evaluate to {@code
114   * true}. The components are evaluated in order, and evaluation will be "short-circuited" as soon
115   * as a false predicate is found.
116   */
117  public static <T extends @Nullable Object> Predicate<T> and(
118      Predicate<? super T> first, Predicate<? super T> second) {
119    return new AndPredicate<>(Predicates.<T>asList(checkNotNull(first), checkNotNull(second)));
120  }
121
122  /**
123   * Returns a predicate that evaluates to {@code true} if any one of its components evaluates to
124   * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited"
125   * as soon as a true predicate is found. It defensively copies the iterable passed in, so future
126   * changes to it won't alter the behavior of this predicate. If {@code components} is empty, the
127   * returned predicate will always evaluate to {@code false}.
128   */
129  public static <T extends @Nullable Object> Predicate<T> or(
130      Iterable<? extends Predicate<? super T>> components) {
131    return new OrPredicate<>(defensiveCopy(components));
132  }
133
134  /**
135   * Returns a predicate that evaluates to {@code true} if any one of its components evaluates to
136   * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited"
137   * as soon as a true predicate is found. It defensively copies the array passed in, so future
138   * changes to it won't alter the behavior of this predicate. If {@code components} is empty, the
139   * returned predicate will always evaluate to {@code false}.
140   */
141  @SafeVarargs
142  public static <T extends @Nullable Object> Predicate<T> or(Predicate<? super T>... components) {
143    return new OrPredicate<T>(defensiveCopy(components));
144  }
145
146  /**
147   * Returns a predicate that evaluates to {@code true} if either of its components evaluates to
148   * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited"
149   * as soon as a true predicate is found.
150   */
151  public static <T extends @Nullable Object> Predicate<T> or(
152      Predicate<? super T> first, Predicate<? super T> second) {
153    return new OrPredicate<>(Predicates.<T>asList(checkNotNull(first), checkNotNull(second)));
154  }
155
156  /**
157   * Returns a predicate that evaluates to {@code true} if the object being tested {@code equals()}
158   * the given target or both are null.
159   */
160  public static <T extends @Nullable Object> Predicate<T> equalTo(@ParametricNullness T target) {
161    return (target == null)
162        ? Predicates.<T>isNull()
163        : new IsEqualToPredicate(target).withNarrowedType();
164  }
165
166  /**
167   * Returns a predicate that evaluates to {@code true} if the object being tested is an instance of
168   * the given class. If the object being tested is {@code null} this predicate evaluates to {@code
169   * false}.
170   *
171   * <p>If you want to filter an {@code Iterable} to narrow its type, consider using {@link
172   * com.google.common.collect.Iterables#filter(Iterable, Class)} in preference.
173   *
174   * <p><b>Warning:</b> contrary to the typical assumptions about predicates (as documented at
175   * {@link Predicate#apply}), the returned predicate may not be <i>consistent with equals</i>. For
176   * example, {@code instanceOf(ArrayList.class)} will yield different results for the two equal
177   * instances {@code Lists.newArrayList(1)} and {@code Arrays.asList(1)}.
178   */
179  @GwtIncompatible // Class.isInstance
180  public static <T extends @Nullable Object> Predicate<T> instanceOf(Class<?> clazz) {
181    return new InstanceOfPredicate<>(clazz);
182  }
183
184  /**
185   * Returns a predicate that evaluates to {@code true} if the class being tested is assignable to
186   * (is a subtype of) {@code clazz}. Example:
187   *
188   * <pre>{@code
189   * List<Class<?>> classes = Arrays.asList(
190   *     Object.class, String.class, Number.class, Long.class);
191   * return Iterables.filter(classes, subtypeOf(Number.class));
192   * }</pre>
193   *
194   * The code above returns an iterable containing {@code Number.class} and {@code Long.class}.
195   *
196   * @since 20.0 (since 10.0 under the incorrect name {@code assignableFrom})
197   */
198  @J2ktIncompatible
199  @GwtIncompatible // Class.isAssignableFrom
200  public static Predicate<Class<?>> subtypeOf(Class<?> clazz) {
201    return new SubtypeOfPredicate(clazz);
202  }
203
204  /**
205   * Returns a predicate that evaluates to {@code true} if the object reference being tested is a
206   * member of the given collection. It does not defensively copy the collection passed in, so
207   * future changes to it will alter the behavior of the predicate.
208   *
209   * <p>This method can technically accept any {@code Collection<?>}, but using a typed collection
210   * helps prevent bugs. This approach doesn't block any potential users since it is always possible
211   * to use {@code Predicates.<Object>in()}.
212   *
213   * @param target the collection that may contain the function input
214   */
215  public static <T extends @Nullable Object> Predicate<T> in(Collection<? extends T> target) {
216    return new InPredicate<>(target);
217  }
218
219  /**
220   * Returns the composition of a function and a predicate. For every {@code x}, the generated
221   * predicate returns {@code predicate(function(x))}.
222   *
223   * @return the composition of the provided function and predicate
224   */
225  public static <A extends @Nullable Object, B extends @Nullable Object> Predicate<A> compose(
226      Predicate<B> predicate, Function<A, ? extends B> function) {
227    return new CompositionPredicate<>(predicate, function);
228  }
229
230  /**
231   * Returns a predicate that evaluates to {@code true} if the {@code CharSequence} being tested
232   * contains any match for the given regular expression pattern. The test used is equivalent to
233   * {@code Pattern.compile(pattern).matcher(arg).find()}
234   *
235   * @throws IllegalArgumentException if the pattern is invalid
236   * @since 3.0
237   */
238  @J2ktIncompatible
239  @GwtIncompatible // Only used by other GWT-incompatible code.
240  public static Predicate<CharSequence> containsPattern(String pattern) {
241    return new ContainsPatternFromStringPredicate(pattern);
242  }
243
244  /**
245   * Returns a predicate that evaluates to {@code true} if the {@code CharSequence} being tested
246   * contains any match for the given regular expression pattern. The test used is equivalent to
247   * {@code pattern.matcher(arg).find()}
248   *
249   * @since 3.0
250   */
251  @J2ktIncompatible
252  @GwtIncompatible(value = "java.util.regex.Pattern")
253  public static Predicate<CharSequence> contains(Pattern pattern) {
254    return new ContainsPatternPredicate(new JdkPattern(pattern));
255  }
256
257  // End public API, begin private implementation classes.
258
259  // Package private for GWT serialization.
260  enum ObjectPredicate implements Predicate<@Nullable Object> {
261    /** @see Predicates#alwaysTrue() */
262    ALWAYS_TRUE {
263      @Override
264      public boolean apply(@CheckForNull Object o) {
265        return true;
266      }
267
268      @Override
269      public String toString() {
270        return "Predicates.alwaysTrue()";
271      }
272    },
273    /** @see Predicates#alwaysFalse() */
274    ALWAYS_FALSE {
275      @Override
276      public boolean apply(@CheckForNull Object o) {
277        return false;
278      }
279
280      @Override
281      public String toString() {
282        return "Predicates.alwaysFalse()";
283      }
284    },
285    /** @see Predicates#isNull() */
286    IS_NULL {
287      @Override
288      public boolean apply(@CheckForNull Object o) {
289        return o == null;
290      }
291
292      @Override
293      public String toString() {
294        return "Predicates.isNull()";
295      }
296    },
297    /** @see Predicates#notNull() */
298    NOT_NULL {
299      @Override
300      public boolean apply(@CheckForNull Object o) {
301        return o != null;
302      }
303
304      @Override
305      public String toString() {
306        return "Predicates.notNull()";
307      }
308    };
309
310    @SuppressWarnings("unchecked") // safe contravariant cast
311    <T extends @Nullable Object> Predicate<T> withNarrowedType() {
312      return (Predicate<T>) this;
313    }
314  }
315
316  /** @see Predicates#not(Predicate) */
317  private static class NotPredicate<T extends @Nullable Object>
318      implements Predicate<T>, Serializable {
319    final Predicate<T> predicate;
320
321    NotPredicate(Predicate<T> predicate) {
322      this.predicate = checkNotNull(predicate);
323    }
324
325    @Override
326    public boolean apply(@ParametricNullness T t) {
327      return !predicate.apply(t);
328    }
329
330    @Override
331    public int hashCode() {
332      return ~predicate.hashCode();
333    }
334
335    @Override
336    public boolean equals(@CheckForNull Object obj) {
337      if (obj instanceof NotPredicate) {
338        NotPredicate<?> that = (NotPredicate<?>) obj;
339        return predicate.equals(that.predicate);
340      }
341      return false;
342    }
343
344    @Override
345    public String toString() {
346      return "Predicates.not(" + predicate + ")";
347    }
348
349    private static final long serialVersionUID = 0;
350  }
351
352  /** @see Predicates#and(Iterable) */
353  private static class AndPredicate<T extends @Nullable Object>
354      implements Predicate<T>, Serializable {
355    private final List<? extends Predicate<? super T>> components;
356
357    private AndPredicate(List<? extends Predicate<? super T>> components) {
358      this.components = components;
359    }
360
361    @Override
362    public boolean apply(@ParametricNullness T t) {
363      // Avoid using the Iterator to avoid generating garbage (issue 820).
364      for (int i = 0; i < components.size(); i++) {
365        if (!components.get(i).apply(t)) {
366          return false;
367        }
368      }
369      return true;
370    }
371
372    @Override
373    public int hashCode() {
374      // add a random number to avoid collisions with OrPredicate
375      return components.hashCode() + 0x12472c2c;
376    }
377
378    @Override
379    public boolean equals(@CheckForNull Object obj) {
380      if (obj instanceof AndPredicate) {
381        AndPredicate<?> that = (AndPredicate<?>) obj;
382        return components.equals(that.components);
383      }
384      return false;
385    }
386
387    @Override
388    public String toString() {
389      return toStringHelper("and", components);
390    }
391
392    private static final long serialVersionUID = 0;
393  }
394
395  /** @see Predicates#or(Iterable) */
396  private static class OrPredicate<T extends @Nullable Object>
397      implements Predicate<T>, Serializable {
398    private final List<? extends Predicate<? super T>> components;
399
400    private OrPredicate(List<? extends Predicate<? super T>> components) {
401      this.components = components;
402    }
403
404    @Override
405    public boolean apply(@ParametricNullness T t) {
406      // Avoid using the Iterator to avoid generating garbage (issue 820).
407      for (int i = 0; i < components.size(); i++) {
408        if (components.get(i).apply(t)) {
409          return true;
410        }
411      }
412      return false;
413    }
414
415    @Override
416    public int hashCode() {
417      // add a random number to avoid collisions with AndPredicate
418      return components.hashCode() + 0x053c91cf;
419    }
420
421    @Override
422    public boolean equals(@CheckForNull Object obj) {
423      if (obj instanceof OrPredicate) {
424        OrPredicate<?> that = (OrPredicate<?>) obj;
425        return components.equals(that.components);
426      }
427      return false;
428    }
429
430    @Override
431    public String toString() {
432      return toStringHelper("or", components);
433    }
434
435    private static final long serialVersionUID = 0;
436  }
437
438  private static String toStringHelper(String methodName, Iterable<?> components) {
439    StringBuilder builder = new StringBuilder("Predicates.").append(methodName).append('(');
440    boolean first = true;
441    for (Object o : components) {
442      if (!first) {
443        builder.append(',');
444      }
445      builder.append(o);
446      first = false;
447    }
448    return builder.append(')').toString();
449  }
450
451  /** @see Predicates#equalTo(Object) */
452  private static class IsEqualToPredicate implements Predicate<@Nullable Object>, Serializable {
453    private final Object target;
454
455    private IsEqualToPredicate(Object target) {
456      this.target = target;
457    }
458
459    @Override
460    public boolean apply(@CheckForNull Object o) {
461      return target.equals(o);
462    }
463
464    @Override
465    public int hashCode() {
466      return target.hashCode();
467    }
468
469    @Override
470    public boolean equals(@CheckForNull Object obj) {
471      if (obj instanceof IsEqualToPredicate) {
472        IsEqualToPredicate that = (IsEqualToPredicate) obj;
473        return target.equals(that.target);
474      }
475      return false;
476    }
477
478    @Override
479    public String toString() {
480      return "Predicates.equalTo(" + target + ")";
481    }
482
483    private static final long serialVersionUID = 0;
484
485    @SuppressWarnings("unchecked") // safe contravariant cast
486    <T extends @Nullable Object> Predicate<T> withNarrowedType() {
487      return (Predicate<T>) this;
488    }
489  }
490
491  /**
492   * @see Predicates#instanceOf(Class)
493   */
494  @GwtIncompatible // Class.isInstance
495  private static class InstanceOfPredicate<T extends @Nullable Object>
496      implements Predicate<T>, Serializable {
497    private final Class<?> clazz;
498
499    private InstanceOfPredicate(Class<?> clazz) {
500      this.clazz = checkNotNull(clazz);
501    }
502
503    @Override
504    public boolean apply(@ParametricNullness T o) {
505      return clazz.isInstance(o);
506    }
507
508    @Override
509    public int hashCode() {
510      return clazz.hashCode();
511    }
512
513    @Override
514    public boolean equals(@CheckForNull Object obj) {
515      if (obj instanceof InstanceOfPredicate) {
516        InstanceOfPredicate<?> that = (InstanceOfPredicate<?>) obj;
517        return clazz == that.clazz;
518      }
519      return false;
520    }
521
522    @Override
523    public String toString() {
524      return "Predicates.instanceOf(" + clazz.getName() + ")";
525    }
526
527    @J2ktIncompatible private static final long serialVersionUID = 0;
528  }
529
530  /**
531   * @see Predicates#subtypeOf(Class)
532   */
533  @J2ktIncompatible
534  @GwtIncompatible // Class.isAssignableFrom
535  private static class SubtypeOfPredicate implements Predicate<Class<?>>, Serializable {
536    private final Class<?> clazz;
537
538    private SubtypeOfPredicate(Class<?> clazz) {
539      this.clazz = checkNotNull(clazz);
540    }
541
542    @Override
543    public boolean apply(Class<?> input) {
544      return clazz.isAssignableFrom(input);
545    }
546
547    @Override
548    public int hashCode() {
549      return clazz.hashCode();
550    }
551
552    @Override
553    public boolean equals(@CheckForNull Object obj) {
554      if (obj instanceof SubtypeOfPredicate) {
555        SubtypeOfPredicate that = (SubtypeOfPredicate) obj;
556        return clazz == that.clazz;
557      }
558      return false;
559    }
560
561    @Override
562    public String toString() {
563      return "Predicates.subtypeOf(" + clazz.getName() + ")";
564    }
565
566    private static final long serialVersionUID = 0;
567  }
568
569  /** @see Predicates#in(Collection) */
570  private static class InPredicate<T extends @Nullable Object>
571      implements Predicate<T>, Serializable {
572    private final Collection<?> target;
573
574    private InPredicate(Collection<?> target) {
575      this.target = checkNotNull(target);
576    }
577
578    @Override
579    public boolean apply(@ParametricNullness T t) {
580      try {
581        return target.contains(t);
582      } catch (NullPointerException | ClassCastException e) {
583        return false;
584      }
585    }
586
587    @Override
588    public boolean equals(@CheckForNull Object obj) {
589      if (obj instanceof InPredicate) {
590        InPredicate<?> that = (InPredicate<?>) obj;
591        return target.equals(that.target);
592      }
593      return false;
594    }
595
596    @Override
597    public int hashCode() {
598      return target.hashCode();
599    }
600
601    @Override
602    public String toString() {
603      return "Predicates.in(" + target + ")";
604    }
605
606    private static final long serialVersionUID = 0;
607  }
608
609  /** @see Predicates#compose(Predicate, Function) */
610  private static class CompositionPredicate<A extends @Nullable Object, B extends @Nullable Object>
611      implements Predicate<A>, Serializable {
612    final Predicate<B> p;
613    final Function<A, ? extends B> f;
614
615    private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) {
616      this.p = checkNotNull(p);
617      this.f = checkNotNull(f);
618    }
619
620    @Override
621    public boolean apply(@ParametricNullness A a) {
622      return p.apply(f.apply(a));
623    }
624
625    @Override
626    public boolean equals(@CheckForNull Object obj) {
627      if (obj instanceof CompositionPredicate) {
628        CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj;
629        return f.equals(that.f) && p.equals(that.p);
630      }
631      return false;
632    }
633
634    @Override
635    public int hashCode() {
636      return f.hashCode() ^ p.hashCode();
637    }
638
639    @Override
640    public String toString() {
641      // TODO(cpovirk): maybe make this look like the method call does ("Predicates.compose(...)")
642      return p + "(" + f + ")";
643    }
644
645    private static final long serialVersionUID = 0;
646  }
647
648  /**
649   * @see Predicates#contains(Pattern)
650   */
651  @J2ktIncompatible
652  @GwtIncompatible // Only used by other GWT-incompatible code.
653  private static class ContainsPatternPredicate implements Predicate<CharSequence>, Serializable {
654    final CommonPattern pattern;
655
656    ContainsPatternPredicate(CommonPattern pattern) {
657      this.pattern = checkNotNull(pattern);
658    }
659
660    @Override
661    public boolean apply(CharSequence t) {
662      return pattern.matcher(t).find();
663    }
664
665    @Override
666    public int hashCode() {
667      // Pattern uses Object.hashCode, so we have to reach
668      // inside to build a hashCode consistent with equals.
669
670      return Objects.hashCode(pattern.pattern(), pattern.flags());
671    }
672
673    @Override
674    public boolean equals(@CheckForNull Object obj) {
675      if (obj instanceof ContainsPatternPredicate) {
676        ContainsPatternPredicate that = (ContainsPatternPredicate) obj;
677
678        // Pattern uses Object (identity) equality, so we have to reach
679        // inside to compare individual fields.
680        return Objects.equal(pattern.pattern(), that.pattern.pattern())
681            && pattern.flags() == that.pattern.flags();
682      }
683      return false;
684    }
685
686    @Override
687    public String toString() {
688      String patternString =
689          MoreObjects.toStringHelper(pattern)
690              .add("pattern", pattern.pattern())
691              .add("pattern.flags", pattern.flags())
692              .toString();
693      return "Predicates.contains(" + patternString + ")";
694    }
695
696    private static final long serialVersionUID = 0;
697  }
698
699  /**
700   * @see Predicates#containsPattern(String)
701   */
702  @J2ktIncompatible
703  @GwtIncompatible // Only used by other GWT-incompatible code.
704  private static class ContainsPatternFromStringPredicate extends ContainsPatternPredicate {
705
706    ContainsPatternFromStringPredicate(String string) {
707      super(Platform.compilePattern(string));
708    }
709
710    @Override
711    public String toString() {
712      return "Predicates.containsPattern(" + pattern.pattern() + ")";
713    }
714
715    private static final long serialVersionUID = 0;
716  }
717
718  private static <T extends @Nullable Object> List<Predicate<? super T>> asList(
719      Predicate<? super T> first, Predicate<? super T> second) {
720    // TODO(kevinb): understand why we still get a warning despite @SafeVarargs!
721    return Arrays.<Predicate<? super T>>asList(first, second);
722  }
723
724  private static <T> List<T> defensiveCopy(T... array) {
725    return defensiveCopy(Arrays.asList(array));
726  }
727
728  static <T> List<T> defensiveCopy(Iterable<T> iterable) {
729    ArrayList<T> list = new ArrayList<>();
730    for (T element : iterable) {
731      list.add(checkNotNull(element));
732    }
733    return list;
734  }
735}