Skip to main content

cadmpeg_ir/decode/
view.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Bounded navigation over one address space.
3
4use crate::cursor::bounded_len;
5
6use super::error::SourceLocation;
7use super::probe::{ParseError, ParseErrorKind};
8use super::space::SpaceId;
9
10/// A count proven to fit in the unread input.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub struct BoundedCount(usize);
13
14impl BoundedCount {
15    /// Returns the proven element count.
16    pub fn get(self) -> usize {
17        self.0
18    }
19}
20
21/// A bounded window over one address space.
22#[derive(Debug, Clone, Copy)]
23pub struct View<'a> {
24    bytes: &'a [u8],
25    space: SpaceId,
26    start: usize,
27    end: usize,
28    position: usize,
29}
30
31impl<'a> View<'a> {
32    /// Creates a full-window view over an entire space buffer.
33    pub(crate) fn over_space(bytes: &'a [u8], space: SpaceId) -> View<'a> {
34        View {
35            bytes,
36            space,
37            start: 0,
38            end: bytes.len(),
39            position: 0,
40        }
41    }
42
43    /// Returns the space this view navigates.
44    pub(crate) fn space(self) -> SpaceId {
45        self.space
46    }
47
48    /// Returns the absolute position within the space.
49    pub fn position(self) -> usize {
50        self.position
51    }
52
53    /// Returns the window's inclusive lower bound.
54    pub fn start(self) -> usize {
55        self.start
56    }
57
58    /// Returns the window's exclusive upper bound.
59    pub fn end(self) -> usize {
60        self.end
61    }
62
63    /// Returns the number of unread bytes before the window's end.
64    pub fn remaining(self) -> usize {
65        self.end.saturating_sub(self.position)
66    }
67
68    /// Returns this view's current source location.
69    pub fn location(self) -> SourceLocation {
70        SourceLocation {
71            space: self.space,
72            offset: self.position as u64,
73        }
74    }
75
76    /// Returns the readable window `start..end` as a slice.
77    pub fn window(self) -> &'a [u8] {
78        self.bytes.get(self.start..self.end).unwrap_or_default()
79    }
80
81    /// Takes `count` bytes, advancing only on success.
82    pub fn take(&mut self, count: usize) -> Option<&'a [u8]> {
83        let end = self.position.checked_add(count)?;
84        if end > self.end {
85            return None;
86        }
87        let bytes = self.bytes.get(self.position..end)?;
88        self.position = end;
89        Some(bytes)
90    }
91
92    /// Takes a fixed-size byte array, advancing only on success.
93    pub fn array<const N: usize>(&mut self) -> Option<[u8; N]> {
94        self.take(N)?.try_into().ok()
95    }
96
97    /// Skips exactly `count` bytes.
98    pub fn skip(&mut self, count: usize) -> Option<()> {
99        self.take(count).map(|_| ())
100    }
101
102    /// Moves to an absolute offset, honoring the stored lower bound.
103    pub fn seek(&mut self, position: usize) -> Option<()> {
104        (self.start <= position && position <= self.end).then(|| self.position = position)
105    }
106
107    /// Reads a single byte.
108    pub fn u8(&mut self) -> Option<u8> {
109        self.array::<1>().map(|[value]| value)
110    }
111
112    /// Returns an exactly contained child window.
113    pub fn child(self, start: usize, end: usize) -> Option<View<'a>> {
114        if self.start <= start && start <= end && end <= self.end {
115            Some(View {
116                bytes: self.bytes,
117                space: self.space,
118                start,
119                end,
120                position: start,
121            })
122        } else {
123            None
124        }
125    }
126
127    /// Proves a declared element count could fit in the unread bytes.
128    pub fn counted(self, count: u64, min_element_size: usize) -> Option<BoundedCount> {
129        bounded_len(count, min_element_size, self.remaining()).map(BoundedCount)
130    }
131
132    /// Builds an unexpected-eof error from the view's current state.
133    fn eof(self, needed: u64) -> ParseError {
134        ParseError {
135            location: self.location(),
136            kind: ParseErrorKind::UnexpectedEof {
137                needed,
138                remaining: self.remaining() as u64,
139            },
140        }
141    }
142
143    /// Required-read mirror of [`View::take`].
144    pub fn req_take(&mut self, count: usize) -> Result<&'a [u8], ParseError> {
145        match self.take(count) {
146            Some(bytes) => Ok(bytes),
147            None => Err(self.eof(count as u64)),
148        }
149    }
150
151    /// Required-read mirror of [`View::u8`].
152    pub fn req_u8(&mut self) -> Result<u8, ParseError> {
153        match self.u8() {
154            Some(value) => Ok(value),
155            None => Err(self.eof(1)),
156        }
157    }
158}
159
160macro_rules! view_readers {
161    ($(($probe:ident, $req:ident, $ty:ty, $conv:ident, $size:literal)),* $(,)?) => {
162        impl View<'_> {
163            $(
164                #[doc = concat!("Probe read of a `", stringify!($ty), "` via `", stringify!($conv), "`.")]
165                pub fn $probe(&mut self) -> Option<$ty> {
166                    self.array::<$size>().map(<$ty>::$conv)
167                }
168
169                #[doc = concat!("Required-read mirror of [`View::", stringify!($probe), "`].")]
170                pub fn $req(&mut self) -> Result<$ty, ParseError> {
171                    match self.array::<$size>() {
172                        Some(bytes) => Ok(<$ty>::$conv(bytes)),
173                        None => Err(self.eof($size)),
174                    }
175                }
176            )*
177        }
178    };
179}
180
181view_readers!(
182    (u16_le, req_u16_le, u16, from_le_bytes, 2),
183    (i16_le, req_i16_le, i16, from_le_bytes, 2),
184    (u32_le, req_u32_le, u32, from_le_bytes, 4),
185    (i32_le, req_i32_le, i32, from_le_bytes, 4),
186    (u64_le, req_u64_le, u64, from_le_bytes, 8),
187    (i64_le, req_i64_le, i64, from_le_bytes, 8),
188    (f32_le, req_f32_le, f32, from_le_bytes, 4),
189    (f64_le, req_f64_le, f64, from_le_bytes, 8),
190    (u16_be, req_u16_be, u16, from_be_bytes, 2),
191    (u32_be, req_u32_be, u32, from_be_bytes, 4),
192    (u64_be, req_u64_be, u64, from_be_bytes, 8),
193    (f64_be, req_f64_be, f64, from_be_bytes, 8),
194);