From 39b2646cbfd8db117008d002c86d9fd8f98fdc29 Mon Sep 17 00:00:00 2001 From: Cerber Ursi Date: Sat, 27 Nov 2021 19:09:09 +0700 Subject: [PATCH] Convinience functions in crate root --- src/error.rs | 2 ++ src/lib.rs | 19 ++++++++++++++++++- src/ser.rs | 9 ++++++++- 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/error.rs b/src/error.rs index 4681011..92de498 100644 --- a/src/error.rs +++ b/src/error.rs @@ -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), } diff --git a/src/lib.rs b/src/lib.rs index 5ecaf2e..a4b0365 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,2 +1,19 @@ +use crate::ser::SerResult; +use serde::Serialize; + +pub mod error; pub mod ser; -pub mod error; \ No newline at end of file + +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) -> SerResult { + value.serialize(&mut ser::Corona::new(std::fs::File::create(target)?)) +} + +pub fn to_string(value: impl Serialize) -> Result { + let mut out = Vec::new(); + value.serialize(&mut ser::Corona::new(&mut out))?; + Ok(String::from_utf8(out)?) +} \ No newline at end of file diff --git a/src/ser.rs b/src/ser.rs index 53c1750..64b0c03 100644 --- a/src/ser.rs +++ b/src/ser.rs @@ -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 { writer: W, @@ -10,6 +10,13 @@ pub struct Corona { } impl Corona { + pub(crate) fn new(target: W) -> Self { + Self { + writer: target, + inside: false, + } + } + fn start_sub(&mut self) -> &mut Self { self.inside = true; self