60 lines
1.5 KiB
Rust
60 lines
1.5 KiB
Rust
#[derive(Clone)]
|
|
pub struct Cursor<'a, T> {
|
|
buf: &'a [T],
|
|
index: usize,
|
|
}
|
|
|
|
impl<'a, T> Cursor<'a, T> {
|
|
pub fn from(buf: &'a [T]) -> Self {
|
|
Self { buf, index: 0 }
|
|
}
|
|
|
|
pub fn index(&mut self) -> usize {
|
|
self.index
|
|
}
|
|
|
|
pub fn next(&mut self) -> Option<&T> {
|
|
let next_index = self.index + 1;
|
|
if next_index > self.buf.len() {
|
|
None
|
|
} else {
|
|
let v = &self.buf[self.index];
|
|
self.index = next_index;
|
|
Some(v)
|
|
}
|
|
}
|
|
|
|
pub fn seek(&mut self, location: usize) -> Result<(), ()> {
|
|
if location > self.buf.len() {
|
|
Err(())
|
|
} else {
|
|
self.index = location;
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
pub fn next_slice(&mut self, amount: usize) -> Option<&'a [T]> {
|
|
let next_index = self.index + amount;
|
|
if next_index > self.buf.len() {
|
|
None
|
|
} else {
|
|
let slice = &self.buf[self.index..next_index];
|
|
self.index = next_index;
|
|
Some(slice)
|
|
}
|
|
}
|
|
|
|
pub fn next_array<const N: usize>(&mut self) -> Option<[T; N]> where [T; N]: TryFrom<&'a [T]> {
|
|
Some(self.next_slice(N)?.try_into().ok()?)
|
|
}
|
|
|
|
pub fn forward(&mut self, amount: usize) -> Result<(), ()> {
|
|
let next_index = self.index + amount;
|
|
if next_index > self.buf.len() {
|
|
Err(())
|
|
} else {
|
|
self.index = next_index;
|
|
Ok(())
|
|
}
|
|
}
|
|
} |