Trait len_trait::capacity::WithCapacity [] [src]

pub trait WithCapacity: Capacity + Default {
    fn with_capacity(capacity: usize) -> Self;

A trait for creating an empty collection with a given, pre-allocated capacity.

If a user knows in advance a minimum bound for how much capacity they will need, they can use the with_capacity trait to pre-allocate memory in advance. The resulting collection is guaranteed to have at least the capacity given.

If the given capacity is zero, then no capacity should be allocated at all. The behaviour of the Default implementation should act the same as with_capacity(0).

Creating a collection with a given capacity should take linear time and space with respect to the requested capacity. Creating a collection of zero-size types should always take constant time and space.

Required Methods

Creates a value of the given capacity.

If a value of zero is given, this should have the same effect as calling Default::default, and should not allocate any memory.


use len_trait::WithCapacity;

fn check_capacity<C: WithCapacity>(zero_sized: bool) {
    let default = C::default();
    let with_cap = C::with_capacity(10);
    if zero_sized {
        assert_eq!(default.capacity(), usize::max_value());
        assert_eq!(with_cap.capacity(), usize::max_value());
    } else {
        assert_eq!(default.capacity(), 0);
        assert!(with_cap.capacity() >= 10);