Skip to main content

core/io/
size_hint.rs

1/// Internal trait used to allow for specialization in `Read::size_hint` and
2/// `Iterator::size_hint`.
3///
4/// All types implement this through a blanket default implementation returning
5/// a hint of `(0, None)`.
6///
7/// Implementors should only provide [`lower_bound`](SizeHint::lower_bound) and
8/// [`upper_bound`](SizeHint::upper_bound).
9/// [`size_hint`](SizeHint::size_hint) is provided as a `final` method to enforce
10/// correctness.
11#[doc(hidden)]
12#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
13pub trait SizeHint {
14    /// Returns a lower bound on the number of elements this container-like item
15    /// contains.
16    /// For example, an array `[u8; 12]` could return any value between `0` and
17    /// `12` inclusively as a correct implementation.
18    ///
19    /// Through specialization, all types implement this method returning a default
20    /// value of `0`.
21    ///
22    /// Implementations *must* ensure the returned value is less than or equal to
23    /// the true element count.
24    fn lower_bound(&self) -> usize;
25
26    /// Returns an upper bound on the number of elements this container-like item
27    /// contains if it can be determined, otherwise `None`.
28    ///
29    /// Through specialization, all types implement this method returning a default
30    /// value of `None`.
31    ///
32    /// Implementations *must* ensure the returned value is greater than or equal
33    /// to the true element count.
34    fn upper_bound(&self) -> Option<usize>;
35
36    /// Returns an estimate for the number of elements this container like type
37    /// contains.
38    ///
39    /// This is a `final` method, and is guaranteed to return
40    /// `(self.lower_bound(), self.upper_bound())`.
41    ///
42    /// Without specialization, types implementing this trait will return `(0, None)`.
43    final fn size_hint(&self) -> (usize, Option<usize>) {
44        (self.lower_bound(), self.upper_bound())
45    }
46}
47
48#[doc(hidden)]
49#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
50impl<T: ?Sized> SizeHint for T {
51    #[inline]
52    default fn lower_bound(&self) -> usize {
53        0
54    }
55
56    #[inline]
57    default fn upper_bound(&self) -> Option<usize> {
58        None
59    }
60}