Skip to main content

babbel_core/embedded/
mod.rs

1//! Embedded Systems & Zero-Allocation Primitives
2//!
3//! Provides utilities, limits, stack-allocated buffers, and compact error reporting
4//! tailored for resource-constrained microcontrollers, real-time operating systems (RTOS),
5//! and bare-metal environments (`no_std` / `no_alloc`).
6
7use crate::error::ErrorCode;
8use core::cell::Cell;
9
10// ==========================================
11// 1. StackBuffer
12// ==========================================
13
14/// Fixed-size stack-allocated byte buffer using const generics.
15///
16/// Provides a way to store, read, and manipulate byte sequences exclusively on
17/// the call stack without dynamic heap allocation.
18#[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    /// Creates a new empty stack buffer.
26    pub const fn new() -> Self {
27        Self {
28            data: [0u8; N],
29            len: 0,
30        }
31    }
32
33    /// Creates a stack buffer from a byte slice. Returns `None` if `slice.len() > N`.
34    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    /// Returns the data as a byte slice.
45    pub fn as_slice(&self) -> &[u8] {
46        &self.data[..self.len]
47    }
48
49    /// Returns the data as a mutable byte slice.
50    pub fn as_mut_slice(&mut self) -> &mut [u8] {
51        &mut self.data[..self.len]
52    }
53
54    /// Returns the written content as a string slice if valid UTF-8.
55    pub fn as_str(&self) -> Result<&str, core::str::Utf8Error> {
56        core::str::from_utf8(self.as_slice())
57    }
58
59    /// Returns the number of bytes stored.
60    pub const fn len(&self) -> usize {
61        self.len
62    }
63
64    /// Returns true if the buffer is empty.
65    pub const fn is_empty(&self) -> bool {
66        self.len == 0
67    }
68
69    /// Returns the total capacity `N`.
70    pub const fn capacity(&self) -> usize {
71        N
72    }
73
74    /// Returns remaining available bytes.
75    pub const fn remaining(&self) -> usize {
76        N.saturating_sub(self.len)
77    }
78
79    /// Clears the buffer.
80    pub fn clear(&mut self) {
81        self.len = 0;
82    }
83
84    /// Attempts to push a single byte. Returns `false` if full.
85    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    /// Attempts to extend the buffer from a byte slice. Returns `false` if insufficient capacity.
95    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// ==========================================
112// 2. MemoryTracker
113// ==========================================
114
115/// Tracks memory allocations and peak watermarks for resource-constrained environments.
116#[derive(Debug, Default)]
117pub struct MemoryTracker {
118    current: Cell<usize>,
119    peak: Cell<usize>,
120    limit: usize,
121}
122
123impl MemoryTracker {
124    /// Creates a new memory tracker without an upper limit.
125    pub const fn new() -> Self {
126        Self {
127            current: Cell::new(0),
128            peak: Cell::new(0),
129            limit: 0,
130        }
131    }
132
133    /// Creates a new memory tracker with a hard byte limit.
134    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    /// Records an allocation of `bytes`. Returns `Err` if it would exceed `limit`.
143    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    /// Records a deallocation of `bytes`.
156    pub fn deallocate(&self, bytes: usize) {
157        let current = self.current.get();
158        self.current.set(current.saturating_sub(bytes));
159    }
160
161    /// Returns the current number of allocated bytes.
162    pub fn current(&self) -> usize {
163        self.current.get()
164    }
165
166    /// Returns the peak watermarked bytes.
167    pub fn peak(&self) -> usize {
168        self.peak.get()
169    }
170
171    /// Returns the configured limit (0 = unlimited).
172    pub fn limit(&self) -> usize {
173        self.limit
174    }
175
176    /// Resets the tracker.
177    pub fn reset(&self) {
178        self.current.set(0);
179        self.peak.set(0);
180    }
181}
182
183// ==========================================
184// 3. EmbeddedLimits
185// ==========================================
186
187/// Runtime and compile-time limits to protect against stack overflows and excessive resource consumption.
188#[derive(Debug, Clone, Copy, PartialEq, Eq)]
189pub struct EmbeddedLimits {
190    /// Maximum recursive nesting depth (default: 16).
191    pub max_depth: usize,
192    /// Maximum token or string length in bytes (default: 256).
193    pub max_token_length: usize,
194    /// Maximum container elements (default: 64).
195    pub max_container_items: usize,
196}
197
198impl EmbeddedLimits {
199    /// Standard conservative limits for 32-bit microcontrollers (e.g. ARM Cortex-M).
200    pub const CONSERVATIVE: Self = Self {
201        max_depth: 16,
202        max_token_length: 256,
203        max_container_items: 64,
204    };
205
206    /// Minimal limits for ultra-constrained systems (e.g. 8-bit AVR or Cortex-M0 with <= 4KB RAM).
207    pub const MINIMAL: Self = Self {
208        max_depth: 8,
209        max_token_length: 64,
210        max_container_items: 16,
211    };
212
213    /// Checks if a nesting depth exceeds configured limit.
214    #[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// ==========================================
231// 4. CompactError (Zero-Allocation Error)
232// ==========================================
233
234/// Zero-allocation 8-byte diagnostic error for bare-metal embedded targets (`no_alloc`).
235#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
236pub struct CompactError {
237    /// Standardized error classification
238    pub code: ErrorCode,
239    /// 0-based byte offset in input stream
240    pub offset: u32,
241}
242
243impl CompactError {
244    /// Creates a new compact error.
245    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()); // 60 + 50 = 110 > 100
292        tracker.deallocate(20);
293        assert_eq!(tracker.current(), 40);
294        assert_eq!(tracker.peak(), 60); // Peak retained
295    }
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}