`StackString<SIZE>`: Added `fmt::Write`, `io::Write` impls

`StackString<SIZE>`: Added `fmt::Display` impl

Fortune for stack-str's current commit: Middle blessing − 中吉
master
Avril 3 years ago
parent c40b415a06
commit 99ada01140
Signed by: flanchan
GPG Key ID: 284488987C31F630

@ -114,7 +114,7 @@ impl<const SIZE: usize> StackString<SIZE>
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<const SIZE: usize> TryFrom<[u8; SIZE]> for StackString<SIZE>
Self::try_from_utf8_array(from)
}
}
impl<const SIZE: usize> fmt::Display for StackString<SIZE>
{
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
{
f.write_str(self.as_str())
}
}
impl<const SIZE: usize> fmt::Write for StackString<SIZE>
{
#[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<const SIZE: usize> Write for StackString<SIZE>
{
#[inline]
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
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(|_| ())
}
}
};

Loading…
Cancel
Save