Skip to content

Commit 0e307c1

Browse files
Add impl Bake for HashMap (#4295)
Fixes #4266
1 parent 933a33e commit 0e307c1

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

CHANGELOG.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
- CLI: Fix behavior of `--segmenter-lstm-root` such that it does not override `icuexportdata-root` (https://github.com/unicode-org/icu4x/pull/4277)
3131
- Utilities
3232
- `databake`
33-
- Add implementations for `BTreeSet`, `BTreeMap` (https://github.com/unicode-org/icu4x/pull/4268, https://github.com/unicode-org/icu4x/pull/4274)
33+
- Add implementations for `HashSet`, `HashMap`, `BTreeSet`, `BTreeMap` (https://github.com/unicode-org/icu4x/pull/4268, https://github.com/unicode-org/icu4x/pull/4274, https://github.com/unicode-org/icu4x/pull/4295)
3434
- Improvements to `databake::test_bake!()` (https://github.com/unicode-org/icu4x/pull/4182)
3535
- `litemap`
3636
- Implement `databake::Bake` on `LiteMap` (https://github.com/unicode-org/icu4x/pull/4275)

utils/databake/src/alloc.rs

+54
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,60 @@ fn btree_map() {
106106
);
107107
}
108108

109+
impl<T> Bake for std::collections::HashSet<T>
110+
where
111+
T: Bake,
112+
{
113+
fn bake(&self, ctx: &CrateEnv) -> TokenStream {
114+
ctx.insert("std");
115+
let mut data = self.iter().map(|d| d.bake(ctx)).collect::<Vec<_>>();
116+
data.sort_unstable_by_key(|data| data.to_string());
117+
quote! {
118+
std::collections::HashSet::from([#(#data),*])
119+
}
120+
}
121+
}
122+
123+
#[test]
124+
fn hash_set() {
125+
test_bake!(
126+
std::collections::HashSet<u8>,
127+
std::collections::HashSet::from([1u8, 2u8]),
128+
std
129+
);
130+
}
131+
132+
impl<K, V> Bake for std::collections::HashMap<K, V>
133+
where
134+
K: Bake,
135+
V: Bake,
136+
{
137+
fn bake(&self, ctx: &CrateEnv) -> TokenStream {
138+
ctx.insert("std");
139+
let mut data = self
140+
.iter()
141+
.map(|(k, v)| {
142+
let k = k.bake(ctx);
143+
let v = v.bake(ctx);
144+
quote!((#k, #v))
145+
})
146+
.collect::<Vec<_>>();
147+
data.sort_unstable_by_key(|data| data.to_string());
148+
quote! {
149+
std::collections::HashMap::from([#(#data),*])
150+
}
151+
}
152+
}
153+
154+
#[test]
155+
fn hash_map() {
156+
test_bake!(
157+
std::collections::HashMap<u8, u8>,
158+
std::collections::HashMap::from([(1u8, 2u8), (2u8, 4u8)]),
159+
std
160+
);
161+
}
162+
109163
impl Bake for String {
110164
fn bake(&self, _: &CrateEnv) -> TokenStream {
111165
quote! {

0 commit comments

Comments
 (0)