1 /*
2  * Copyright 2014 - 2020 Rafael Winterhalter
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 package net.bytebuddy.matcher;
17
18 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
19 import net.bytebuddy.build.HashCodeAndEqualsPlugin;
20
21 import java.util.Collection;
22
23 /**
24  * An element matcher that matches a collection by its size.
25  *
26  * @param <T> The type of the matched entity.
27  */

28 @HashCodeAndEqualsPlugin.Enhance
29 public class CollectionSizeMatcher<T extends Iterable<?>> extends ElementMatcher.Junction.AbstractBase<T> {
30
31     /**
32      * The expected size of the matched collection.
33      */

34     private final int size;
35
36     /**
37      * Creates a new matcher that matches the size of a matched collection.
38      *
39      * @param size The expected size of the matched collection.
40      */

41     public CollectionSizeMatcher(int size) {
42         this.size = size;
43     }
44
45     /**
46      * {@inheritDoc}
47      */

48     @SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE", justification = "Iteration required to count size of an iterable")
49     public boolean matches(T target) {
50         if (target instanceof Collection) {
51             return ((Collection<?>) target).size() == size;
52         } else {
53             int size = 0;
54             for (Object ignored : target) {
55                 size++;
56             }
57             return size == this.size;
58         }
59     }
60
61     @Override
62     public String toString() {
63         return "ofSize(" + size + ')';
64     }
65 }
66