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  @GwtIncompatible // Only used by other GWT-incompatible code.
239  public static Predicate<CharSequence> containsPattern(String pattern) {
240    return new ContainsPatternFromStringPredicate(pattern);
241  }
242
243  /**
244   * Returns a predicate that evaluates to {@code true} if the {@code CharSequence} being tested
245   * contains any match for the given regular expression pattern. The test used is equivalent to
246   * {@code pattern.matcher(arg).find()}
247   *
248   * @since 3.0
249   */
250  @GwtIncompatible(value = "java.util.regex.Pattern")
251  public static Predicate<CharSequence> contains(Pattern pattern) {
252    return new ContainsPatternPredicate(new JdkPattern(pattern));
253  }
254
255  // End public API, begin private implementation classes.
256
257  // Package private for GWT serialization.
258  enum ObjectPredicate implements Predicate<@Nullable Object> {
259    /** @see Predicates#alwaysTrue() */
260    ALWAYS_TRUE {
261      @Override
262      public boolean apply(@CheckForNull Object o) {
263        return true;
264      }
265
266      @Override
267      public String toString() {
268        return "Predicates.alwaysTrue()";
269      }
270    },
271    /** @see Predicates#alwaysFalse() */
272    ALWAYS_FALSE {
273      @Override
274      public boolean apply(@CheckForNull Object o) {
275        return false;
276      }
277
278      @Override
279      public String toString() {
280        return "Predicates.alwaysFalse()";
281      }
282    },
283    /** @see Predicates#isNull() */
284    IS_NULL {
285      @Override
286      public boolean apply(@CheckForNull Object o) {
287        return o == null;
288      }
289
290      @Override
291      public String toString() {
292        return "Predicates.isNull()";
293      }
294    },
295    /** @see Predicates#notNull() */
296    NOT_NULL {
297      @Override
298      public boolean apply(@CheckForNull Object o) {
299        return o != null;
300      }
301
302      @Override
303      public String toString() {
304        return "Predicates.notNull()";
305      }
306    };
307
308    @SuppressWarnings("unchecked") // safe contravariant cast
309    <T extends @Nullable Object> Predicate<T> withNarrowedType() {
310      return (Predicate<T>) this;
311    }
312  }
313
314  /** @see Predicates#not(Predicate) */
315  private static class NotPredicate<T extends @Nullable Object>
316      implements Predicate<T>, Serializable {
317    final Predicate<T> predicate;
318
319    NotPredicate(Predicate<T> predicate) {
320      this.predicate = checkNotNull(predicate);
321    }
322
323    @Override
324    public boolean apply(@ParametricNullness T t) {
325      return !predicate.apply(t);
326    }
327
328    @Override
329    public int hashCode() {
330      return ~predicate.hashCode();
331    }
332
333    @Override
334    public boolean equals(@CheckForNull Object obj) {
335      if (obj instanceof NotPredicate) {
336        NotPredicate<?> that = (NotPredicate<?>) obj;
337        return predicate.equals(that.predicate);
338      }
339      return false;
340    }
341
342    @Override
343    public String toString() {
344      return "Predicates.not(" + predicate + ")";
345    }
346
347    private static final long serialVersionUID = 0;
348  }
349
350  /** @see Predicates#and(Iterable) */
351  private static class AndPredicate<T extends @Nullable Object>
352      implements Predicate<T>, Serializable {
353    private final List<? extends Predicate<? super T>> components;
354
355    private AndPredicate(List<? extends Predicate<? super T>> components) {
356      this.components = components;
357    }
358
359    @Override
360    public boolean apply(@ParametricNullness T t) {
361      // Avoid using the Iterator to avoid generating garbage (issue 820).
362      for (int i = 0; i < components.size(); i++) {
363        if (!components.get(i).apply(t)) {
364          return false;
365        }
366      }
367      return true;
368    }
369
370    @Override
371    public int hashCode() {
372      // add a random number to avoid collisions with OrPredicate
373      return components.hashCode() + 0x12472c2c;
374    }
375
376    @Override
377    public boolean equals(@CheckForNull Object obj) {
378      if (obj instanceof AndPredicate) {
379        AndPredicate<?> that = (AndPredicate<?>) obj;
380        return components.equals(that.components);
381      }
382      return false;
383    }
384
385    @Override
386    public String toString() {
387      return toStringHelper("and", components);
388    }
389
390    private static final long serialVersionUID = 0;
391  }
392
393  /** @see Predicates#or(Iterable) */
394  private static class OrPredicate<T extends @Nullable Object>
395      implements Predicate<T>, Serializable {
396    private final List<? extends Predicate<? super T>> components;
397
398    private OrPredicate(List<? extends Predicate<? super T>> components) {
399      this.components = components;
400    }
401
402    @Override
403    public boolean apply(@ParametricNullness T t) {
404      // Avoid using the Iterator to avoid generating garbage (issue 820).
405      for (int i = 0; i < components.size(); i++) {
406        if (components.get(i).apply(t)) {
407          return true;
408        }
409      }
410      return false;
411    }
412
413    @Override
414    public int hashCode() {
415      // add a random number to avoid collisions with AndPredicate
416      return components.hashCode() + 0x053c91cf;
417    }
418
419    @Override
420    public boolean equals(@CheckForNull Object obj) {
421      if (obj instanceof OrPredicate) {
422        OrPredicate<?> that = (OrPredicate<?>) obj;
423        return components.equals(that.components);
424      }
425      return false;
426    }
427
428    @Override
429    public String toString() {
430      return toStringHelper("or", components);
431    }
432
433    private static final long serialVersionUID = 0;
434  }
435
436  private static String toStringHelper(String methodName, Iterable<?> components) {
437    StringBuilder builder = new StringBuilder("Predicates.").append(methodName).append('(');
438    boolean first = true;
439    for (Object o : components) {
440      if (!first) {
441        builder.append(',');
442      }
443      builder.append(o);
444      first = false;
445    }
446    return builder.append(')').toString();
447  }
448
449  /** @see Predicates#equalTo(Object) */
450  private static class IsEqualToPredicate implements Predicate<@Nullable Object>, Serializable {
451    private final Object target;
452
453    private IsEqualToPredicate(Object target) {
454      this.target = target;
455    }
456
457    @Override
458    public boolean apply(@CheckForNull Object o) {
459      return target.equals(o);
460    }
461
462    @Override
463    public int hashCode() {
464      return target.hashCode();
465    }
466
467    @Override
468    public boolean equals(@CheckForNull Object obj) {
469      if (obj instanceof IsEqualToPredicate) {
470        IsEqualToPredicate that = (IsEqualToPredicate) obj;
471        return target.equals(that.target);
472      }
473      return false;
474    }
475
476    @Override
477    public String toString() {
478      return "Predicates.equalTo(" + target + ")";
479    }
480
481    private static final long serialVersionUID = 0;
482
483    @SuppressWarnings("unchecked") // safe contravariant cast
484    <T extends @Nullable Object> Predicate<T> withNarrowedType() {
485      return (Predicate<T>) this;
486    }
487  }
488
489  /**
490   * @see Predicates#instanceOf(Class)
491   */
492  @GwtIncompatible // Class.isInstance
493  private static class InstanceOfPredicate<T extends @Nullable Object>
494      implements Predicate<T>, Serializable {
495    private final Class<?> clazz;
496
497    private InstanceOfPredicate(Class<?> clazz) {
498      this.clazz = checkNotNull(clazz);
499    }
500
501    @Override
502    public boolean apply(@ParametricNullness T o) {
503      return clazz.isInstance(o);
504    }
505
506    @Override
507    public int hashCode() {
508      return clazz.hashCode();
509    }
510
511    @Override
512    public boolean equals(@CheckForNull Object obj) {
513      if (obj instanceof InstanceOfPredicate) {
514        InstanceOfPredicate<?> that = (InstanceOfPredicate<?>) obj;
515        return clazz == that.clazz;
516      }
517      return false;
518    }
519
520    @Override
521    public String toString() {
522      return "Predicates.instanceOf(" + clazz.getName() + ")";
523    }
524
525    @J2ktIncompatible private static final long serialVersionUID = 0;
526  }
527
528  /**
529   * @see Predicates#subtypeOf(Class)
530   */
531  @J2ktIncompatible
532  @GwtIncompatible // Class.isAssignableFrom
533  private static class SubtypeOfPredicate implements Predicate<Class<?>>, Serializable {
534    private final Class<?> clazz;
535
536    private SubtypeOfPredicate(Class<?> clazz) {
537      this.clazz = checkNotNull(clazz);
538    }
539
540    @Override
541    public boolean apply(Class<?> input) {
542      return clazz.isAssignableFrom(input);
543    }
544
545    @Override
546    public int hashCode() {
547      return clazz.hashCode();
548    }
549
550    @Override
551    public boolean equals(@CheckForNull Object obj) {
552      if (obj instanceof SubtypeOfPredicate) {
553        SubtypeOfPredicate that = (SubtypeOfPredicate) obj;
554        return clazz == that.clazz;
555      }
556      return false;
557    }
558
559    @Override
560    public String toString() {
561      return "Predicates.subtypeOf(" + clazz.getName() + ")";
562    }
563
564    private static final long serialVersionUID = 0;
565  }
566
567  /** @see Predicates#in(Collection) */
568  private static class InPredicate<T extends @Nullable Object>
569      implements Predicate<T>, Serializable {
570    private final Collection<?> target;
571
572    private InPredicate(Collection<?> target) {
573      this.target = checkNotNull(target);
574    }
575
576    @Override
577    public boolean apply(@ParametricNullness T t) {
578      try {
579        return target.contains(t);
580      } catch (NullPointerException | ClassCastException e) {
581        return false;
582      }
583    }
584
585    @Override
586    public boolean equals(@CheckForNull Object obj) {
587      if (obj instanceof InPredicate) {
588        InPredicate<?> that = (InPredicate<?>) obj;
589        return target.equals(that.target);
590      }
591      return false;
592    }
593
594    @Override
595    public int hashCode() {
596      return target.hashCode();
597    }
598
599    @Override
600    public String toString() {
601      return "Predicates.in(" + target + ")";
602    }
603
604    private static final long serialVersionUID = 0;
605  }
606
607  /** @see Predicates#compose(Predicate, Function) */
608  private static class CompositionPredicate<A extends @Nullable Object, B extends @Nullable Object>
609      implements Predicate<A>, Serializable {
610    final Predicate<B> p;
611    final Function<A, ? extends B> f;
612
613    private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) {
614      this.p = checkNotNull(p);
615      this.f = checkNotNull(f);
616    }
617
618    @Override
619    public boolean apply(@ParametricNullness A a) {
620      return p.apply(f.apply(a));
621    }
622
623    @Override
624    public boolean equals(@CheckForNull Object obj) {
625      if (obj instanceof CompositionPredicate) {
626        CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj;
627        return f.equals(that.f) && p.equals(that.p);
628      }
629      return false;
630    }
631
632    @Override
633    public int hashCode() {
634      return f.hashCode() ^ p.hashCode();
635    }
636
637    @Override
638    public String toString() {
639      // TODO(cpovirk): maybe make this look like the method call does ("Predicates.compose(...)")
640      return p + "(" + f + ")";
641    }
642
643    private static final long serialVersionUID = 0;
644  }
645
646  /**
647   * @see Predicates#contains(Pattern)
648   */
649  @GwtIncompatible // Only used by other GWT-incompatible code.
650  private static class ContainsPatternPredicate implements Predicate<CharSequence>, Serializable {
651    final CommonPattern pattern;
652
653    ContainsPatternPredicate(CommonPattern pattern) {
654      this.pattern = checkNotNull(pattern);
655    }
656
657    @Override
658    public boolean apply(CharSequence t) {
659      return pattern.matcher(t).find();
660    }
661
662    @Override
663    public int hashCode() {
664      // Pattern uses Object.hashCode, so we have to reach
665      // inside to build a hashCode consistent with equals.
666
667      return Objects.hashCode(pattern.pattern(), pattern.flags());
668    }
669
670    @Override
671    public boolean equals(@CheckForNull Object obj) {
672      if (obj instanceof ContainsPatternPredicate) {
673        ContainsPatternPredicate that = (ContainsPatternPredicate) obj;
674
675        // Pattern uses Object (identity) equality, so we have to reach
676        // inside to compare individual fields.
677        return Objects.equal(pattern.pattern(), that.pattern.pattern())
678            && pattern.flags() == that.pattern.flags();
679      }
680      return false;
681    }
682
683    @Override
684    public String toString() {
685      String patternString =
686          MoreObjects.toStringHelper(pattern)
687              .add("pattern", pattern.pattern())
688              .add("pattern.flags", pattern.flags())
689              .toString();
690      return "Predicates.contains(" + patternString + ")";
691    }
692
693    private static final long serialVersionUID = 0;
694  }
695
696  /**
697   * @see Predicates#containsPattern(String)
698   */
699  @GwtIncompatible // Only used by other GWT-incompatible code.
700  private static class ContainsPatternFromStringPredicate extends ContainsPatternPredicate {
701
702    ContainsPatternFromStringPredicate(String string) {
703      super(Platform.compilePattern(string));
704    }
705
706    @Override
707    public String toString() {
708      return "Predicates.containsPattern(" + pattern.pattern() + ")";
709    }
710
711    private static final long serialVersionUID = 0;
712  }
713
714  private static <T extends @Nullable Object> List<Predicate<? super T>> asList(
715      Predicate<? super T> first, Predicate<? super T> second) {
716    // TODO(kevinb): understand why we still get a warning despite @SafeVarargs!
717    return Arrays.<Predicate<? super T>>asList(first, second);
718  }
719
720  private static <T> List<T> defensiveCopy(T... array) {
721    return defensiveCopy(Arrays.asList(array));
722  }
723
724  static <T> List<T> defensiveCopy(Iterable<T> iterable) {
725    ArrayList<T> list = new ArrayList<>();
726    for (T element : iterable) {
727      list.add(checkNotNull(element));
728    }
729    return list;
730  }
731}