ya_service_bus/
serialization.rs1use std::sync::atomic::{AtomicBool, Ordering};
2
3#[cfg(feature = "flex")]
4pub use flex::{DecodeError, EncodeError};
5#[cfg(feature = "json")]
6pub use json::{DecodeError, EncodeError};
7
8lazy_static::lazy_static! {
9 pub static ref CONFIG: Config = Config::default();
10}
11
12#[derive(Default)]
13pub struct Config {
14 compress: AtomicBool,
15}
16
17impl Config {
18 pub fn set_compress(&self, val: bool) {
19 self.compress.store(val, Ordering::SeqCst);
20 }
21}
22
23pub fn to_vec<T: serde::Serialize>(value: &T) -> Result<Vec<u8>, EncodeError> {
24 #[cfg(feature = "flex")]
25 use flex::to_vec;
26 #[cfg(feature = "json")]
27 use json::to_vec;
28
29 to_vec(value).map(|vec| {
30 if CONFIG.compress.load(Ordering::SeqCst) {
31 miniz_oxide::deflate::compress_to_vec_zlib(vec.as_slice(), 6)
32 } else {
33 vec
34 }
35 })
36}
37
38pub fn from_slice<T: serde::de::DeserializeOwned>(slice: &[u8]) -> Result<T, DecodeError> {
39 #[cfg(feature = "flex")]
40 use flex::from_slice;
41 #[cfg(feature = "json")]
42 use json::from_slice;
43
44 match miniz_oxide::inflate::decompress_to_vec_zlib(slice) {
45 Ok(vec) => from_slice(vec.as_slice()),
46 Err(_) => from_slice(slice),
47 }
48}
49
50#[allow(dead_code)]
51#[cfg(feature = "flex")]
52mod flex {
53 use flexbuffers::{DeserializationError, SerializationError};
54
55 #[derive(Debug, thiserror::Error)]
56 #[error("{0}")]
57 pub struct DecodeError(DeserializationError);
58
59 #[derive(Debug, thiserror::Error)]
60 #[error("{0}")]
61 pub struct EncodeError(SerializationError);
62
63 #[inline]
64 pub fn to_vec<T: serde::Serialize>(value: &T) -> Result<Vec<u8>, EncodeError> {
65 flexbuffers::to_vec(value).map_err(EncodeError)
66 }
67
68 #[inline]
69 pub fn from_slice<T: serde::de::DeserializeOwned>(slice: &[u8]) -> Result<T, DecodeError> {
70 flexbuffers::from_slice(slice).map_err(DecodeError)
71 }
72}
73
74#[allow(dead_code)]
75#[cfg(feature = "json")]
76mod json {
77 use serde_json::Error;
78
79 #[derive(Debug, thiserror::Error)]
80 #[error("{0}")]
81 pub struct DecodeError(Error);
82
83 #[derive(Debug, thiserror::Error)]
84 #[error("{0}")]
85 pub struct EncodeError(Error);
86
87 #[inline]
88 pub fn to_vec<T: serde::Serialize>(value: &T) -> Result<Vec<u8>, EncodeError> {
89 serde_json::to_vec(value).map_err(EncodeError)
90 }
91
92 #[inline]
93 pub fn from_slice<T: serde::de::DeserializeOwned>(slice: &[u8]) -> Result<T, DecodeError> {
94 serde_json::from_slice(slice).map_err(DecodeError)
95 }
96}