Skip to content

Commit 064d4f5

Browse files
Andre da Silvama2bd
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 dbbfd59 commit 064d4f5

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
@@ -66,3 +66,38 @@ macro_rules! impl_from_infallible {
6666

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

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)