I can't seem to get the right trait bound on a generic wrapper struct for serde serialize.
I wanted to write a wrapper struct which would just call serialize map (without having to put things in a btreemap or hashmap). I accomplished this, but I'm not able to use my wrapper struct on all the types I would like.
Any ideas for how to change the bound on the impl block so that the struct can be used as seen in using_newtype_shared and using_newtype_owned.
//
// [package]
// name = "serialize-benchmark"
// version = "0.1.0"
// edition = "2021"
//
// [dependencies]
// serde = { version = "1.0.204", features = ["derive"] }
// serde_json = "1.0.120"
//
// [dev-dependencies]
// divan = "0.1.14"
//
// [[bench]]
// name = "bench"
// harness = false
//
//
// in benches/bench.rs
use divan::main;
struct SerializeAsMap<I>(I);
impl<I, K, V> serde::Serialize for SerializeAsMap<I>
where
I: IntoIterator<Item = (K, V)> + Copy, // not a fan of having to have the copy bound here
K: serde::Serialize,
V: serde::Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.collect_map(self.0)
}
}
#[divan::bench]
fn using_newtype_owned() -> String {
let a = std::hint::black_box("asdf");
let x = [("a", a)];
let y = SerializeAsMap(x);
serde_json::to_string(&y).unwrap()
}
#[divan::bench]
fn using_newtype_shared() -> String {
let a = std::hint::black_box("asdf");
let x = [("a", a)];
let y = SerializeAsMap(&x);
serde_json::to_string(&y).unwrap() // this doesn't compile
}
#[divan::bench]
fn using_serde_json() -> String {
let a = std::hint::black_box("asdf");
let x = serde_json::json!({"a": a});
serde_json::to_string(&x).unwrap()
}
#[divan::bench]
fn using_hashmap() -> String {
let a = std::hint::black_box("asdf");
let x = std::collections::HashMap::from([("a", a)]);
serde_json::to_string(&x).unwrap()
}
$ cargo bench
Running benches/bench.rs (target/release/deps/bench-ab596dc39b16c93b)
Timer precision: 15 ns
bench fastest โ slowest โ median โ mean โ samples โ iters
โโ using_hashmap 69.65 ns โ 664.3 ns โ 71.82 ns โ 106.6 ns โ 100 โ 3200
โโ using_newtype_owned 34.86 ns โ 3.905 ยตs โ 43.54 ns โ 96.31 ns โ 100 โ 3200
โฐโ using_serde_json 129.7 ns โ 1.55 ยตs โ 138.7 ns โ 156.1 ns โ 100 โ 100