Trait len_trait::capacity::Capacity [] [src]

pub trait Capacity: Len {
    fn capacity(&self) -> usize;

A trait for describing the capacity of a collection.

Because frequently allocating memory can be inefficient, collections often store room for more data than they actually hold. This "extra length" is represented by capacity, stating the maximum length that can be occupied without any memory allocations.

Obtaining the capacity of the collection must take a constant amount of time and space.

Required Methods

Returns the capacity of the collection.

If this collection stores zero-sized types, then it effectively has infinite capacity. For this reason, those collections should have a capacity of usize::MAX.


use len_trait::Capacity;

fn check_capacity<C: Capacity>(collection: C, zero_sized: bool) {
    if zero_sized {
        assert_eq!(collection.capacity(), usize::max_value());
    } else {
        assert!(collection.capacity() >= collection.len());

check_capacity(vec![()], true);
check_capacity(vec![1, 2, 3], false);
check_capacity("Hello, world!".to_string(), false);