Skip to content

Commit bf916e2

Browse files
committed
primitives - BalancesMap - key to lowercase on Serialization
1 parent 6568ae8 commit bf916e2

File tree

1 file changed

+56
-1
lines changed

1 file changed

+56
-1
lines changed

primitives/src/balances_map.rs

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,60 @@
11
use std::collections::BTreeMap;
22

33
use crate::BigNum;
4+
use std::collections::btree_map::{Entry, Iter, Values};
45

5-
pub type BalancesMap = BTreeMap<String, BigNum>;
6+
use serde::{ser::SerializeMap, Deserialize, Serialize, Serializer};
7+
use std::iter::FromIterator;
8+
9+
type BalancesKey = String;
10+
type BalancesValue = BigNum;
11+
12+
#[serde(transparent)]
13+
#[derive(Clone, Debug, Deserialize, Default)]
14+
pub struct BalancesMap(
15+
#[serde(serialize_with = "serialize_balances_map")] BTreeMap<BalancesKey, BalancesValue>,
16+
);
17+
18+
impl BalancesMap {
19+
pub fn iter(&self) -> Iter<'_, BalancesKey, BalancesValue> {
20+
self.0.iter()
21+
}
22+
23+
pub fn values(&self) -> Values<'_, BalancesKey, BalancesValue> {
24+
self.0.values()
25+
}
26+
27+
pub fn get(&self, key: &BalancesKey) -> Option<&BalancesValue> {
28+
self.0.get(key)
29+
}
30+
31+
pub fn entry(&mut self, key: BalancesKey) -> Entry<'_, BalancesKey, BalancesValue> {
32+
self.0.entry(key)
33+
}
34+
35+
pub fn insert(&mut self, key: BalancesKey, value: BalancesValue) -> Option<BalancesValue> {
36+
self.0.insert(key, value)
37+
}
38+
}
39+
40+
impl FromIterator<(BalancesKey, BalancesValue)> for BalancesMap {
41+
fn from_iter<I: IntoIterator<Item = (BalancesKey, BalancesValue)>>(iter: I) -> Self {
42+
// @TODO: Is there better way to do this?
43+
let btree_map: BTreeMap<BalancesKey, BalancesValue> = iter.into_iter().collect();
44+
45+
BalancesMap(btree_map)
46+
}
47+
}
48+
49+
impl Serialize for BalancesMap {
50+
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
51+
where
52+
S: Serializer,
53+
{
54+
let mut map = serializer.serialize_map(Some(self.0.len()))?;
55+
for (key, big_num) in self.0.iter() {
56+
map.serialize_entry(&key.to_lowercase(), big_num)?;
57+
}
58+
map.end()
59+
}
60+
}

0 commit comments

Comments
 (0)