Classes in this File | Line Coverage | Branch Coverage | Complexity | ||||
SubjectUtils |
|
| 2.75;2.75 |
1 | /* | |
2 | * Copyright (c) 2011 David Saff | |
3 | * Copyright (c) 2011 Christian Gruber | |
4 | * Copyright (c) 2012 Google, Inc. | |
5 | * | |
6 | * Licensed under the Apache License, Version 2.0 (the "License"); | |
7 | * you may not use this file except in compliance with the License. | |
8 | * You may obtain a copy of the License at | |
9 | * | |
10 | * http://www.apache.org/licenses/LICENSE-2.0 | |
11 | * | |
12 | * Unless required by applicable law or agreed to in writing, software | |
13 | * distributed under the License is distributed on an "AS IS" BASIS, | |
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
15 | * See the License for the specific language governing permissions and | |
16 | * limitations under the License. | |
17 | */ | |
18 | package org.truth0.subjects; | |
19 | ||
20 | import java.util.ArrayList; | |
21 | import java.util.Arrays; | |
22 | import java.util.Collection; | |
23 | import java.util.Collections; | |
24 | import java.util.HashSet; | |
25 | import java.util.List; | |
26 | import java.util.Set; | |
27 | ||
28 | ||
29 | /** | |
30 | * Utility methods used in Subject<T> implementors. | |
31 | * | |
32 | * @author Christian Gruber (cgruber@israfil.net) | |
33 | */ | |
34 | 0 | final class SubjectUtils { |
35 | ||
36 | static <T> List<T> accumulate(T only) { | |
37 | 0 | return new ArrayList<T>(Collections.singleton(only)); |
38 | } | |
39 | @SafeVarargs static <T> List<T> accumulate(T first, T second, T ... rest) { | |
40 | // rest should never be deliberately null, so assume that the caller passed null | |
41 | // in the third position but intended it to be the third element in the array of values. | |
42 | // Javac makes the opposite inference, so handle that here. | |
43 | 0 | List<T> items = new ArrayList<T>(2 + ((rest == null) ? 1 : rest.length)); |
44 | 0 | items.add(first); |
45 | 0 | items.add(second); |
46 | 0 | if (rest == null) { |
47 | 0 | items.add(null); |
48 | } else { | |
49 | 0 | items.addAll(Arrays.asList(rest)); |
50 | } | |
51 | 0 | return items; |
52 | } | |
53 | ||
54 | static <T> int countOf(T t, Iterable<T> items) { | |
55 | 0 | int count = 0; |
56 | 0 | for (T item : items) { |
57 | 0 | if (t == null ? (item == null) : t.equals(item)) { |
58 | 0 | count++; |
59 | } | |
60 | 0 | } |
61 | 0 | return count; |
62 | } | |
63 | ||
64 | static <T> List<Object> countDuplicates(Collection<T> items) { | |
65 | 0 | Set<T> itemSet = new HashSet<T>(items); |
66 | 0 | Object[] params = new Object[itemSet.size()]; |
67 | 0 | int n = 0; |
68 | 0 | for (T item : itemSet) { |
69 | 0 | int count = countOf(item, items); |
70 | 0 | params[n++] = (count > 1) ? item + " [" + count + " copies]" : item; |
71 | 0 | } |
72 | 0 | return Arrays.asList(params); |
73 | } | |
74 | ||
75 | } |