interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-kernel / src / report.rs

90 lines · 2547 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Fixed-capacity text buffer for boot reports, usable without a heap.
17//!
18//! The same report text is sent to every output (screen, firmware variable,
19//! serial), so all of them carry identical evidence.
20
21use core::fmt;
22
23pub struct ReportBuf<const N: usize> {
24 bytes: [u8; N],
25 len: usize,
26 truncated: bool,
27}
28
29impl<const N: usize> Default for ReportBuf<N> {
30 fn default() -> Self {
31 Self::new()
32 }
33}
34
35impl<const N: usize> ReportBuf<N> {
36 pub const fn new() -> Self {
37 Self {
38 bytes: [0; N],
39 len: 0,
40 truncated: false,
41 }
42 }
43
44 pub fn as_bytes(&self) -> &[u8] {
45 &self.bytes[..self.len]
46 }
47
48 pub fn as_str(&self) -> &str {
49 // Only whole UTF-8 characters are ever appended.
50 core::str::from_utf8(self.as_bytes()).unwrap_or("")
51 }
52
53 /// True if some text did not fit.
54 pub fn truncated(&self) -> bool {
55 self.truncated
56 }
57}
58
59impl<const N: usize> fmt::Write for ReportBuf<N> {
60 fn write_str(&mut self, s: &str) -> fmt::Result {
61 for c in s.chars() {
62 let mut tmp = [0u8; 4];
63 let encoded = c.encode_utf8(&mut tmp).as_bytes();
64 if self.len + encoded.len() > N {
65 self.truncated = true;
66 return Ok(());
67 }
68 self.bytes[self.len..self.len + encoded.len()].copy_from_slice(encoded);
69 self.len += encoded.len();
70 }
71 Ok(())
72 }
73}
74
75#[cfg(test)]
76mod tests {
77 use super::*;
78 use core::fmt::Write;
79
80 #[test]
81 fn formats_and_truncates_on_character_boundaries() {
82 let mut r = ReportBuf::<8>::new();
83 write!(r, "ab{}", 12).unwrap();
84 assert_eq!(r.as_str(), "ab12");
85 write!(r, "é€xyz").unwrap();
86 assert!(r.truncated());
87 assert_eq!(r.as_str(), "ab12é");
88 assert!(r.as_bytes().len() <= 8);
89 }
90}