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.collections4.bloomfilter;
18
19 import java.util.function.LongPredicate;
20
21 /**
22 * A long predicate that applies the test func to each member of the {@code ary} in sequence for each call to {@code test()}.
23 * if the {@code ary} is exhausted, the subsequent calls to {@code test} are executed with a zero value.
24 * If the calls to {@code test} do not exhaust the {@code ary} the {@code processRemaining} method can be called to
25 * execute the @{code test} with a zero value for each remaining {@code idx} value.
26 */
27 class CountingLongPredicate implements LongPredicate {
28
29 private int idx;
30 private final long[] ary;
31 private final LongBiPredicate func;
32
33 /**
34 * Constructs an instance that will compare the elements in {@code ary} with the elements returned by {@code func}.
35 * function is called as {@code func.test( idxValue, otherValue )}. If there are more {@code otherValue} values than
36 * {@code idxValues} then {@code func} is called as {@code func.test( 0, otherValue )}.
37 *
38 * @param ary The array of long values to compare.
39 * @param func The function to apply to the pairs of long values.
40 */
41 CountingLongPredicate(final long[] ary, final LongBiPredicate func) {
42 this.ary = ary;
43 this.func = func;
44 }
45
46 /**
47 * Call the long-long consuming bi-predicate for each remaining unpaired long in
48 * the input array. This method should be invoked after the predicate has been
49 * passed to {@link BitMapExtractor#processBitMaps(LongPredicate)} to consume any
50 * unpaired bitmaps. The second argument to the bi-predicate will be zero.
51 *
52 * @return true if all calls to the predicate were successful
53 */
54 boolean processRemaining() {
55 // uses local references for optimization benefit.
56 int i = idx;
57 final long[] a = ary;
58 final int limit = a.length;
59 while (i != limit && func.test(a[i], 0)) {
60 i++;
61 }
62 return i == limit;
63 }
64
65 @Override
66 public boolean test(final long other) {
67 return func.test(idx == ary.length ? 0 : ary[idx++], other);
68 }
69 }