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