1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use core::{cmp, fmt, ops, ptr};
use *;

/// Length disassembler mutable iterator.
///
/// Instances are created by the [`Isa::iter_mut`](trait.Isa.html#method.iter_mut) method.
pub struct IterMut<'a, X: Isa> {
	/// The remaining bytes to length disassemble.
	pub bytes: &'a mut [u8],
	/// The current virtual address.
	pub va: X::Va,
}

impl<'a, X: Isa> IterMut<'a, X> {
	/// Cast as const iterator.
	pub fn as_iter<'s>(&'s self) -> Iter<'s, X> {
		Iter {
			bytes: self.bytes,
			va: self.va,
		}
	}
	/// Cast into const iterator.
	pub fn into_iter(self) -> Iter<'a, X> {
		Iter {
			bytes: self.bytes,
			va: self.va,
		}
	}
	/// Consumes a number of bytes from the input and returns it as an opcode and its virtual address.
	pub fn consume(&mut self, n: usize) -> (&'a mut OpCode, X::Va) {
		let n = cmp::min(n, self.bytes.len());
		// The trouble here is that we want ownership of self.bytes, split it up and reinitialize self
		// However this would need a `mem::replace_with` to satisfy the lifetime requirements of the mutable reference
		// Temp fix to use some unsafe code to whack the lifetimes
		let (head, tail) = unsafe { ptr::read(&mut self.bytes) }.split_at_mut(n);
		let result = (head.into(), self.va);
		self.bytes = tail;
		self.va += X::as_va(n);
		result
	}
}

impl<'a, X: Isa> Iterator for IterMut<'a, X> {
	type Item = (&'a mut OpCode, X::Va);
	fn next(&mut self) -> Option<Self::Item> {
		let len = X::ld(self.bytes);
		if len > 0 {
			Some(self.consume(len as usize))
		}
		else {
			None
		}
	}
}

impl<'a, X: Isa> ops::Deref for IterMut<'a, X> {
	type Target = [u8];
	fn deref(&self) -> &[u8] {
		self.bytes
	}
}
impl<'a, X: Isa> ops::DerefMut for IterMut<'a, X> {
	fn deref_mut(&mut self) -> &mut [u8] {
		self.bytes
	}
}

/// Debug formatter.
///
/// Single line, opcodes grouped with square brackets.
/// Alternate flag to put spaces between the bytes.
impl<'a, X: Isa> fmt::Debug for IterMut<'a, X> {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		self.as_iter().fmt(f)
	}
}

/// Display formatter.
///
/// One line per opcode.
/// Alternate flag to put spaces between the bytes.
impl<'a, X: Isa> fmt::Display for IterMut<'a, X> {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		self.as_iter().fmt(f)
	}
}