50 lines
1.3 KiB
Rust
50 lines
1.3 KiB
Rust
use owned_str::{Error, OwnedStr};
|
|
use ufmt::uWrite;
|
|
|
|
pub struct OwnedStrWriter<const CAP: usize>(OwnedStr<CAP>);
|
|
|
|
impl<const CAP: usize> OwnedStrWriter<CAP> {
|
|
pub fn new() -> Self {
|
|
Self(OwnedStr::new())
|
|
}
|
|
|
|
pub fn push(&mut self, c: char) -> Result<(), Error> {
|
|
self.0.try_push(c).map(|_| ())
|
|
}
|
|
}
|
|
|
|
impl<const CAP: usize> From<OwnedStr<CAP>> for OwnedStrWriter<CAP> {
|
|
fn from(owned_str: OwnedStr<CAP>) -> Self {
|
|
Self(owned_str)
|
|
}
|
|
}
|
|
|
|
impl<const CAP: usize> From<OwnedStrWriter<CAP>> for OwnedStr<CAP> {
|
|
fn from(writer: OwnedStrWriter<CAP>) -> Self {
|
|
writer.0
|
|
}
|
|
}
|
|
|
|
impl<const CAP: usize> uWrite for OwnedStrWriter<CAP> {
|
|
type Error = owned_str::Error;
|
|
fn write_str(&mut self, s: &str) -> Result<(), Self::Error> {
|
|
self.0.try_push_str(s).map(|_| ())
|
|
}
|
|
fn write_char(&mut self, c: char) -> Result<(), Self::Error> {
|
|
self.0.try_push(c).map(|_| ())
|
|
}
|
|
}
|
|
|
|
pub fn center_str<const CAP: usize>(
|
|
str: &str,
|
|
width: usize,
|
|
) -> Result<OwnedStr<CAP>, owned_str::Error> {
|
|
let mut res = OwnedStr::new();
|
|
let len = str.len();
|
|
let padding = (width.saturating_sub(len) + 1) / 2;
|
|
for _ in 0..padding {
|
|
res.try_push(' ')?;
|
|
}
|
|
res.try_push_str(str)?;
|
|
Ok(res)
|
|
}
|