Skip to main content

kernel/lib/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 const fn new() -> Self {
16        Self {
17            buf: [0u8; N],
18            pos: 0
19        }
20    }
21
22    /// Return the bytes written so far as a `&str` (empty on invalid UTF-8).
23    pub fn as_str(&self) -> &str {
24        core::str::from_utf8(
25            &self.buf[..self.pos]
26        ).unwrap_or("")
27    }
28}
29
30impl<const N: usize> core::fmt::Write for FmtBuffer<N> {
31    fn write_str(&mut self, s: &str) -> core::fmt::Result {
32        let bytes = s.as_bytes();
33        let remaining = N - self.pos;
34        let to_copy = bytes.len().min(remaining);
35
36        self.buf[self.pos..self.pos + to_copy].copy_from_slice(&bytes[..to_copy]);
37        self.pos += to_copy;
38
39        Ok(())
40    }
41}