use core::iter::FusedIterator;
use crate::{Error, Instruction, decode_bytes};
#[derive(Debug, Clone)]
pub struct Decoder<'a> {
bytes: &'a [u8],
base: u64,
offset: usize,
}
impl<'a> Decoder<'a> {
pub const fn new(bytes: &'a [u8], address: u64) -> Self {
Self {
bytes,
base: address,
offset: 0,
}
}
pub const fn offset(&self) -> usize {
self.offset
}
pub const fn address(&self) -> u64 {
self.base.wrapping_add(self.offset as u64)
}
pub const fn set_offset(&mut self, offset: usize) {
self.offset = offset;
}
pub fn remaining(&self) -> &'a [u8] {
self.bytes.get(self.offset..).unwrap_or_default()
}
}
impl Iterator for Decoder<'_> {
type Item = (u64, Result<Instruction, Error>);
fn next(&mut self) -> Option<Self::Item> {
let rest = self.remaining();
if rest.is_empty() {
return None;
}
let address = self.address();
let result = decode_bytes(rest);
self.offset = self.offset.saturating_add(4);
Some((address, result))
}
fn size_hint(&self) -> (usize, Option<usize>) {
let count = self.remaining().len().div_ceil(4);
(count, Some(count))
}
}
impl ExactSizeIterator for Decoder<'_> {}
impl FusedIterator for Decoder<'_> {}