Trait len_trait::capacity::CapacityMut
[−]
[src]
pub trait CapacityMut: WithCapacity { fn reserve(&mut self, additional: usize); fn reserve_exact(&mut self, additional: usize) { ... } fn shrink_to_fit(&mut self) { ... } }
A trait for modifying the capacity of a collection.
These methods are mostly hints to
Clearing a collection must take at most a linear amount of time and space with respect to the number of elements which are dropped.
Required Methods
fn reserve(&mut self, additional: usize)
Ensures that the capacity is at least the current length plus additional
.
Usually, this is used to avoid multiple allocations when you know exactly how much capacity is needed to store data.
Examples
use len_trait::CapacityMut; fn check_capacity<C: CapacityMut>(mut collection: C) { collection.reserve(100); assert!(collection.capacity() >= collection.len() + 100) } check_capacity(vec![1, 2, 3]); check_capacity("Hello, world!".to_string());
Provided Methods
fn reserve_exact(&mut self, additional: usize)
Similar to reserve
, adding a strong hint to not reserve capacity above what's needed.
By default, this method just delegates to reserve
unless the implementation has a more
efficient version.
Examples
use std::collections::HashMap; use len_trait::CapacityMut; fn check_capacity<C: CapacityMut>(mut collection: C, exact: bool) { collection.reserve_exact(100); if exact { assert_eq!(collection.capacity(), collection.len() + 100) } else { assert!(collection.capacity() > collection.len() + 100) } } check_capacity(vec![1, 2, 3], true); check_capacity("Hello, world!".to_string(), true); check_capacity( { let mut map = HashMap::new(); map.insert('a', 1); map.insert('b', 2); map.insert('c', 3); map }, false, );
fn shrink_to_fit(&mut self)
Reduces the capacity down as close as possible to the current length.
If the length of the collection is zero, this method will set its capacity to zero. By default, this method does nothing unless the capacity is zero.
Examples
use len_trait::{Capacity, WithCapacity, CapacityMut}; let mut v: Vec<usize> = WithCapacity::with_capacity(10); v.extend(&[1, 2, 3, 4, 5, 6][..]); assert_eq!(v.capacity(), 10); CapacityMut::shrink_to_fit(&mut v); assert_eq!(v.capacity(), 6); v.clear(); CapacityMut::shrink_to_fit(&mut v); assert_eq!(v.capacity(), 0);