Iterator size_hint Guides Collect Allocation

Override size_hint on a custom iterator so collect reserves capacity up front, and compare it with a wrapper that hides the hint and grows as it pushes.

RustData Integrity

Code

rustsnippet
55 lines
struct RecordIds {
    next: u32,
    end: u32,
}

impl RecordIds {
    fn new(start: u32, end: u32) -> Self {
        Self { next: start, end }
    }
}

impl Iterator for RecordIds {
    type Item = u32;

    fn next(&mut self) -> Option<u32> {
        if self.next >= self.end {
            return None;
        }
        let id = self.next;
        self.next += 1;
        Some(id)
    }

    // 剩余元素数精确可知:默认的 (0, None) 会让 collect 从头反复扩容
    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = (self.end - self.next) as usize;
        (remaining, Some(remaining))
    }
}

// size_hint 精确时才能声称精确长度,len() 由它推导
impl ExactSizeIterator for RecordIds {}

// 只转发 next:其余与 RecordIds 完全一样,但把 size_hint 藏起来
struct Opaque<I>(I);

impl<I: Iterator> Iterator for Opaque<I> {
    type Item = I::Item;

    fn next(&mut self) -> Option<I::Item> {
        self.0.next()
    }
}

fn main() {
    let ids = RecordIds::new(10, 16);
    println!("len from size_hint: {}", ids.len());

    let hinted: Vec<u32> = RecordIds::new(0, 1000).collect();
    let hidden: Vec<u32> = Opaque(RecordIds::new(0, 1000)).collect();

    println!("hinted len {} capacity {}", hinted.len(), hinted.capacity());
    println!("hidden len {} capacity {}", hidden.len(), hidden.capacity());
    println!("same elements: {}", hinted == hidden);
}

How it works

The code’s whole job belongs to the functions new, next, size_hint and main.

Caveats

  • No dependencies section needed; the standard library is the whole story.

Using it

The primary signature is fn new(start: u32, end: u32) -> Self

The run emits 4 labeled sections — len from size_hint:, hinted len, hidden len, same elements: — one per step.

The comparison only separates the two paths above the small-allocation boundary, which is why the demo collects 1,000 elements rather than a handful. With the exact hint, collect reserves the full remaining length up front, so the hinted line prints capacity equal to len (1000). The Opaque wrapper collapses the hint to the default (0, None), so that Vec starts empty and doubles through the growth sequence as it pushes — its final capacity overshoots 1,000, landing on the next power-of-two step above it. Both vectors hold identical elements, so same elements: true separates element equality from allocation behavior.

main sequences new; executing the file runs that flow once.

Key statements

let hidden: Vec<u32> = Opaque(RecordIds::new(0, 1000)).collect();
let hinted: Vec<u32> = RecordIds::new(0, 1000).collect();
fn size_hint(&self) -> (usize, Option<usize>) {
let remaining = (self.end - self.next) as usize;
(remaining, Some(remaining))
}

Interactive Tools for This Topic

FAQ

What does Iterator size_hint Guides Collect Allocation print when run?
No setup needed: run the file and look for labeled lines like `len from size_hint:`, `hinted len`, `hidden len` in the output.