Skip to content

Commit 820010d

Browse files
Andre da Silvaafck
Andre da Silva
authored andcommitted
Serialize BTreeMap with keys as strings (#2668)
## Motivation When we try to save the wallet, the `pending_blobs` inside of `UserChain` will need to be serialized to JSON, but that map is currently a `BlobId`. ## Proposal Write a custom serialization module for BTreeMaps that will serialize the keys as strings Fixes #2665 ## Test Plan CI + stacked #2646 on top of this and ran the benchmark test, it did not fail in the serialization anymore ## Release Plan - Nothing to do / These changes follow the usual release cycle.
1 parent 4497c48 commit 820010d

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

linera-client/src/util.rs

+35
Original file line numberDiff line numberDiff line change
@@ -65,3 +65,38 @@ macro_rules! impl_from_infallible {
6565

6666
pub(crate) use impl_from_dynamic;
6767
pub(crate) use impl_from_infallible;
68+
69+
pub mod serde_btreemap_keys_as_strings {
70+
use std::{collections::BTreeMap, fmt::Display, str::FromStr};
71+
72+
use serde::{self, Deserialize, Deserializer, Serialize, Serializer};
73+
74+
pub fn serialize<K, V, S>(map: &BTreeMap<K, V>, serializer: S) -> Result<S::Ok, S::Error>
75+
where
76+
K: Display,
77+
V: Serialize,
78+
S: Serializer,
79+
{
80+
let string_map: BTreeMap<String, &V> =
81+
map.iter().map(|(k, v)| (k.to_string(), v)).collect();
82+
string_map.serialize(serializer)
83+
}
84+
85+
pub fn deserialize<'de, K, V, D>(deserializer: D) -> Result<BTreeMap<K, V>, D::Error>
86+
where
87+
K: FromStr + Ord,
88+
<K as FromStr>::Err: Display,
89+
V: Deserialize<'de>,
90+
D: Deserializer<'de>,
91+
{
92+
let string_map: BTreeMap<String, V> = BTreeMap::deserialize(deserializer)?;
93+
string_map
94+
.into_iter()
95+
.map(|(k, v)| {
96+
k.parse()
97+
.map(|key| (key, v))
98+
.map_err(serde::de::Error::custom)
99+
})
100+
.collect()
101+
}
102+
}

linera-client/src/wallet.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use linera_storage::Storage;
1818
use rand::Rng as _;
1919
use serde::{Deserialize, Serialize};
2020

21-
use crate::{config::GenesisConfig, error, Error};
21+
use crate::{config::GenesisConfig, error, util::serde_btreemap_keys_as_strings, Error};
2222

2323
#[derive(Serialize, Deserialize)]
2424
pub struct Wallet {
@@ -210,6 +210,7 @@ pub struct UserChain {
210210
pub timestamp: Timestamp,
211211
pub next_block_height: BlockHeight,
212212
pub pending_block: Option<Block>,
213+
#[serde(with = "serde_btreemap_keys_as_strings")]
213214
pub pending_blobs: BTreeMap<BlobId, Blob>,
214215
}
215216

0 commit comments

Comments
 (0)