From e310eee4682162c4d102d09fd01ec1193ee6afa0 Mon Sep 17 00:00:00 2001 From: Drew Galbraith Date: Fri, 26 Jul 2024 15:57:10 -0700 Subject: [PATCH] Add method for formatting strings. --- rust/lib/mammoth/src/syscall.rs | 50 +++++++++++++++++++++++++++++++++ rust/usr/testbed/src/main.rs | 2 ++ 2 files changed, 52 insertions(+) diff --git a/rust/lib/mammoth/src/syscall.rs b/rust/lib/mammoth/src/syscall.rs index 030edc1..768a85f 100644 --- a/rust/lib/mammoth/src/syscall.rs +++ b/rust/lib/mammoth/src/syscall.rs @@ -1,4 +1,9 @@ +extern crate alloc; + +use alloc::string::String; +use alloc::vec::Vec; use core::ffi::c_void; +use core::fmt; use core::panic::PanicInfo; include!("bindings.rs"); @@ -29,3 +34,48 @@ pub fn debug(msg: &str) { }; syscall(kZionDebug, &req); } + +pub struct Writer { + int_vec: Vec, +} + +impl Writer { + pub fn new() -> Self { + Self { + int_vec: Vec::new(), + } + } +} + +impl Into for Writer { + fn into(self) -> String { + String::from_utf8(self.int_vec).expect("Failed to convert") + } +} + +impl fmt::Write for Writer { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.bytes() { + self.int_vec.push(c); + } + fmt::Result::Ok(()) + } +} + +#[macro_export] +macro_rules! debug { + () => { + debug(""); + }; + ($fmt:literal) => { + debug($fmt); + }; + ($fmt:literal, $($val:expr),+) => {{ + use core::fmt::Write as _; + use alloc::string::String; + let mut w = mammoth::syscall::Writer::new(); + write!(&mut w, $fmt, $($val),*).expect("Failed to format"); + let s: String = w.into(); + debug(&s); + }}; +} diff --git a/rust/usr/testbed/src/main.rs b/rust/usr/testbed/src/main.rs index 3804002..d771249 100644 --- a/rust/usr/testbed/src/main.rs +++ b/rust/usr/testbed/src/main.rs @@ -4,6 +4,7 @@ extern crate alloc; use alloc::boxed::Box; +use mammoth::debug; use mammoth::define_entry; use mammoth::syscall::debug; use mammoth::syscall::z_err_t; @@ -15,5 +16,6 @@ pub extern "C" fn main() -> z_err_t { debug("Testing!"); let x = Box::new("Heap str"); debug(&x); + debug!("Formatted {}", "string"); 0 }