1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//! Traits involving the length of a collection.

/// A trait for describing the length of a collection.
///
/// The amount of data stored in a collection, i.e. the amount of space it requires in memory, is
/// directly proportional to its length. For this reason, `str` and other types measure their
/// lengths in code values (e.g. `u8`), not code points (e.g. `char`).
///
/// Obtaining the length of the collection must take a constant amount of time and space.
pub trait Len {
    /// Returns the length of the collection.
    fn len(&self) -> usize;

    /// Returns whether the collection is empty, i.e. if its length is zero.
    ///
    /// This defaults to checking if `len() == 0`, although can be overridden to be more efficient.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// A trait for clearing collections.
///
/// A collection is cleared by dropping all of its data. After `clear` is called, the collection is
/// guaranteed to be empty.
///
/// Clearing a collection must take at most a linear amount of time and space.
pub trait Clear: Len {
    /// Clears the collection, dropping its elements and returning its length to zero.
    fn clear(&mut self);
}

/// A trait for modifying the length of a collection.
///
/// These methods must take at most a linear amount of time and space with respect to the number of
/// elements which are moved or dropped.
pub trait LenMut: Default + Clear {
    /// Truncates the collection to be no greater than `len` long, dropping elements as needed.
    ///
    /// If the collection is less than `len` long, do nothing.
    fn truncate(&mut self, len: usize);

    /// Splits off the collection at the given index, returning the data past the index.
    fn split_off(&mut self, index: usize) -> Self;
}