Skip to main content

nanvm_lib/common/
sized_index.rs

1use core::ops::Index;
2
3use crate::common::{default::default, index_iter::IndexIter, uint::Uint};
4
5/// A container indexed by `I` from `0` up to [`length`](Self::length).
6///
7/// The length is fixed: it does not change for as long as the container is
8/// held, so [`IndexIter`] can promise an exact `size_hint` and stay fused. A
9/// container with interior mutability that could change its length must not
10/// implement this trait.
11pub trait SizedIndex<I: Uint>: Index<I> {
12    fn length(&self) -> I;
13    fn is_empty(&self) -> bool {
14        self.length() == default()
15    }
16    fn last(&self) -> Option<&Self::Output> {
17        if self.is_empty() {
18            None
19        } else {
20            Some(&self[self.length() - 1.into()])
21        }
22    }
23    fn index_iter(self) -> IndexIter<I, Self>
24    where
25        Self: Sized,
26    {
27        IndexIter::new(self)
28    }
29}
30
31impl<T> SizedIndex<usize> for [T] {
32    fn length(&self) -> usize {
33        self.len()
34    }
35}