Skip to main content

kernel/types/
fmt_buffer.rs

1// SPDX-License-Identifier: GPL-3.0-only
2//! Fixed-capacity formatting buffer for no-alloc contexts.
3//!
4//! Authors: MarioS271
5
6/// Stack-allocated, fixed-size [`core::fmt::Write`] buffer for no-alloc contexts
7/// (interrupt handlers, panic path). Writes beyond capacity `N` are silently dropped.
8pub struct FmtBuffer<const N: usize> {
9    buf: [u8; N],
10    pos: usize,
11}
12
13impl<const N: usize> FmtBuffer<N> {
14    /// Create an empty buffer with all bytes zeroed.
15    pub fn new() -> Self {
16        Self { buf: [0u8; N], pos: 0 }
17    }
18
19    /// Return the bytes written so far as a `&str` (empty on invalid UTF-8).
20    pub fn as_str(&self) -> &str {
21        core::str::from_utf8(&self.buf[..self.pos]).unwrap_or("")
22    }
23}
24
25impl<const N: usize> core::fmt::Write for FmtBuffer<N> {
26    fn write_str(&mut self, s: &str) -> core::fmt::Result {
27        let bytes = s.as_bytes();
28        let remaining = N - self.pos;
29        let to_copy = bytes.len().min(remaining);
30        self.buf[self.pos..self.pos + to_copy].copy_from_slice(&bytes[..to_copy]);
31        self.pos += to_copy;
32        Ok(())
33    }
34}