From 4650e865fb798f32cbfddf9dd450cb17f6abf293 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Fri, 30 Oct 2020 20:48:34 +0800 Subject: [PATCH] xous: String: add `from_message()` as an initializer Allow creating a `String` from a `MemoryMessage`. Signed-off-by: Sean Cross --- xous-rs/src/string.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/xous-rs/src/string.rs b/xous-rs/src/string.rs index c17d7f2eb..69afa189b 100644 --- a/xous-rs/src/string.rs +++ b/xous-rs/src/string.rs @@ -25,6 +25,25 @@ impl<'a> String<'a> { } } + pub fn len(&self) -> usize { + self.len + } + + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + /// Convert a `MemoryMessage` into a `String` + pub fn from_message(message: &'a mut MemoryMessage) -> core::result::Result, core::str::Utf8Error> { + let raw_slice = unsafe { core::slice::from_raw_parts_mut(message.buf.as_mut_ptr(), message.buf.len()) }; + let starting_length = message.valid.map(|x| x.get()).unwrap_or(0); + Ok(String { + raw_slice, + s: core::str::from_utf8(unsafe { core::slice::from_raw_parts(message.buf.as_ptr(), starting_length) })?, + len: 0, + }) + } + /// Perform an immutable lend of this String to the specified server. /// This function will block until the server returns. pub fn lend(&self, connection: CID, id: usize) -> core::result::Result {