1 // Copyright 2022 Google LLC
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 /// Counts the number of elements in `value`.
16 ///
17 /// This uses [`Iterator::size_hint`] when that function returns an
18 /// unambiguous answer, i.e., the upper bound exists and the lower and upper
19 /// bounds agree. Otherwise it iterates through `value` and counts the
20 /// elements.
count_elements<ContainerT: ?Sized>(value: &ContainerT) -> usize where for<'b> &'b ContainerT: IntoIterator,21 pub(crate) fn count_elements<ContainerT: ?Sized>(value: &ContainerT) -> usize
22 where
23 for<'b> &'b ContainerT: IntoIterator,
24 {
25 let iterator = value.into_iter();
26 if let (lower, Some(higher)) = iterator.size_hint() {
27 if lower == higher {
28 return lower;
29 }
30 }
31 iterator.count()
32 }
33