Line data Source code
1 : // Copyright (C) 2022 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.index.query; 16 : 17 : import java.util.Collection; 18 : import java.util.Optional; 19 : 20 : public class AndCardinalPredicate<T> extends AndPredicate<T> implements HasCardinality { 21 : private final int cardinality; 22 : 23 : public AndCardinalPredicate(Collection<? extends Predicate<T>> that) { 24 7 : super(that); 25 7 : Optional<Predicate<T>> atLeastOneCardinalPredicate = 26 7 : getChildren().stream().filter(p -> (p instanceof HasCardinality)).findAny(); 27 7 : if (!atLeastOneCardinalPredicate.isPresent()) { 28 1 : throw new IllegalArgumentException("No HasCardinality Found"); 29 : } 30 6 : int minCardinality = Integer.MAX_VALUE; 31 6 : for (Predicate<T> child : getChildren()) { 32 6 : if (child instanceof HasCardinality) { 33 6 : minCardinality = Math.min(((HasCardinality) child).getCardinality(), minCardinality); 34 : } 35 6 : } 36 6 : cardinality = minCardinality; 37 6 : } 38 : 39 : @Override 40 : public Predicate<T> copy(Collection<? extends Predicate<T>> children) { 41 0 : return new AndCardinalPredicate<>(children); 42 : } 43 : 44 : @Override 45 : public int getCardinality() { 46 2 : return cardinality; 47 : } 48 : }