binbun_aarch64/decoder.rs
1//! Decoding a buffer of code instruction by instruction.
2
3use core::iter::FusedIterator;
4
5use crate::{Error, Instruction, decode_bytes};
6
7/// Decodes the instructions of a buffer one after another (a linear sweep).
8///
9/// Each item is the instruction's address and the decode result. Every A64
10/// instruction is 4 bytes, so the decoder moves 4 bytes on, after an error
11/// too; a last piece shorter than 4 bytes gives [`Error::TooShort`] and
12/// ends the sweep.
13///
14/// ```
15/// use binbun_aarch64::Decoder;
16///
17/// let code = [0xe0, 0x03, 0x01, 0xaa, 0xc0, 0x03, 0x5f, 0xd6]; // mov x0, x1; ret
18/// let mut decoder = Decoder::new(&code, 0x1000);
19/// let (address, mov) = decoder.next().unwrap();
20/// assert_eq!((address, mov.unwrap().display(address).to_string()), (0x1000, "mov\tx0, x1".into()));
21/// let (address, ret) = decoder.next().unwrap();
22/// assert_eq!((address, ret.unwrap().mnemonic()), (0x1004, "ret"));
23/// assert!(decoder.next().is_none());
24/// ```
25#[derive(Debug, Clone)]
26pub struct Decoder<'a> {
27 bytes: &'a [u8],
28 /// Address of `bytes[0]`.
29 base: u64,
30 /// Offset of the next instruction in `bytes`.
31 offset: usize,
32}
33
34impl<'a> Decoder<'a> {
35 /// A decoder of `bytes`, which are at `address`.
36 pub const fn new(bytes: &'a [u8], address: u64) -> Self {
37 Self {
38 bytes,
39 base: address,
40 offset: 0,
41 }
42 }
43
44 /// Offset in the buffer of the next instruction.
45 pub const fn offset(&self) -> usize {
46 self.offset
47 }
48
49 /// Address of the next instruction.
50 pub const fn address(&self) -> u64 {
51 self.base.wrapping_add(self.offset as u64)
52 }
53
54 /// Continues at `offset` in the buffer (past the end: nothing more).
55 pub const fn set_offset(&mut self, offset: usize) {
56 self.offset = offset;
57 }
58
59 /// The bytes not decoded yet.
60 pub fn remaining(&self) -> &'a [u8] {
61 self.bytes.get(self.offset..).unwrap_or_default()
62 }
63}
64
65impl Iterator for Decoder<'_> {
66 type Item = (u64, Result<Instruction, Error>);
67
68 fn next(&mut self) -> Option<Self::Item> {
69 let rest = self.remaining();
70 if rest.is_empty() {
71 return None;
72 }
73 let address = self.address();
74 let result = decode_bytes(rest);
75 self.offset = self.offset.saturating_add(4);
76 Some((address, result))
77 }
78
79 fn size_hint(&self) -> (usize, Option<usize>) {
80 let count = self.remaining().len().div_ceil(4);
81 (count, Some(count))
82 }
83}
84
85impl ExactSizeIterator for Decoder<'_> {}
86
87impl FusedIterator for Decoder<'_> {}