Le Dong Thuc
Le Dong Thuc

Reputation: 305

Rust Vec reverse_exact: capacity will be greater than or equal to self.len() + additional

In the Rust document Vec, the method reserve_exact said about:

After calling reserve_exact, capacity will be greater than or equal to self.len() + additional

https://doc.rust-lang.org/std/vec/struct.Vec.html#method.reserve_exact

But when I read the code from https://doc.rust-lang.org/beta/src/alloc/raw_vec.rs.html#408

I see the new capacity is equal always size + additonal. So I'm not sure which part of the reserve_exact() will make capacity is greater than self.len() + additional

    fn grow_exact(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> {
        if mem::size_of::<T>() == 0 {
            // Since we return a capacity of `usize::MAX` when the type size is
            // 0, getting to here necessarily means the `RawVec` is overfull.
            return Err(CapacityOverflow.into());
        }

        let cap = len.checked_add(additional).ok_or(CapacityOverflow)?;
        let new_layout = Layout::array::<T>(cap);

        // `finish_grow` is non-generic over `T`.
        let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?;
        self.set_ptr_and_cap(ptr, cap);
        Ok(())
    }

Maybe I miss part of the code, thanks if you can point what I missed!

Upvotes: 0

Views: 149

Answers (1)

Finomnis
Finomnis

Reputation: 22738

fn main() {
    let mut vec1 = vec![1, 2, 3, 4, 5];
    println!("vec1 len: {}, cap: {}", vec1.len(), vec1.capacity());
    vec1.reserve_exact(3);
    println!("vec1 len: {}, cap: {}", vec1.len(), vec1.capacity());
    println!("   expected: cap >= 8\n");

    let mut vec2 = Vec::with_capacity(100);
    vec2.push(1);
    vec2.push(2);
    vec2.push(3);
    println!("vec2 len: {}, cap: {}", vec2.len(), vec2.capacity());
    vec2.reserve_exact(3);
    println!("vec2 len: {}, cap: {}", vec2.len(), vec2.capacity());
    println!("   expected: cap >= 6");
}
vec1 len: 5, cap: 5
vec1 len: 5, cap: 8
   expected >= 8

vec2 len: 3, cap: 100
vec2 len: 3, cap: 100
   expected >= 6

Q.E.D.


The line that warrants the greater than is here:

if self.needs_to_grow(len, additional) ...

As in the example, if your capacity is 100, but your content is only 3, and you want to grow it by an additional 3, nothing happens, because it's already big enough, fulfilling the bigger or equal requirement. And as 100 is obviously bigger than 6, this should hopefully answer your question ;)

Upvotes: 1

Related Questions