babbel_core/embedded/
mod.rs1use crate::error::ErrorCode;
8use core::cell::Cell;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct StackBuffer<const N: usize> {
20 data: [u8; N],
21 len: usize,
22}
23
24impl<const N: usize> StackBuffer<N> {
25 pub const fn new() -> Self {
27 Self {
28 data: [0u8; N],
29 len: 0,
30 }
31 }
32
33 pub fn from_slice(slice: &[u8]) -> Option<Self> {
35 if slice.len() > N {
36 return None;
37 }
38 let mut buffer = Self::new();
39 buffer.data[..slice.len()].copy_from_slice(slice);
40 buffer.len = slice.len();
41 Some(buffer)
42 }
43
44 pub fn as_slice(&self) -> &[u8] {
46 &self.data[..self.len]
47 }
48
49 pub fn as_mut_slice(&mut self) -> &mut [u8] {
51 &mut self.data[..self.len]
52 }
53
54 pub fn as_str(&self) -> Result<&str, core::str::Utf8Error> {
56 core::str::from_utf8(self.as_slice())
57 }
58
59 pub const fn len(&self) -> usize {
61 self.len
62 }
63
64 pub const fn is_empty(&self) -> bool {
66 self.len == 0
67 }
68
69 pub const fn capacity(&self) -> usize {
71 N
72 }
73
74 pub const fn remaining(&self) -> usize {
76 N.saturating_sub(self.len)
77 }
78
79 pub fn clear(&mut self) {
81 self.len = 0;
82 }
83
84 pub fn push(&mut self, byte: u8) -> bool {
86 if self.len >= N {
87 return false;
88 }
89 self.data[self.len] = byte;
90 self.len += 1;
91 true
92 }
93
94 pub fn extend_from_slice(&mut self, slice: &[u8]) -> bool {
96 if self.len + slice.len() > N {
97 return false;
98 }
99 self.data[self.len..self.len + slice.len()].copy_from_slice(slice);
100 self.len += slice.len();
101 true
102 }
103}
104
105impl<const N: usize> Default for StackBuffer<N> {
106 fn default() -> Self {
107 Self::new()
108 }
109}
110
111#[derive(Debug, Default)]
117pub struct MemoryTracker {
118 current: Cell<usize>,
119 peak: Cell<usize>,
120 limit: usize,
121}
122
123impl MemoryTracker {
124 pub const fn new() -> Self {
126 Self {
127 current: Cell::new(0),
128 peak: Cell::new(0),
129 limit: 0,
130 }
131 }
132
133 pub const fn with_limit(limit: usize) -> Self {
135 Self {
136 current: Cell::new(0),
137 peak: Cell::new(0),
138 limit,
139 }
140 }
141
142 pub fn allocate(&self, bytes: usize) -> Result<(), &'static str> {
144 let new_current = self.current.get().saturating_add(bytes);
145 if self.limit > 0 && new_current > self.limit {
146 return Err("Memory limit exceeded");
147 }
148 self.current.set(new_current);
149 if new_current > self.peak.get() {
150 self.peak.set(new_current);
151 }
152 Ok(())
153 }
154
155 pub fn deallocate(&self, bytes: usize) {
157 let current = self.current.get();
158 self.current.set(current.saturating_sub(bytes));
159 }
160
161 pub fn current(&self) -> usize {
163 self.current.get()
164 }
165
166 pub fn peak(&self) -> usize {
168 self.peak.get()
169 }
170
171 pub fn limit(&self) -> usize {
173 self.limit
174 }
175
176 pub fn reset(&self) {
178 self.current.set(0);
179 self.peak.set(0);
180 }
181}
182
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
189pub struct EmbeddedLimits {
190 pub max_depth: usize,
192 pub max_token_length: usize,
194 pub max_container_items: usize,
196}
197
198impl EmbeddedLimits {
199 pub const CONSERVATIVE: Self = Self {
201 max_depth: 16,
202 max_token_length: 256,
203 max_container_items: 64,
204 };
205
206 pub const MINIMAL: Self = Self {
208 max_depth: 8,
209 max_token_length: 64,
210 max_container_items: 16,
211 };
212
213 #[inline]
215 pub fn check_depth(&self, current_depth: usize) -> Result<(), ErrorCode> {
216 if current_depth > self.max_depth {
217 Err(ErrorCode::SyntaxError)
218 } else {
219 Ok(())
220 }
221 }
222}
223
224impl Default for EmbeddedLimits {
225 fn default() -> Self {
226 Self::CONSERVATIVE
227 }
228}
229
230#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
236pub struct CompactError {
237 pub code: ErrorCode,
239 pub offset: u32,
241}
242
243impl CompactError {
244 pub const fn new(code: ErrorCode, offset: u32) -> Self {
246 Self { code, offset }
247 }
248}
249
250impl core::fmt::Display for CompactError {
251 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
252 write!(f, "{:?} at byte offset {}", self.code, self.offset)
253 }
254}
255
256#[cfg(test)]
257mod tests {
258 use super::*;
259
260 #[test]
261 fn test_stack_buffer() {
262 let mut buf = StackBuffer::<16>::new();
263 assert!(buf.is_empty());
264 assert_eq!(buf.capacity(), 16);
265 assert_eq!(buf.remaining(), 16);
266
267 assert!(buf.push(b'H'));
268 assert!(buf.push(b'i'));
269 assert_eq!(buf.len(), 2);
270 assert_eq!(buf.as_slice(), b"Hi");
271 assert_eq!(buf.as_str().unwrap(), "Hi");
272
273 assert!(buf.extend_from_slice(b" embedded"));
274 assert_eq!(buf.as_str().unwrap(), "Hi embedded");
275
276 assert!(!buf.extend_from_slice(b" this will overflow the buffer capacity"));
277 buf.clear();
278 assert!(buf.is_empty());
279 }
280
281 #[test]
282 fn test_memory_tracker() {
283 let tracker = MemoryTracker::with_limit(100);
284 assert_eq!(tracker.current(), 0);
285 assert_eq!(tracker.limit(), 100);
286
287 assert!(tracker.allocate(60).is_ok());
288 assert_eq!(tracker.current(), 60);
289 assert_eq!(tracker.peak(), 60);
290
291 assert!(tracker.allocate(50).is_err()); tracker.deallocate(20);
293 assert_eq!(tracker.current(), 40);
294 assert_eq!(tracker.peak(), 60); }
296
297 #[test]
298 fn test_limits() {
299 let limits = EmbeddedLimits::CONSERVATIVE;
300 assert!(limits.check_depth(10).is_ok());
301 assert!(limits.check_depth(17).is_err());
302 }
303
304 #[test]
305 fn test_compact_error() {
306 let err = CompactError::new(ErrorCode::UnexpectedEof, 42);
307 assert_eq!(err.code, ErrorCode::UnexpectedEof);
308 assert_eq!(err.offset, 42);
309 }
310}