size_hinter
Iterator adaptors for overriding or specifying exact size hints in Rust.
Overview
size_hinter provides an extension trait two iterator adaptors that allow you to control size_hint() and len() behavior of iterators, and a trait for fluently creating these adaptors.
ExactLen: Wraps an iterator to provide an exact length viaExactSizeIterator::len()and a corespondingIterator::size_hint(). This is useful when you know the exact length of an iterator that doesn't normally implementExactSizeIterator(likeFilter).HintSize: Wraps anIteratorin an adaptor that provides a customIterator::size_hint()implementation only. This is primarily useful for implementing a fixed universal size hint(0, None)for testing.SizeHinter: An extension trait for fluently creating these adaptors.
Usage
ExactLen - Adding Exact Length to Iterators
ExactLen provides an exact length via ExactSizeIterator::len() and a coresponding Iterator::size_hint(). This is useful when you know the exact length of an iterator that doesn't normally implement ExactSizeIterator (like Filter), and may allow for some performance optimizations.
use SizeHinter;
// Filter doesn't implement ExactSizeIterator, but we know there are 3 odd numbers
let mut nums = .filter.exact_len;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
HintSize - Overrides Size Hints
HintSize provides a custom Iterator::size_hint() implementation only. This is primarily useful for implementing a fixed universal size hint (0, None) for testing, but any valid size hint can be provided.
use SizeHinter;
// Hide the size hint completely (returns (0, None))
let mut hidden = vec!.into_iter.hide_size;
assert_eq!;
assert_eq!;
assert_eq!;
// Provide a custom size hint
let mut custom = vec!.into_iter.hint_size;
assert_eq!;
assert_eq!;
assert_eq!;
Performance Considerations
Wrapping an iterator that does not provide a detailed size hint or implement ExactSizeIterator may allow for some optimizations or performance improvements. However, it may lead to performance penalties if the wrapped iterator already implements TrustedLen, even if it does not implement ExactSizeIterator. For example, std::iter::Chain. Since this adaptor hides that implementation.
Safety
Neither ExactLen nor HintSize should be unsafe to use in any scenario, regardless of the values they return. However it is the caller's responsibility to ensure that the length provided are accurate. Providing an incorrect length may lead to incorrect behavior or panics in code that relies on these values.