1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.functor.core;
18
19 import org.apache.commons.functor.BinaryPredicate;
20 import org.apache.commons.functor.Predicate;
21 import org.apache.commons.functor.UnaryPredicate;
22
23 /**
24 * A predicate that returns <code>true</code>
25 * the first <i>n</i> times it is invoked.
26 *
27 * @since 1.0
28 * @version $Revision: 1160412 $ $Date: 2011-08-22 22:10:41 +0200 (Mon, 22 Aug 2011) $
29 * @author Jason Horman (jason@jhorman.org)
30 * @author Rodney Waldhoff
31 */
32
33 public final class Limit implements Predicate, UnaryPredicate<Object>, BinaryPredicate<Object, Object> {
34 // instance variables
35 //---------------------------------------------------------------
36 /**
37 * The max number of times the predicate can be invoked.
38 */
39 private final int max;
40 /**
41 * The current number of times the predicate has been invoked.
42 */
43 private int current;
44
45 /**
46 * Create a new Limit.
47 * @param count limit
48 */
49 public Limit(int count) {
50 if (count < 0) {
51 throw new IllegalArgumentException("Argument must be a non-negative integer.");
52 }
53 this.max = count;
54 }
55
56 /**
57 * {@inheritDoc}
58 */
59 public synchronized boolean test() {
60 // stop incrementing when we've hit max, so we don't loop around
61 if (current < max) {
62 current++;
63 return true;
64 }
65 return false;
66 }
67
68 /**
69 * {@inheritDoc}
70 */
71 public boolean test(Object obj) {
72 return test();
73 }
74
75 /**
76 * {@inheritDoc}
77 */
78 public boolean test(Object a, Object b) {
79 return test();
80 }
81
82 /**
83 * {@inheritDoc}
84 */
85 public String toString() {
86 return "Limit<" + max + ">";
87 }
88
89 //default == equals/hashCode due to statefulness
90 }