From 99ada011405a16aa2f38ae51d2e955746e876849 Mon Sep 17 00:00:00 2001 From: Avril Date: Fri, 15 Apr 2022 23:15:06 +0100 Subject: [PATCH] `StackString`: Added `fmt::Write`, `io::Write` impls MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `StackString`: Added `fmt::Display` impl Fortune for stack-str's current commit: Middle blessing − 中吉 --- src/lib.rs | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 5b495d1..fbd0ef3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -114,7 +114,7 @@ impl StackString fn as_raw_buf(&self) -> &[u8] { unsafe { - // MaybeUninit::slice_assume_init_ref(&self.buffer.as_bytes()[..self.fill_ptr]); + // MaybeUninit::slice_assume_init_ref(&self.buffer.as_bytes()[..self.fill_ptr]); slice::from_raw_parts(self.buffer.as_ptr() as *const u8, self.fill_ptr) } } @@ -283,3 +283,57 @@ impl TryFrom<[u8; SIZE]> for StackString Self::try_from_utf8_array(from) } } + +impl fmt::Display for StackString +{ + #[inline] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result + { + f.write_str(self.as_str()) + } +} + + +impl fmt::Write for StackString +{ + #[inline] + fn write_str(&mut self, s: &str) -> fmt::Result { + self.try_append_whole_str(s).map_err(|_| fmt::Error::default())?; + Ok(()) + } + #[inline] + fn write_char(&mut self, c: char) -> fmt::Result { + let l = c.len_utf8(); + if l > self.available() { + Err(fmt::Error::default()) + } else { + let end = self.fill_ptr; + let end = c.encode_utf8(&mut (self.as_raw_buf_mut())[end..]).len(); + self.fill_ptr += end; + Ok(()) + } + } +} + +const _: () = { + use std::io::{ + self,Write + }; + impl Write for StackString + { + #[inline] + fn write(&mut self, buf: &[u8]) -> std::io::Result { + let buf = std::str::from_utf8(buf).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + Ok(self.append_from_str(buf)) + } + #[inline] + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + #[inline] + fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { + let buf = std::str::from_utf8(buf).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + self.try_append_whole_str(buf).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)).map(|_| ()) + } + } +};