Skip to content

Take does not reserve its limit on read_to_end #51746

Closed
@MichaelTheriot

Description

@MichaelTheriot

Using readable.take(x).read_to_end(&mut buf) can cause the capacity of buf to exceed what is needed.

I tried this code:

use std::io::Read;

fn main() {
    let readable = &[1];
    let mut buf: Vec<u8> = Vec::with_capacity(2);

    assert_eq!(buf.len(), 0);
    assert_eq!(buf.capacity(), 2);
    readable.take(1).read_to_end(&mut buf).unwrap();

    assert_eq!(buf.len(), 1);
    assert_eq!(buf.capacity(), 32);
}

https://play.rust-lang.org/?gist=83401a704fddcec007bcfb0ecc85fc6d&version=nightly&mode=debug

I expected to see this happen:
readable.take(1) should reserve 1.

Take should reserve a maximum of take.limit().

Instead, this happened:
buf capacity increased because readable.take(1) reserved 32 which exceeds its limit.

Take will always reserve in increments of 32 rather than its known limit.


I'm new to Rust; my guess is implementing read_to_end specifically for Take is the way to improve this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: An issue proposing an enhancement or a PR with one.I-slowIssue: Problems and improvements with respect to performance of generated code.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions