Skip to content

Commit

Permalink
common: Add .get functions that return errors
Browse files Browse the repository at this point in the history
  • Loading branch information
sophie-h committed Dec 5, 2024
1 parent 7041683 commit 6858988
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions gufo-common/src/read.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,36 @@
use std::io::{Cursor, Seek};
use std::slice::SliceIndex;

use crate::math::*;

pub trait GetExt<T> {
fn e_get<I: SliceIndex<[T]>>(
&self,
index: I,
) -> Result<&<I as SliceIndex<[T]>>::Output, ReadError>;

fn e_get_mut<I: SliceIndex<[T]>>(
&mut self,
index: I,
) -> Result<&mut <I as SliceIndex<[T]>>::Output, ReadError>;
}

impl<T> GetExt<T> for [T] {
fn e_get<I: SliceIndex<[T]>>(
&self,
index: I,
) -> Result<&<I as SliceIndex<[T]>>::Output, ReadError> {
self.get(index).ok_or(ReadError::InvalidIndex)
}

fn e_get_mut<I: SliceIndex<[T]>>(
&mut self,
index: I,
) -> Result<&mut <I as SliceIndex<[T]>>::Output, ReadError> {
self.get_mut(index).ok_or(ReadError::InvalidIndex)
}
}

pub trait ReadExt: std::io::BufRead + std::io::Seek {
fn read_array<const T: usize>(&mut self) -> Result<[u8; T], ReadError> {
let buf = &mut [0; T];
Expand Down Expand Up @@ -74,4 +103,6 @@ pub enum ReadError {
Math(#[from] MathError),
#[error("IO: {0}")]
Io(#[from] std::io::Error),
#[error("Invalid index")]
InvalidIndex,
}

0 comments on commit 6858988

Please sign in to comment.