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 OrCardinalPredicate<T> extends OrPredicate<T> implements HasCardinality { 21 : private final int cardinality; 22 : 23 : public OrCardinalPredicate(Collection<? extends Predicate<T>> that) { 24 8 : super(that); 25 8 : Optional<Predicate<T>> nonHasCardinality = 26 8 : getChildren().stream().filter(p -> !(p instanceof HasCardinality)).findAny(); 27 8 : if (nonHasCardinality.isPresent()) { 28 1 : throw new IllegalArgumentException("No HasCardinality: " + nonHasCardinality.get()); 29 : } 30 7 : int aggregateCardinality = 0; 31 7 : for (Predicate<T> p : getChildren()) { 32 7 : if (p instanceof HasCardinality) { 33 7 : aggregateCardinality += ((HasCardinality) p).getCardinality(); 34 : } 35 7 : } 36 7 : cardinality = aggregateCardinality; 37 7 : } 38 : 39 : @Override 40 : public Predicate<T> copy(Collection<? extends Predicate<T>> children) { 41 0 : return new OrCardinalPredicate<>(children); 42 : } 43 : 44 : @Override 45 : public int getCardinality() { 46 2 : return cardinality; 47 : } 48 : }