1/*
2 * Copyright (C) 2007 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.common.base;
18
19import static com.google.common.base.Preconditions.checkNotNull;
20
21import com.google.common.annotations.GwtCompatible;
22
23import java.io.Serializable;
24import java.util.ArrayList;
25import java.util.Arrays;
26import java.util.Collection;
27import java.util.List;
28
29import javax.annotation.Nullable;
30
31/**
32 * Static utility methods pertaining to {@code Predicate} instances.
33 *
34 * <p>All methods returns serializable predicates as long as they're given
35 * serializable parameters.
36 *
37 * @author Kevin Bourrillion
38 * @since 2.0 (imported from Google Collections Library)
39 */
40@GwtCompatible(emulated = true)
41public final class Predicates {
42  private Predicates() {}
43
44  // TODO(kevinb): considering having these implement a VisitablePredicate
45  // interface which specifies an accept(PredicateVisitor) method.
46
47  /**
48   * Returns a predicate that always evaluates to {@code true}.
49   */
50  @GwtCompatible(serializable = true)
51  public static <T> Predicate<T> alwaysTrue() {
52    return ObjectPredicate.ALWAYS_TRUE.withNarrowedType();
53  }
54
55  /**
56   * Returns a predicate that always evaluates to {@code false}.
57   */
58  @GwtCompatible(serializable = true)
59  public static <T> Predicate<T> alwaysFalse() {
60    return ObjectPredicate.ALWAYS_FALSE.withNarrowedType();
61  }
62
63  /**
64   * Returns a predicate that evaluates to {@code true} if the object reference
65   * being tested is null.
66   */
67  @GwtCompatible(serializable = true)
68  public static <T> Predicate<T> isNull() {
69    return ObjectPredicate.IS_NULL.withNarrowedType();
70  }
71
72  /**
73   * Returns a predicate that evaluates to {@code true} if the object reference
74   * being tested is not null.
75   */
76  @GwtCompatible(serializable = true)
77  public static <T> Predicate<T> notNull() {
78    return ObjectPredicate.NOT_NULL.withNarrowedType();
79  }
80
81  /**
82   * Returns a predicate that evaluates to {@code true} if the given predicate
83   * evaluates to {@code false}.
84   */
85  public static <T> Predicate<T> not(Predicate<T> predicate) {
86    return new NotPredicate<T>(predicate);
87  }
88
89  /**
90   * Returns a predicate that evaluates to {@code true} if each of its
91   * components evaluates to {@code true}. The components are evaluated in
92   * order, and evaluation will be "short-circuited" as soon as a false
93   * predicate is found. It defensively copies the iterable passed in, so future
94   * changes to it won't alter the behavior of this predicate. If {@code
95   * components} is empty, the returned predicate will always evaluate to {@code
96   * true}.
97   */
98  public static <T> Predicate<T> and(
99      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
105   * components evaluates to {@code true}. The components are evaluated in
106   * order, and evaluation will be "short-circuited" as soon as a false
107   * predicate is found. It defensively copies the array passed in, so future
108   * changes to it won't alter the behavior of this predicate. If {@code
109   * components} is empty, the returned predicate will always evaluate to {@code
110   * true}.
111   */
112  public static <T> Predicate<T> and(Predicate<? super T>... components) {
113    return new AndPredicate<T>(defensiveCopy(components));
114  }
115
116  /**
117   * Returns a predicate that evaluates to {@code true} if both of its
118   * components evaluate to {@code true}. The components are evaluated in
119   * order, and evaluation will be "short-circuited" as soon as a false
120   * predicate is found.
121   */
122  public static <T> Predicate<T> and(Predicate<? super T> first,
123      Predicate<? super T> second) {
124    return new AndPredicate<T>(Predicates.<T>asList(
125        checkNotNull(first), checkNotNull(second)));
126  }
127
128  /**
129   * Returns a predicate that evaluates to {@code true} if any one of its
130   * components evaluates to {@code true}. The components are evaluated in
131   * order, and evaluation will be "short-circuited" as soon as a
132   * true predicate is found. It defensively copies the iterable passed in, so
133   * future changes to it won't alter the behavior of this predicate. If {@code
134   * components} is empty, the returned predicate will always evaluate to {@code
135   * false}.
136   */
137  public static <T> Predicate<T> or(
138      Iterable<? extends Predicate<? super T>> components) {
139    return new OrPredicate<T>(defensiveCopy(components));
140  }
141
142  /**
143   * Returns a predicate that evaluates to {@code true} if any one of its
144   * components evaluates to {@code true}. The components are evaluated in
145   * order, and evaluation will be "short-circuited" as soon as a
146   * true predicate is found. It defensively copies the array passed in, so
147   * future changes to it won't alter the behavior of this predicate. If {@code
148   * components} is empty, the returned predicate will always evaluate to {@code
149   * false}.
150   */
151  public static <T> Predicate<T> or(Predicate<? super T>... components) {
152    return new OrPredicate<T>(defensiveCopy(components));
153  }
154
155  /**
156   * Returns a predicate that evaluates to {@code true} if either of its
157   * components evaluates to {@code true}. The components are evaluated in
158   * order, and evaluation will be "short-circuited" as soon as a
159   * true predicate is found.
160   */
161  public static <T> Predicate<T> or(
162      Predicate<? super T> first, Predicate<? super T> second) {
163    return new OrPredicate<T>(Predicates.<T>asList(
164        checkNotNull(first), checkNotNull(second)));
165  }
166
167  /**
168   * Returns a predicate that evaluates to {@code true} if the object being
169   * tested {@code equals()} the given target or both are null.
170   */
171  public static <T> Predicate<T> equalTo(@Nullable T target) {
172    return (target == null)
173        ? Predicates.<T>isNull()
174        : new IsEqualToPredicate<T>(target);
175  }
176
177  /**
178   * Returns a predicate that evaluates to {@code true} if the object reference
179   * being tested is a member of the given collection. It does not defensively
180   * copy the collection passed in, so future changes to it will alter the
181   * behavior of the predicate.
182   *
183   * <p>This method can technically accept any {@code Collection<?>}, but using
184   * a typed collection helps prevent bugs. This approach doesn't block any
185   * potential users since it is always possible to use {@code
186   * Predicates.<Object>in()}.
187   *
188   * @param target the collection that may contain the function input
189   */
190  public static <T> Predicate<T> in(Collection<? extends T> target) {
191    return new InPredicate<T>(target);
192  }
193
194  /**
195   * Returns the composition of a function and a predicate. For every {@code x},
196   * the generated predicate returns {@code predicate(function(x))}.
197   *
198   * @return the composition of the provided function and predicate
199   */
200  public static <A, B> Predicate<A> compose(
201      Predicate<B> predicate, Function<A, ? extends B> function) {
202    return new CompositionPredicate<A, B>(predicate, function);
203  }
204
205  // End public API, begin private implementation classes.
206
207  // Package private for GWT serialization.
208  enum ObjectPredicate implements Predicate<Object> {
209    ALWAYS_TRUE {
210      @Override public boolean apply(@Nullable Object o) {
211        return true;
212      }
213    },
214    ALWAYS_FALSE {
215      @Override public boolean apply(@Nullable Object o) {
216        return false;
217      }
218    },
219    IS_NULL {
220      @Override public boolean apply(@Nullable Object o) {
221        return o == null;
222      }
223    },
224    NOT_NULL {
225      @Override public boolean apply(@Nullable Object o) {
226        return o != null;
227      }
228    };
229
230    @SuppressWarnings("unchecked") // these Object predicates work for any T
231    <T> Predicate<T> withNarrowedType() {
232      return (Predicate<T>) this;
233    }
234  }
235
236  /** @see Predicates#not(Predicate) */
237  private static class NotPredicate<T> implements Predicate<T>, Serializable {
238    final Predicate<T> predicate;
239
240    NotPredicate(Predicate<T> predicate) {
241      this.predicate = checkNotNull(predicate);
242    }
243    @Override
244    public boolean apply(T t) {
245      return !predicate.apply(t);
246    }
247    @Override public int hashCode() {
248      return ~predicate.hashCode();
249    }
250    @Override public boolean equals(@Nullable Object obj) {
251      if (obj instanceof NotPredicate) {
252        NotPredicate<?> that = (NotPredicate<?>) obj;
253        return predicate.equals(that.predicate);
254      }
255      return false;
256    }
257    @Override public String toString() {
258      return "Not(" + predicate.toString() + ")";
259    }
260    private static final long serialVersionUID = 0;
261  }
262
263  private static final Joiner COMMA_JOINER = Joiner.on(",");
264
265  /** @see Predicates#and(Iterable) */
266  private static class AndPredicate<T> implements Predicate<T>, Serializable {
267    private final List<? extends Predicate<? super T>> components;
268
269    private AndPredicate(List<? extends Predicate<? super T>> components) {
270      this.components = components;
271    }
272    @Override
273    public boolean apply(T t) {
274      for (int i = 0; i < components.size(); i++) {
275        if (!components.get(i).apply(t)) {
276          return false;
277        }
278      }
279      return true;
280    }
281    @Override public int hashCode() {
282      // 0x12472c2c is a random number to help avoid collisions with OrPredicate
283      return components.hashCode() + 0x12472c2c;
284    }
285    @Override public boolean equals(@Nullable Object obj) {
286      if (obj instanceof AndPredicate) {
287        AndPredicate<?> that = (AndPredicate<?>) obj;
288        return components.equals(that.components);
289      }
290      return false;
291    }
292    @Override public String toString() {
293      return "And(" + COMMA_JOINER.join(components) + ")";
294    }
295    private static final long serialVersionUID = 0;
296  }
297
298  /** @see Predicates#or(Iterable) */
299  private static class OrPredicate<T> implements Predicate<T>, Serializable {
300    private final List<? extends Predicate<? super T>> components;
301
302    private OrPredicate(List<? extends Predicate<? super T>> components) {
303      this.components = components;
304    }
305    @Override
306    public boolean apply(T t) {
307      for (int i = 0; i < components.size(); i++) {
308        if (components.get(i).apply(t)) {
309          return true;
310        }
311      }
312      return false;
313    }
314    @Override public int hashCode() {
315      // 0x053c91cf is a random number to help avoid collisions with AndPredicate
316      return components.hashCode() + 0x053c91cf;
317    }
318    @Override public boolean equals(@Nullable Object obj) {
319      if (obj instanceof OrPredicate) {
320        OrPredicate<?> that = (OrPredicate<?>) obj;
321        return components.equals(that.components);
322      }
323      return false;
324    }
325    @Override public String toString() {
326      return "Or(" + COMMA_JOINER.join(components) + ")";
327    }
328    private static final long serialVersionUID = 0;
329  }
330
331  /** @see Predicates#equalTo(Object) */
332  private static class IsEqualToPredicate<T>
333      implements Predicate<T>, Serializable {
334    private final T target;
335
336    private IsEqualToPredicate(T target) {
337      this.target = target;
338    }
339    @Override
340    public boolean apply(T t) {
341      return target.equals(t);
342    }
343    @Override public int hashCode() {
344      return target.hashCode();
345    }
346    @Override public boolean equals(@Nullable Object obj) {
347      if (obj instanceof IsEqualToPredicate) {
348        IsEqualToPredicate<?> that = (IsEqualToPredicate<?>) obj;
349        return target.equals(that.target);
350      }
351      return false;
352    }
353    @Override public String toString() {
354      return "IsEqualTo(" + target + ")";
355    }
356    private static final long serialVersionUID = 0;
357  }
358
359  /** @see Predicates#in(Collection) */
360  private static class InPredicate<T> implements Predicate<T>, Serializable {
361    private final Collection<?> target;
362
363    private InPredicate(Collection<?> target) {
364      this.target = checkNotNull(target);
365    }
366
367    @Override
368    public boolean apply(T t) {
369      try {
370        return target.contains(t);
371      } catch (NullPointerException e) {
372        return false;
373      } catch (ClassCastException e) {
374        return false;
375      }
376    }
377
378    @Override public boolean equals(@Nullable Object obj) {
379      if (obj instanceof InPredicate) {
380        InPredicate<?> that = (InPredicate<?>) obj;
381        return target.equals(that.target);
382      }
383      return false;
384    }
385
386    @Override public int hashCode() {
387      return target.hashCode();
388    }
389
390    @Override public String toString() {
391      return "In(" + target + ")";
392    }
393    private static final long serialVersionUID = 0;
394  }
395
396  /** @see Predicates#compose(Predicate, Function) */
397  private static class CompositionPredicate<A, B>
398      implements Predicate<A>, Serializable {
399    final Predicate<B> p;
400    final Function<A, ? extends B> f;
401
402    private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) {
403      this.p = checkNotNull(p);
404      this.f = checkNotNull(f);
405    }
406
407    @Override
408    public boolean apply(A a) {
409      return p.apply(f.apply(a));
410    }
411
412    @Override public boolean equals(@Nullable Object obj) {
413      if (obj instanceof CompositionPredicate) {
414        CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj;
415        return f.equals(that.f) && p.equals(that.p);
416      }
417      return false;
418    }
419
420    @Override public int hashCode() {
421      return f.hashCode() ^ p.hashCode();
422    }
423
424    @Override public String toString() {
425      return p.toString() + "(" + f.toString() + ")";
426    }
427
428    private static final long serialVersionUID = 0;
429  }
430
431  @SuppressWarnings("unchecked")
432  private static <T> List<Predicate<? super T>> asList(
433      Predicate<? super T> first, Predicate<? super T> second) {
434    return Arrays.<Predicate<? super T>>asList(first, second);
435  }
436
437  private static <T> List<T> defensiveCopy(T... array) {
438    return defensiveCopy(Arrays.asList(array));
439  }
440
441  static <T> List<T> defensiveCopy(Iterable<T> iterable) {
442    ArrayList<T> list = new ArrayList<T>();
443    for (T element : iterable) {
444      list.add(checkNotNull(element));
445    }
446    return list;
447  }
448}
449
450