Skip to content

Test iterators #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

A no-std, stack-allocated vector with fixed capacity and dynamic length.

`StaticVector<T, CAPACITY>` stores elements on the stack using a fixed-size array without heap allocations.
`StaticVector` stores elements on the stack using a fixed-size array without heap allocations.

Aims to be suitable for low-level projects and to have an API as safe and explicit as possible.
The goal is to allocate only when needed. When first constructed, the vector will not allocate.
Expand All @@ -17,12 +17,12 @@ The goal is to allocate only when needed. When first constructed, the vector wil

- No heap allocation (`#![no_std]` compatible)
- Constant-time indexed access
- Supports iteration, mutable access, clearing, and appending
- Supports iteration, mutable access, clearing, resizing
- Compile-time enforced capacity

## Requirements

- `T: Clone` for insertion (e.g., `push`, `append`)
- `T: Clone` for insertion: `push`
- `T: Default` only if `set_len` is used
- `CAPACITY > 0`

Expand Down
8 changes: 8 additions & 0 deletions codecov.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
coverage:
status:
patch:
default:
threshold: 100
project:
default:
threshold: 100
59 changes: 41 additions & 18 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! A no-std, stack-allocated vector with fixed capacity and dynamic length.
//!
//! `StaticVector<T, CAPACITY>` stores elements on the stack using a fixed-size array without heap allocations.
//! [`StaticVector`] stores elements on the stack using a fixed-size array without heap allocations.
//!
//! Aims to be suitable for low-level projects and to have an API as safe and explicit as possible.
//! The goal is to allocate only when needed. When first constructed, the vector will not allocate.
Expand All @@ -10,12 +10,12 @@
//! # Features
//! - No heap allocation (`#![no_std]` compatible)
//! - Constant-time indexed access
//! - Supports iteration, mutable access, clearing, and appending
//! - Supports iteration, mutable access, clearing, resizing
//! - Compile-time enforced capacity
//!
//! # Requirements
//! - `T: Clone` for insertion (e.g., `push`, `append`)
//! - `T: Default` only if `set_len` is used
//! - `T: Clone` for insertion: [`StaticVector::push()`]
//! - `T: Default` only if [`StaticVector::set_len()`] is used
//! - `CAPACITY > 0`
//!
//! # Example
Expand All @@ -29,10 +29,11 @@
//! ```

#![no_std]
#![deny(missing_docs)]

use core::{array, borrow::Borrow, mem::MaybeUninit};
use core::{array, mem::MaybeUninit};

/// Error type returned by `StaticVector`.
/// Error type returned by [`StaticVector`].
#[derive(Debug)]
pub struct Error(pub &'static str);

Expand All @@ -45,7 +46,7 @@ pub struct StaticVector<T: Clone, const CAPACITY: usize> {
}

impl<T: Clone, const CAPACITY: usize> Default for StaticVector<T, CAPACITY> {
/// Creates an empty `StaticVector`. Equivalent to `StaticVector::new()`.
/// Creates an empty [`StaticVector`]. Equivalent to [`StaticVector::new()`].
fn default() -> Self {
Self::new()
}
Expand All @@ -54,7 +55,7 @@ impl<T: Clone, const CAPACITY: usize> Default for StaticVector<T, CAPACITY> {
impl<T: Clone, const CAPACITY: usize> StaticVector<T, CAPACITY> {
const ASSERT_CAPACITY: () = assert!(CAPACITY > 0);

/// Creates a new empty `StaticVector` with maximum `CAPACITY` elements of type `T`.
/// Creates a new empty [`StaticVector`] with maximum `CAPACITY` elements of type `T`.
#[inline]
pub fn new() -> Self {
let () = Self::ASSERT_CAPACITY;
Expand Down Expand Up @@ -84,7 +85,7 @@ impl<T: Clone, const CAPACITY: usize> StaticVector<T, CAPACITY> {
///
/// # Errors
///
/// Returns [`Error`](`crate::Error`) if the vector is already at full capacity.
/// Returns [`Error`] if the vector is already at full capacity.
pub fn push(&mut self, value: &T) -> Result<(), Error> {
if self.length == CAPACITY {
return Err(Error("capacity"));
Expand All @@ -96,14 +97,6 @@ impl<T: Clone, const CAPACITY: usize> StaticVector<T, CAPACITY> {
Ok(())
}

pub fn append<I>(&mut self, iter: I) -> Result<(), Error>
where
I: IntoIterator,
I::Item: Borrow<T>,
{
iter.into_iter().try_for_each(|value| self.push(value.borrow()))
}

/// Removes all elements. Size will be zero.
pub fn clear(&mut self) {
self.drop(0, self.length);
Expand All @@ -119,7 +112,7 @@ impl<T: Clone, const CAPACITY: usize> StaticVector<T, CAPACITY> {
///
/// # Errors
///
/// Returns [`Error`](`crate::Error`) if `new_length` exceeds the vector's fixed capacity.
/// Returns [`Error`] if `new_length` exceeds the vector's fixed capacity.
pub fn set_len(&mut self, new_length: usize) -> Result<(), Error>
where
T: Default,
Expand Down Expand Up @@ -170,11 +163,13 @@ impl<T: Clone, const CAPACITY: usize> StaticVector<T, CAPACITY> {
}
}

/// Returns an iterator over immutable references to the elements in the vector.
#[inline(always)]
pub fn iter(&self) -> StaticVectorIterator<T> {
StaticVectorIterator { data: &self.data, size: self.length, index: 0 }
}

/// Returns an iterator over mutable references to the elements in the vector.
#[inline(always)]
pub fn iter_mut(&mut self) -> StaticVectorMutableIterator<T> {
StaticVectorMutableIterator { data: &mut self.data, size: self.length, index: 0 }
Expand All @@ -195,6 +190,9 @@ impl<T: Clone, const CAPACITY: usize> Drop for StaticVector<T, CAPACITY> {
}
}

/// Immutable iterator over a [`StaticVector`].
///
/// Created by calling [`StaticVector::iter()`].
#[must_use = "must consume iterator"]
pub struct StaticVectorIterator<'a, T> {
data: &'a [MaybeUninit<T>],
Expand All @@ -216,6 +214,9 @@ impl<'a, T> Iterator for StaticVectorIterator<'a, T> {
}
}

/// Mutable iterator over a [`StaticVector`].
///
/// Created by calling [`StaticVector::iter_mut()`].
#[must_use = "must consume iterator"]
pub struct StaticVectorMutableIterator<'a, T> {
data: &'a mut [MaybeUninit<T>],
Expand Down Expand Up @@ -324,4 +325,26 @@ mod tests {
assert_eq!(vec.get_mut(0).unwrap(), &5);
assert!(vec.get_mut(3).is_none());
}

#[test]
fn iter() {
let mut vec = StaticVector::<i32, 10>::new();
for i in 1..8 {
vec.push(&i).unwrap()
}

let even_sum = vec.iter().filter(|v| *v % 2 == 0).sum::<i32>();
assert_eq!(even_sum, 12);
}

#[test]
fn iter_mut() {
let mut vec = StaticVector::<i32, 10>::new();
for i in 1..8 {
vec.push(&i).unwrap()
}

let even_sum = vec.iter_mut().filter(|v| **v % 2 == 0).map(|v| *v).sum::<i32>();
assert_eq!(even_sum, 12);
}
}