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 ContainsPatternPredicate(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    ALWAYS_TRUE {
277      @Override public boolean apply(@Nullable Object o) {
278        return true;
279      }
280    },
281    ALWAYS_FALSE {
282      @Override public boolean apply(@Nullable Object o) {
283        return false;
284      }
285    },
286    IS_NULL {
287      @Override public boolean apply(@Nullable Object o) {
288        return o == null;
289      }
290    },
291    NOT_NULL {
292      @Override public boolean apply(@Nullable Object o) {
293        return o != null;
294      }
295    };
296
297    @SuppressWarnings("unchecked") // these Object predicates work for any T
298    <T> Predicate<T> withNarrowedType() {
299      return (Predicate<T>) this;
300    }
301  }
302
303  /** @see Predicates#not(Predicate) */
304  private static class NotPredicate<T> implements Predicate<T>, Serializable {
305    final Predicate<T> predicate;
306
307    NotPredicate(Predicate<T> predicate) {
308      this.predicate = checkNotNull(predicate);
309    }
310    @Override
311    public boolean apply(@Nullable T t) {
312      return !predicate.apply(t);
313    }
314    @Override public int hashCode() {
315      return ~predicate.hashCode();
316    }
317    @Override public boolean equals(@Nullable Object obj) {
318      if (obj instanceof NotPredicate) {
319        NotPredicate<?> that = (NotPredicate<?>) obj;
320        return predicate.equals(that.predicate);
321      }
322      return false;
323    }
324    @Override public String toString() {
325      return "Not(" + predicate.toString() + ")";
326    }
327    private static final long serialVersionUID = 0;
328  }
329
330  private static final Joiner COMMA_JOINER = Joiner.on(",");
331
332  /** @see Predicates#and(Iterable) */
333  private static class AndPredicate<T> implements Predicate<T>, Serializable {
334    private final List<? extends Predicate<? super T>> components;
335
336    private AndPredicate(List<? extends Predicate<? super T>> components) {
337      this.components = components;
338    }
339    @Override
340    public boolean apply(@Nullable T t) {
341      // Avoid using the Iterator to avoid generating garbage (issue 820).
342      for (int i = 0; i < components.size(); i++) {
343        if (!components.get(i).apply(t)) {
344          return false;
345        }
346      }
347      return true;
348    }
349    @Override public int hashCode() {
350      // add a random number to avoid collisions with OrPredicate
351      return components.hashCode() + 0x12472c2c;
352    }
353    @Override public boolean equals(@Nullable Object obj) {
354      if (obj instanceof AndPredicate) {
355        AndPredicate<?> that = (AndPredicate<?>) obj;
356        return components.equals(that.components);
357      }
358      return false;
359    }
360    @Override public String toString() {
361      return "And(" + COMMA_JOINER.join(components) + ")";
362    }
363    private static final long serialVersionUID = 0;
364  }
365
366  /** @see Predicates#or(Iterable) */
367  private static class OrPredicate<T> implements Predicate<T>, Serializable {
368    private final List<? extends Predicate<? super T>> components;
369
370    private OrPredicate(List<? extends Predicate<? super T>> components) {
371      this.components = components;
372    }
373    @Override
374    public boolean apply(@Nullable T t) {
375      // Avoid using the Iterator to avoid generating garbage (issue 820).
376      for (int i = 0; i < components.size(); i++) {
377        if (components.get(i).apply(t)) {
378          return true;
379        }
380      }
381      return false;
382    }
383    @Override public int hashCode() {
384      // add a random number to avoid collisions with AndPredicate
385      return components.hashCode() + 0x053c91cf;
386    }
387    @Override public boolean equals(@Nullable Object obj) {
388      if (obj instanceof OrPredicate) {
389        OrPredicate<?> that = (OrPredicate<?>) obj;
390        return components.equals(that.components);
391      }
392      return false;
393    }
394    @Override public String toString() {
395      return "Or(" + COMMA_JOINER.join(components) + ")";
396    }
397    private static final long serialVersionUID = 0;
398  }
399
400  /** @see Predicates#equalTo(Object) */
401  private static class IsEqualToPredicate<T>
402      implements Predicate<T>, Serializable {
403    private final T target;
404
405    private IsEqualToPredicate(T target) {
406      this.target = target;
407    }
408    @Override
409    public boolean apply(T t) {
410      return target.equals(t);
411    }
412    @Override public int hashCode() {
413      return target.hashCode();
414    }
415    @Override public boolean equals(@Nullable Object obj) {
416      if (obj instanceof IsEqualToPredicate) {
417        IsEqualToPredicate<?> that = (IsEqualToPredicate<?>) obj;
418        return target.equals(that.target);
419      }
420      return false;
421    }
422    @Override public String toString() {
423      return "IsEqualTo(" + target + ")";
424    }
425    private static final long serialVersionUID = 0;
426  }
427
428  /** @see Predicates#instanceOf(Class) */
429  @GwtIncompatible("Class.isInstance")
430  private static class InstanceOfPredicate
431      implements Predicate<Object>, Serializable {
432    private final Class<?> clazz;
433
434    private InstanceOfPredicate(Class<?> clazz) {
435      this.clazz = checkNotNull(clazz);
436    }
437    @Override
438    public boolean apply(@Nullable Object o) {
439      return clazz.isInstance(o);
440    }
441    @Override public int hashCode() {
442      return clazz.hashCode();
443    }
444    @Override public boolean equals(@Nullable Object obj) {
445      if (obj instanceof InstanceOfPredicate) {
446        InstanceOfPredicate that = (InstanceOfPredicate) obj;
447        return clazz == that.clazz;
448      }
449      return false;
450    }
451    @Override public String toString() {
452      return "IsInstanceOf(" + clazz.getName() + ")";
453    }
454    private static final long serialVersionUID = 0;
455  }
456
457  /** @see Predicates#assignableFrom(Class) */
458  @GwtIncompatible("Class.isAssignableFrom")
459  private static class AssignableFromPredicate
460      implements Predicate<Class<?>>, Serializable {
461    private final Class<?> clazz;
462
463    private AssignableFromPredicate(Class<?> clazz) {
464      this.clazz = checkNotNull(clazz);
465    }
466    @Override
467    public boolean apply(Class<?> input) {
468      return clazz.isAssignableFrom(input);
469    }
470    @Override public int hashCode() {
471      return clazz.hashCode();
472    }
473    @Override public boolean equals(@Nullable Object obj) {
474      if (obj instanceof AssignableFromPredicate) {
475        AssignableFromPredicate that = (AssignableFromPredicate) obj;
476        return clazz == that.clazz;
477      }
478      return false;
479    }
480    @Override public String toString() {
481      return "IsAssignableFrom(" + clazz.getName() + ")";
482    }
483    private static final long serialVersionUID = 0;
484  }
485
486  /** @see Predicates#in(Collection) */
487  private static class InPredicate<T> implements Predicate<T>, Serializable {
488    private final Collection<?> target;
489
490    private InPredicate(Collection<?> target) {
491      this.target = checkNotNull(target);
492    }
493
494    @Override
495    public boolean apply(@Nullable T t) {
496      try {
497        return target.contains(t);
498      } catch (NullPointerException e) {
499        return false;
500      } catch (ClassCastException e) {
501        return false;
502      }
503    }
504
505    @Override public boolean equals(@Nullable Object obj) {
506      if (obj instanceof InPredicate) {
507        InPredicate<?> that = (InPredicate<?>) obj;
508        return target.equals(that.target);
509      }
510      return false;
511    }
512
513    @Override public int hashCode() {
514      return target.hashCode();
515    }
516
517    @Override public String toString() {
518      return "In(" + target + ")";
519    }
520    private static final long serialVersionUID = 0;
521  }
522
523  /** @see Predicates#compose(Predicate, Function) */
524  private static class CompositionPredicate<A, B>
525      implements Predicate<A>, Serializable {
526    final Predicate<B> p;
527    final Function<A, ? extends B> f;
528
529    private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) {
530      this.p = checkNotNull(p);
531      this.f = checkNotNull(f);
532    }
533
534    @Override
535    public boolean apply(@Nullable A a) {
536      return p.apply(f.apply(a));
537    }
538
539    @Override public boolean equals(@Nullable Object obj) {
540      if (obj instanceof CompositionPredicate) {
541        CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj;
542        return f.equals(that.f) && p.equals(that.p);
543      }
544      return false;
545    }
546
547    @Override public int hashCode() {
548      return f.hashCode() ^ p.hashCode();
549    }
550
551    @Override public String toString() {
552      return p.toString() + "(" + f.toString() + ")";
553    }
554
555    private static final long serialVersionUID = 0;
556  }
557
558  /**
559   * @see Predicates#contains(Pattern)
560   * @see Predicates#containsPattern(String)
561   */
562  @GwtIncompatible("Only used by other GWT-incompatible code.")
563  private static class ContainsPatternPredicate
564      implements Predicate<CharSequence>, Serializable {
565    final Pattern pattern;
566
567    ContainsPatternPredicate(Pattern pattern) {
568      this.pattern = checkNotNull(pattern);
569    }
570
571    ContainsPatternPredicate(String patternStr) {
572      this(Pattern.compile(patternStr));
573    }
574
575    @Override
576    public boolean apply(CharSequence t) {
577      return pattern.matcher(t).find();
578    }
579
580    @Override public int hashCode() {
581      // Pattern uses Object.hashCode, so we have to reach
582      // inside to build a hashCode consistent with equals.
583
584      return Objects.hashCode(pattern.pattern(), pattern.flags());
585    }
586
587    @Override public boolean equals(@Nullable Object obj) {
588      if (obj instanceof ContainsPatternPredicate) {
589        ContainsPatternPredicate that = (ContainsPatternPredicate) obj;
590
591        // Pattern uses Object (identity) equality, so we have to reach
592        // inside to compare individual fields.
593        return Objects.equal(pattern.pattern(), that.pattern.pattern())
594            && Objects.equal(pattern.flags(), that.pattern.flags());
595      }
596      return false;
597    }
598
599    @Override public String toString() {
600      return Objects.toStringHelper(this)
601          .add("pattern", pattern)
602          .add("pattern.flags", Integer.toHexString(pattern.flags()))
603          .toString();
604    }
605
606    private static final long serialVersionUID = 0;
607  }
608
609  @SuppressWarnings("unchecked")
610  private static <T> List<Predicate<? super T>> asList(
611      Predicate<? super T> first, Predicate<? super T> second) {
612    return Arrays.<Predicate<? super T>>asList(first, second);
613  }
614
615  private static <T> List<T> defensiveCopy(T... array) {
616    return defensiveCopy(Arrays.asList(array));
617  }
618
619  static <T> List<T> defensiveCopy(Iterable<T> iterable) {
620    ArrayList<T> list = new ArrayList<T>();
621    for (T element : iterable) {
622      list.add(checkNotNull(element));
623    }
624    return list;
625  }
626}