Skip to main content

hashiverse_lib/tools/
json.rs

1//! # Thin JSON (de)serialisation helpers
2//!
3//! Four trivial wrappers over `serde_json` that return `anyhow::Result` and either
4//! `Bytes` or `String`. The point is consistency: every caller in the codebase goes
5//! through these helpers instead of sprinkling `serde_json::to_vec` / `from_slice`
6//! calls, so error handling and encoding choices stay uniform.
7//!
8//! JSON is used for the rare human-readable persisted blobs (configuration, on-disk
9//! key locker entries). Wire-format payloads go through the hand-rolled binary
10//! encoders in [`crate::protocol`] instead.
11
12use bytes::Bytes;
13use serde::{Serialize, de::DeserializeOwned};
14
15pub fn bytes_to_struct<T: DeserializeOwned>(bytes: &[u8]) -> anyhow::Result<T> {
16    let v = serde_json::from_slice(bytes)?;
17    Ok(v)
18}
19
20pub fn struct_to_bytes<T: Serialize>(v: &T) -> anyhow::Result<Bytes> {
21    let bytes = serde_json::to_vec(v)?;
22    Ok(Bytes::from(bytes))
23}
24
25pub fn string_to_struct<T: DeserializeOwned>(str: &str) -> anyhow::Result<T> {
26    let v = serde_json::from_str(str)?;
27    Ok(v)
28}
29
30pub fn struct_to_string<T: Serialize>(v: &T) -> anyhow::Result<String> {
31    let str = serde_json::to_string(v)?;
32    Ok(str)
33}