rust-sen/sehn/src/utils/string_writer.rs

37 lines
646 B
Rust

use std::str::Utf8Error;
use std::string::FromUtf8Error;
use crate::se::{Write, SerializerError};
pub struct StringWriter {
buf: Vec<u8>
}
impl StringWriter {
pub fn new() -> Self {
Self {
buf: Vec::new()
}
}
pub fn clear(&mut self) {
self.buf.clear();
}
pub fn as_str(&self) -> Result<&str, Utf8Error> {
std::str::from_utf8(self.buf.as_ref())
}
pub fn to_string(self) -> Result<String, FromUtf8Error> {
String::from_utf8(self.buf)
}
}
impl Write for &mut StringWriter {
type Error = SerializerError;
fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error> {
self.buf.extend_from_slice(bytes);
Ok(())
}
}