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