serde-rs / serde

Serialization framework for Rust
https://serde.rs/
Apache License 2.0
8.82k stars 748 forks source link

Add support for `write!` macro to `Serializer` #2689

Closed nyurik closed 1 month ago

nyurik commented 5 months ago

The write!($dst, $args+) macro wraps a call to $dst.write_fmt(format_args!($($arg)*)) - making it ergonomic to use formatted output on anything "writable" -- write!(dst, "foo={foo}"). It seems serde does not support write! because it does not have write_fmt, even though it has almost identical collect_str. Even its documentation implies similar usage pattern.

Would it be possible to add another write_fmt fn to the Serializer to make this usecase easier? In theory, if collect_str was called write_fmt, it would have worked out of the box, so a default Trait impl to simply forward the call should be possible?

dtolnay commented 1 month ago

I would prefer not to build support for this into Serializer. It would be extremely unusual for a write_fmt method to consume ownership of $dst. Ordinarily they operate on &mut self.

But you can use serializer.collect_str(&format_args!(...)) instead to accomplish behavior that is equivalent.