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