From 7fc8dafc39de4d8474e37e2142561b93fb0d2de0 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Fri, 30 Oct 2020 10:29:58 +0800 Subject: [PATCH] shell: add `StringBuffer` struct Add a StringBuffer struct that can be used to create string messages. This will eventually be promoted to Xous. Signed-off-by: Sean Cross --- services/shell/src/main.rs | 65 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/services/shell/src/main.rs b/services/shell/src/main.rs index 04f91c3af..e3da76167 100644 --- a/services/shell/src/main.rs +++ b/services/shell/src/main.rs @@ -36,6 +36,71 @@ fn ensure_connection(server: xous::SID) -> xous::CID { } } +struct StringBuffer<'a> { + raw_slice: &'a mut [u8], + pub s: &'a str, + pub len: usize, +} + +impl<'a> StringBuffer<'a> { + pub fn new(max: usize) -> StringBuffer<'a> { + let mem = xous::map_memory(None, None, max, xous::MemoryFlags::R | xous::MemoryFlags::W).unwrap(); + let p = mem.as_mut_ptr(); + for i in 0..max { + unsafe { p.add(i).write_volatile(0) }; + } + StringBuffer { + raw_slice: unsafe { core::slice::from_raw_parts_mut(mem.as_mut_ptr(), max)}, + s: unsafe { + core::str::from_utf8_unchecked(core::slice::from_raw_parts(mem.as_ptr(), 0)) + }, + len: 0, + } + } + + /// Perform an immutable lend of this Carton to the specified server. + /// This function will block until the server returns. + pub fn lend(&self, connection: xous::CID, id: usize) -> Result { + let memory_range = xous::MemoryRange::new(self.raw_slice.as_ptr() as _, self.raw_slice.len()).unwrap(); + let msg = xous::MemoryMessage { + id, + buf: memory_range, + offset: None, + valid: xous::MemorySize::new(self.len).map(|x| Some(x)).unwrap_or(None), + }; + xous::send_message(connection, xous::Message::Borrow(msg)) + } + + pub fn clear(&mut self) { + self.len = 0; + self.s = unsafe { + core::str::from_utf8_unchecked(core::slice::from_raw_parts(self.raw_slice.as_ptr(), self.len)) + }; + } +} + +impl<'a> core::fmt::Display for StringBuffer<'a> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{}", self.s) + } +} + +impl<'a> core::fmt::Write for StringBuffer<'a> { + fn write_str(&mut self, s: &str) -> Result<(), core::fmt::Error> { + for c in s.bytes() { + if self.len < self.raw_slice.len() { + self.raw_slice[self.len] = c; + self.len += 1; + } + } + self.s = unsafe { + core::str::from_utf8_unchecked(core::slice::from_raw_parts(self.raw_slice.as_ptr(), self.len)) + }; + Ok(()) + } +} + + #[xous::xous_main] fn shell_main() -> ! { timer::init();