Skip to main content

reserve_bounded

Function reserve_bounded 

Source
pub fn reserve_bounded<T>(count: usize, buf: &impl Buf) -> Vec<T>
Expand description

Reserve space for count items without trusting count.

A count-prefixed list declares how many items follow, and the declaration arrives before any of them. Passing it straight to Vec::with_capacity hands an unauthenticated peer control of one allocation: a varint holds values up to 2^62-1, and asking for that many elements aborts the process with capacity overflow before a single item has been read. On a control stream the first message is a peer’s SETUP, so this is reachable before anything has been negotiated or authenticated.

Every item in these lists occupies at least one byte on the wire, so the bytes still in buf are a true upper bound on how many can really follow. A well-formed message is unaffected — its count is far below its length — and a malformed one allocates no more than it actually sent.

This bounds the allocation only. The decode loop still fails on the first item that is not there, which is what turns an over-long count into an error rather than a short read.