From ddd728cd5d61c3f94f9e13c5fabdde70d8ac4fa6 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Mon, 14 Aug 2023 15:50:50 +0300 Subject: [PATCH] add utils::BincodeVecWriter --- lib/src/util.rs | 71 +++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 57 insertions(+), 14 deletions(-) diff --git a/lib/src/util.rs b/lib/src/util.rs index e33f587..e7c431a 100644 --- a/lib/src/util.rs +++ b/lib/src/util.rs @@ -1,14 +1,57 @@ -pub trait ErrorToString { - type Output; - fn str_err(self) -> std::result::Result; -} - -impl ErrorToString for std::result::Result -where - E: std::error::Error, -{ - type Output = T; - fn str_err(self) -> std::result::Result { - self.map_err(|e| e.to_string()) - } -} +pub trait ErrorToString { + type Output; + fn str_err(self) -> std::result::Result; +} + +impl ErrorToString for std::result::Result +where + E: std::error::Error, +{ + type Output = T; + fn str_err(self) -> std::result::Result { + self.map_err(|e| e.to_string()) + } +} + +#[cfg(any(feature = "sync", feature = "async"))] +mod bincode_utils { + use std::ops::{Deref, DerefMut}; + + use bincode::enc::write::Writer; + use bincode::error::EncodeError; + + /// struct that allows [`Vec`] to implement [bincode::enc::write::Writer] trait + pub struct BincodeVecWriter { + vec: Vec, + } + + impl BincodeVecWriter { + pub fn new(vec: Vec) -> BincodeVecWriter { + BincodeVecWriter { vec } + } + } + + impl Deref for BincodeVecWriter { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.vec + } + } + + impl DerefMut for BincodeVecWriter { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.vec + } + } + + impl Writer for BincodeVecWriter { + fn write(&mut self, bytes: &[u8]) -> Result<(), EncodeError> { + self.vec.extend_from_slice(bytes); + Ok(()) + } + } +} + +#[cfg(any(feature = "sync", feature = "async"))] +pub use bincode_utils::BincodeVecWriter;