Convinience functions in crate root

This commit is contained in:
Cerber Ursi
2021-11-27 19:09:09 +07:00
parent d69f08cf02
commit 39b2646cbf
3 changed files with 28 additions and 2 deletions
+2
View File
@@ -5,6 +5,8 @@ use thiserror::Error;
pub enum CoronaError {
#[error("IO error while writing code: {0}")]
Io(#[from] std::io::Error),
#[error("Serialization process yielded invalid UTF-8 sequence: {0}")]
Utf8(#[from] std::string::FromUtf8Error),
#[error("Unknown error: {0}")]
Custom(String),
}
+18 -1
View File
@@ -1,2 +1,19 @@
use crate::ser::SerResult;
use serde::Serialize;
pub mod error;
pub mod ser;
pub mod error;
pub fn write(value: impl Serialize, target: impl std::io::Write) -> SerResult {
value.serialize(&mut ser::Corona::new(target))
}
pub fn to_file(value: impl Serialize, target: impl AsRef<std::path::Path>) -> SerResult {
value.serialize(&mut ser::Corona::new(std::fs::File::create(target)?))
}
pub fn to_string(value: impl Serialize) -> Result<String, error::CoronaError> {
let mut out = Vec::new();
value.serialize(&mut ser::Corona::new(&mut out))?;
Ok(String::from_utf8(out)?)
}
+8 -1
View File
@@ -2,7 +2,7 @@ use crate::error::CoronaError;
use serde::ser;
use std::io::Write;
type SerResult = Result<(), CoronaError>;
pub(crate) type SerResult = Result<(), CoronaError>;
pub struct Corona<W: Write> {
writer: W,
@@ -10,6 +10,13 @@ pub struct Corona<W: Write> {
}
impl<W: Write> Corona<W> {
pub(crate) fn new(target: W) -> Self {
Self {
writer: target,
inside: false,
}
}
fn start_sub(&mut self) -> &mut Self {
self.inside = true;
self