Skip to content

Commit

Permalink
Add impl Bake for HashMap (#4295)
Browse files Browse the repository at this point in the history
Fixes #4266
  • Loading branch information
robertbastian authored Nov 15, 2023
1 parent 933a33e commit 0e307c1
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
- CLI: Fix behavior of `--segmenter-lstm-root` such that it does not override `icuexportdata-root` (https://github.com/unicode-org/icu4x/pull/4277)
- Utilities
- `databake`
- Add implementations for `BTreeSet`, `BTreeMap` (https://github.com/unicode-org/icu4x/pull/4268, https://github.com/unicode-org/icu4x/pull/4274)
- 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)
- Improvements to `databake::test_bake!()` (https://github.com/unicode-org/icu4x/pull/4182)
- `litemap`
- Implement `databake::Bake` on `LiteMap` (https://github.com/unicode-org/icu4x/pull/4275)
Expand Down
54 changes: 54 additions & 0 deletions utils/databake/src/alloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,60 @@ fn btree_map() {
);
}

impl<T> Bake for std::collections::HashSet<T>
where
T: Bake,
{
fn bake(&self, ctx: &CrateEnv) -> TokenStream {
ctx.insert("std");
let mut data = self.iter().map(|d| d.bake(ctx)).collect::<Vec<_>>();
data.sort_unstable_by_key(|data| data.to_string());
quote! {
std::collections::HashSet::from([#(#data),*])
}
}
}

#[test]
fn hash_set() {
test_bake!(
std::collections::HashSet<u8>,
std::collections::HashSet::from([1u8, 2u8]),
std
);
}

impl<K, V> Bake for std::collections::HashMap<K, V>
where
K: Bake,
V: Bake,
{
fn bake(&self, ctx: &CrateEnv) -> TokenStream {
ctx.insert("std");
let mut data = self
.iter()
.map(|(k, v)| {
let k = k.bake(ctx);
let v = v.bake(ctx);
quote!((#k, #v))
})
.collect::<Vec<_>>();
data.sort_unstable_by_key(|data| data.to_string());
quote! {
std::collections::HashMap::from([#(#data),*])
}
}
}

#[test]
fn hash_map() {
test_bake!(
std::collections::HashMap<u8, u8>,
std::collections::HashMap::from([(1u8, 2u8), (2u8, 4u8)]),
std
);
}

impl Bake for String {
fn bake(&self, _: &CrateEnv) -> TokenStream {
quote! {
Expand Down

0 comments on commit 0e307c1

Please sign in to comment.