use crate::{
asm::{ToBytes, TryFromBytes},
BytecodeMapped, BytecodeMappedLazy,
};
pub trait OpAccess {
type Op;
type Error: core::fmt::Debug + core::fmt::Display;
fn op_access(&mut self, index: usize) -> Option<Result<Self::Op, Self::Error>>;
}
impl<'a, Op> OpAccess for &'a [Op]
where
Op: Clone,
{
type Op = Op;
type Error = core::convert::Infallible;
fn op_access(&mut self, index: usize) -> Option<Result<Self::Op, Self::Error>> {
self.get(index).cloned().map(Ok)
}
}
impl<'a, Op, Bytes> OpAccess for &'a BytecodeMapped<Op, Bytes>
where
Op: TryFromBytes,
Bytes: core::ops::Deref<Target = [u8]>,
{
type Op = Op;
type Error = core::convert::Infallible;
fn op_access(&mut self, index: usize) -> Option<Result<Self::Op, Self::Error>> {
self.op(index).map(Ok)
}
}
impl<Op, I> OpAccess for BytecodeMappedLazy<Op, I>
where
Op: ToBytes + TryFromBytes,
I: Iterator<Item = u8>,
{
type Op = Op;
type Error = Op::Error;
fn op_access(&mut self, index: usize) -> Option<Result<Op, Self::Error>> {
loop {
match self.mapped.op(index) {
Some(op) => return Some(Ok(op)),
None => match Op::try_from_bytes(&mut self.iter)? {
Err(err) => return Some(Err(err)),
Ok(op) => self.mapped.push_op(op),
},
}
}
}
}