bincode_json/
lib.rs

1//! `bincode-json` is a wrapper around `bincode` to encode/decode JSON-like objects.
2//!
3//! ## Features
4//!  - `json`: enables converting from/to `serde_json::Value`.
5
6pub mod de;
7pub mod error;
8pub mod ser;
9pub mod value;
10
11pub use error::{Error, Result};
12pub use value::Value;
13
14use serde::{de::DeserializeOwned, Serialize};
15
16/// Interpret a [Value] as an instance of type `T`.
17pub fn from_value<T: DeserializeOwned>(val: Value) -> Result<T> {
18    T::deserialize(de::Deserializer::from(val))
19}
20
21/// Convert a `T` into [Value].
22pub fn to_value<T: Serialize>(val: &T) -> Result<Value> {
23    val.serialize(ser::Serializer::new())
24}
25
26/// Serialize the given data structure as a byte vector.
27pub fn to_vec<T: Serialize>(val: &T) -> Result<Vec<u8>> {
28    let value = to_value(val)?;
29    Ok(bincode::encode_to_vec(value, bincode::config::standard())?)
30}
31
32/// Deserialize an instance of type `T` from bytes of Bincode JSON.
33pub fn from_slice<T: DeserializeOwned>(val: &[u8]) -> Result<T> {
34    let (value, _) = bincode::decode_from_slice(val, bincode::config::standard())?;
35    from_value(value)
36}