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