|
| 1 | +use heapless::{String, Vec}; |
| 2 | + |
| 3 | +/// A fixed-capacity event log that never touches the heap. |
| 4 | +/// |
| 5 | +/// In real-time and safety-critical systems the global allocator is |
| 6 | +/// forbidden because allocation time is unbounded and fragmentation |
| 7 | +/// can cause silent OOM failures in long-running firmware. |
| 8 | +/// |
| 9 | +/// [`heapless::Vec`] stores up to `N` elements on the stack (or in a |
| 10 | +/// `static`). The capacity is fixed at compile time, so the memory |
| 11 | +/// footprint is constant and predictable. |
| 12 | +struct EventLog<const N: usize> { |
| 13 | + entries: Vec<Event, N>, |
| 14 | +} |
| 15 | + |
| 16 | +#[derive(Debug, Clone)] |
| 17 | +struct Event { |
| 18 | + timestamp_ms: u32, |
| 19 | + code: u16, |
| 20 | +} |
| 21 | + |
| 22 | +impl<const N: usize> EventLog<N> { |
| 23 | + /// Creates an empty log. |
| 24 | + fn new() -> Self { |
| 25 | + Self { |
| 26 | + entries: Vec::new(), |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + /// Records an event. Returns `Err` if the log is full instead |
| 31 | + /// of panicking or allocating—the caller decides what to do. |
| 32 | + fn record(&mut self, timestamp_ms: u32, code: u16) -> Result<(), Event> { |
| 33 | + let event = Event { timestamp_ms, code }; |
| 34 | + self.entries.push(event).map_err(|e| e) |
| 35 | + } |
| 36 | + |
| 37 | + /// Returns how many events have been recorded. |
| 38 | + fn len(&self) -> usize { |
| 39 | + self.entries.len() |
| 40 | + } |
| 41 | + |
| 42 | + /// Returns the most recent event, if any. |
| 43 | + fn latest(&self) -> Option<&Event> { |
| 44 | + self.entries.last() |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +/// Formats a sensor label without heap allocation. |
| 49 | +/// |
| 50 | +/// [`heapless::String<N>`] works like `std::string::String` but |
| 51 | +/// stores up to `N` bytes on the stack. `write!` returns `Err` if |
| 52 | +/// the formatted text would exceed capacity. |
| 53 | +fn format_label(sensor_id: u16, value: f32) -> Result<String<32>, core::fmt::Error> { |
| 54 | + use core::fmt::Write; |
| 55 | + let mut buf: String<32> = String::new(); |
| 56 | + write!(buf, "S{sensor_id}={value:.1}")?; |
| 57 | + Ok(buf) |
| 58 | +} |
| 59 | + |
| 60 | +fn main() { |
| 61 | + // A log that holds at most 8 events — zero heap allocation. |
| 62 | + let mut log: EventLog<8> = EventLog::new(); |
| 63 | + |
| 64 | + log.record(100, 0x01).expect("log not full"); |
| 65 | + log.record(200, 0x02).expect("log not full"); |
| 66 | + log.record(300, 0xFF).expect("log not full"); |
| 67 | + |
| 68 | + println!("logged {} events", log.len()); |
| 69 | + println!("latest: {:?}", log.latest().unwrap()); |
| 70 | + |
| 71 | + // Stack-allocated string formatting. |
| 72 | + let label = format_label(42, 3.14).expect("fits in 32 bytes"); |
| 73 | + println!("label: {label}"); |
| 74 | + |
| 75 | + // Demonstrate capacity enforcement — the 9th push returns Err. |
| 76 | + let mut full_log: EventLog<2> = EventLog::new(); |
| 77 | + full_log.record(0, 1).unwrap(); |
| 78 | + full_log.record(1, 2).unwrap(); |
| 79 | + let overflow = full_log.record(2, 3); |
| 80 | + assert!(overflow.is_err()); |
| 81 | + println!("overflow correctly rejected"); |
| 82 | +} |
| 83 | + |
| 84 | +#[cfg(test)] |
| 85 | +mod tests { |
| 86 | + use super::*; |
| 87 | + |
| 88 | + #[test] |
| 89 | + fn test_event_log_records_and_retrieves() { |
| 90 | + let mut log: EventLog<4> = EventLog::new(); |
| 91 | + log.record(10, 0xAA).unwrap(); |
| 92 | + log.record(20, 0xBB).unwrap(); |
| 93 | + |
| 94 | + assert_eq!(log.len(), 2); |
| 95 | + assert_eq!(log.latest().unwrap().code, 0xBB); |
| 96 | + } |
| 97 | + |
| 98 | + #[test] |
| 99 | + fn test_event_log_rejects_overflow() { |
| 100 | + let mut log: EventLog<1> = EventLog::new(); |
| 101 | + assert!(log.record(0, 1).is_ok()); |
| 102 | + assert!(log.record(1, 2).is_err()); |
| 103 | + assert_eq!(log.len(), 1); |
| 104 | + } |
| 105 | + |
| 106 | + #[test] |
| 107 | + fn test_format_label() { |
| 108 | + let label = format_label(7, 25.0).unwrap(); |
| 109 | + assert_eq!(label.as_str(), "S7=25.0"); |
| 110 | + } |
| 111 | + |
| 112 | + #[test] |
| 113 | + fn test_format_label_overflow() { |
| 114 | + // heapless::String<4> can only hold 4 bytes — "S1=0.0" won't fit. |
| 115 | + use core::fmt::Write; |
| 116 | + let mut tiny: heapless::String<4> = heapless::String::new(); |
| 117 | + let result = write!(tiny, "S1=99.9"); |
| 118 | + assert!(result.is_err()); |
| 119 | + } |
| 120 | +} |
0 commit comments