~ren/polymorphos

1ec66b43d6fcdd4ae97dc9543e078b0c63624ea3 — Lauren Jenkinson 1 year, 6 days ago 5cb4e72
helpers: Add `StaticCollection` type
2 files changed, 73 insertions(+), 0 deletions(-)

M polymorph-helpers/src/lib.rs
A polymorph-helpers/src/staticcollection.rs
M polymorph-helpers/src/lib.rs => polymorph-helpers/src/lib.rs +2 -0
@@ 19,4 19,6 @@ pub static ALLOCATOR: LockedAllocator = LockedAllocator::empty();

pub mod byteclone;
mod unsafecontainer;
mod staticcollection;
pub use self::unsafecontainer::UnsafeContainer;
pub use self::staticcollection::StaticCollection;

A polymorph-helpers/src/staticcollection.rs => polymorph-helpers/src/staticcollection.rs +71 -0
@@ 0,0 1,71 @@
//! A fixed-size collection type

use core::default::Default;
use core::fmt::{self, Debug};

/// Maximum number of entries a [`StaticCollection`] can hold.
pub const STATIC_COLLECTION_SIZE: usize = 128;

/// A fixed-size collection.
#[derive(Clone)]
pub struct StaticCollection<T: Default + Debug + Copy> {
    /// Objects in this collection.
    entries: [T; STATIC_COLLECTION_SIZE],

    /// Index of the next entry in the `entries` array.
    next_entry: usize,
}

impl<T: Default + Debug + Copy> StaticCollection<T> {
    /// Create a new empty `StaticCollection`.
    pub fn new() -> Self {
        Self {
            entries: [Default::default(); STATIC_COLLECTION_SIZE],
            next_entry: 0,
        }
    }

    /// Add an entry to this collection.
    pub fn push(&mut self, entry: T) {
        assert!(self.next_entry < STATIC_COLLECTION_SIZE);
        self.entries[self.next_entry] = entry;
        self.next_entry += 1;
    }

	/// Return a slice of the entries within this collection.
    pub fn as_slice(&self) -> &[T] {
        &self.entries[0..self.next_entry]
    }
}

impl<T: Default + Debug + Copy> Debug for StaticCollection<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("StaticCollection")
            .field(&self.as_slice())
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::prelude::v1::*;

    #[test]
    fn test_as_slice() {
        let mut container: StaticCollection<&'static str> = StaticCollection::new();
        container.push("test one");
        container.push("test two");

        assert_eq!(container.as_slice(), &["test one", "test two"]);
    }

    #[test]
    fn test_debug_format() {
        let mut container: StaticCollection<&'static str> = StaticCollection::new();
        container.push("test one");
        container.push("test two");

        assert_eq!(format!("{:?}", container), String::from("StaticCollection([\"test one\", \"test two\"])"));
    }
}