1#[derive(Debug, Clone, Copy)]
4pub struct Cursor<'a> {
5 pub data: &'a [u8],
6 pub pos: usize,
7}
8
9impl<'a> Cursor<'a> {
10 pub fn new(data: &'a [u8]) -> Self {
11 Cursor { data, pos: 0 }
12 }
13
14 pub fn at(data: &'a [u8], pos: usize) -> Self {
15 Cursor { data, pos }
16 }
17
18 pub fn remaining(&self) -> usize {
19 self.data.len().saturating_sub(self.pos)
20 }
21
22 fn take(&mut self, n: usize) -> Option<&'a [u8]> {
23 if self.remaining() < n {
24 return None;
25 }
26 let s = &self.data[self.pos..self.pos + n];
27 self.pos += n;
28 Some(s)
29 }
30
31 pub fn u1(&mut self) -> Option<u8> {
32 self.take(1).map(|s| s[0])
33 }
34
35 pub fn u2(&mut self) -> Option<u16> {
36 self.take(2).map(|s| u16::from_le_bytes([s[0], s[1]]))
37 }
38
39 pub fn u4(&mut self) -> Option<u32> {
40 self.take(4)
41 .map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
42 }
43
44 pub fn s4(&mut self) -> Option<i32> {
45 self.u4().map(|v| v as i32)
46 }
47
48 pub fn u8v(&mut self) -> Option<u64> {
49 self.take(8).map(|s| {
50 let mut b = [0u8; 8];
51 b.copy_from_slice(s);
52 u64::from_le_bytes(b)
53 })
54 }
55
56 pub fn peek_rest(&self) -> &'a [u8] {
58 &self.data[self.pos.min(self.data.len())..]
59 }
60
61 pub fn skip(&mut self, n: usize) {
62 self.pos = (self.pos + n).min(self.data.len());
63 }
64
65 pub fn read_uleb128(&mut self) -> Option<u64> {
66 let mut result: u64 = 0;
67 let mut shift = 0u32;
68 loop {
69 let b = self.u1()?;
70 result |= ((b & 0x7f) as u64) << shift;
71 if b & 0x80 == 0 {
72 return Some(result);
73 }
74 shift += 7;
75 if shift > 63 {
76 return None;
77 }
78 }
79 }
80
81 pub fn read_sleb128(&mut self) -> Option<i64> {
82 let mut result: i64 = 0;
83 let mut shift = 0u32;
84 loop {
85 let b = self.u1()?;
86 result |= ((b & 0x7f) as i64) << shift;
87 shift += 7;
88 if b & 0x80 == 0 {
89 if shift < 64 && (b & 0x40) != 0 {
90 result |= -1i64 << shift;
91 }
92 return Some(result);
93 }
94 if shift > 63 {
95 return None;
96 }
97 }
98 }
99
100 pub fn read_uleb128p1(&mut self) -> Option<i64> {
102 self.read_uleb128().map(|v| v as i64 - 1)
103 }
104
105 pub fn read_mutf8(&self, pos: usize, utf16_len: u64) -> Option<String> {
108 if let Some(nul) = self.data[pos..].iter().position(|&b| b == 0) {
113 let ascii = &self.data[pos..pos + nul];
114 if !ascii.is_empty() && ascii.is_ascii() {
115 return Some(unsafe { std::str::from_utf8_unchecked(ascii).to_string() });
117 }
118 }
119 let mut out = String::new();
120 let mut i = pos;
121 let mut units = 0u64;
122 while units < utf16_len {
124 if i >= self.data.len() {
125 return None;
126 }
127 let b0 = self.data[i];
128 match b0 {
129 0x00 => {
130 break;
132 }
133 0x01..=0x7f => {
134 out.push(b0 as char);
135 i += 1;
136 }
137 0xc0..=0xdf => {
138 if i + 1 >= self.data.len() || (self.data[i + 1] & 0xc0) != 0x80 {
139 out.push('\u{fffd}');
140 i += 1;
141 } else {
142 let c = (((b0 & 0x1f) as u32) << 6) | ((self.data[i + 1] & 0x3f) as u32);
143 out.push(char::from_u32(c).unwrap_or('\u{fffd}'));
144 i += 2;
145 }
146 }
147 0xe0..=0xef => {
148 if i + 2 >= self.data.len()
149 || (self.data[i + 1] & 0xc0) != 0x80
150 || (self.data[i + 2] & 0xc0) != 0x80
151 {
152 out.push('\u{fffd}');
153 i += 1;
154 } else {
155 let c = (((b0 & 0x0f) as u32) << 12)
156 | (((self.data[i + 1] & 0x3f) as u32) << 6)
157 | ((self.data[i + 2] & 0x3f) as u32);
158 if (0xd800..0xdc00).contains(&c) {
160 if i + 5 < self.data.len()
161 && (self.data[i + 3] & 0xf0) == 0xe0
162 && (self.data[i + 4] & 0xc0) == 0x80
163 && (self.data[i + 5] & 0xc0) == 0x80
164 {
165 let lo = (((self.data[i + 3] & 0x0f) as u32) << 12)
166 | (((self.data[i + 4] & 0x3f) as u32) << 6)
167 | ((self.data[i + 5] & 0x3f) as u32);
168 let cp = 0x10000 + ((c - 0xd800) << 10) + (lo - 0xdc00);
169 out.push(char::from_u32(cp).unwrap_or('\u{fffd}'));
170 i += 6;
171 units += 2;
172 continue;
173 }
174 out.push('\u{fffd}');
175 i += 3;
176 } else {
177 out.push(char::from_u32(c).unwrap_or('\u{fffd}'));
178 i += 3;
179 }
180 }
181 }
182 _ => {
183 out.push('\u{fffd}');
184 i += 1;
185 }
186 }
187 units += 1;
188 }
189 Some(out)
190 }
191}
192
193pub fn mutf8_decode(data: &[u8], utf16_len: u64) -> Option<String> {
196 Cursor::new(data).read_mutf8(0, utf16_len)
197}
198
199#[cfg(test)]
200mod tests {
201 use super::*;
202
203 #[test]
204 fn uleb() {
205 let mut c = Cursor::new(&[0x00]);
206 assert_eq!(c.read_uleb128(), Some(0));
207 let mut c = Cursor::new(&[0x81, 0x01]);
208 assert_eq!(c.read_uleb128(), Some(129));
209 let mut c = Cursor::new(&[0xff, 0xff, 0xff, 0xff, 0x0f]);
210 assert_eq!(c.read_uleb128(), Some(0xffff_ffff));
211 }
212
213 #[test]
214 fn sleb() {
215 let mut c = Cursor::new(&[0x00]);
216 assert_eq!(c.read_sleb128(), Some(0));
217 let mut c = Cursor::new(&[0x7f]);
218 assert_eq!(c.read_sleb128(), Some(-1));
219 let mut c = Cursor::new(&[0x81, 0x7f]);
220 assert_eq!(c.read_sleb128(), Some(-127));
221 let mut c = Cursor::new(&[0xc0, 0xbb, 0x78]);
222 assert_eq!(c.read_sleb128(), Some(-123456));
223 }
224
225 #[test]
226 fn mutf8_ascii() {
227 assert_eq!(mutf8_decode(b"hello\0", 5).as_deref(), Some("hello"));
228 }
229
230 #[test]
231 fn mutf8_embedded_nul() {
232 assert_eq!(mutf8_decode(&[0xc0, 0x80], 1).as_deref(), Some("\0"));
233 }
234
235 #[test]
236 fn mutf8_supplementary() {
237 let bytes = [0xed, 0xa0, 0xbd, 0xed, 0xb8, 0x80];
239 assert_eq!(mutf8_decode(&bytes, 2).as_deref(), Some("\u{1f600}"));
240 }
241}