Skip to content

Commit 1c0fdbb

Browse files
authored
Merge pull request #55 from CosmWasm/fix-collect_str
Test collect_str and let it use the default implementation
2 parents e0f5cc4 + d92b365 commit 1c0fdbb

File tree

2 files changed

+30
-8
lines changed

2 files changed

+30
-8
lines changed

CHANGELOG.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,10 @@ project adheres to [Semantic Versioning](http://semver.org/).
99

1010
### Added
1111

12-
- Add support for `str_collect` serialization.
12+
- Add support for `collect_str` serialization ([#51], [#55]).
1313

14+
[#51]: https://github.com/CosmWasm/serde-json-wasm/pull/51
15+
[#55]: https://github.com/CosmWasm/serde-json-wasm/pull/55
1416

1517
## [0.5.0] - 2022-12-06
1618

src/ser/mod.rs

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -428,13 +428,6 @@ impl<'a> ser::Serializer for &'a mut Serializer {
428428
self.buf.push(b':');
429429
self.serialize_struct(name, len)
430430
}
431-
432-
fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok>
433-
where
434-
T: fmt::Display,
435-
{
436-
self.serialize_str(&value.to_string())
437-
}
438431
}
439432

440433
/// Serializes the given data structure as a string of JSON text
@@ -539,6 +532,7 @@ impl ser::SerializeStructVariant for Unreachable {
539532
mod tests {
540533

541534
use super::to_string;
535+
use serde::{Serialize, Serializer};
542536
use serde_derive::{Deserialize, Serialize};
543537

544538
#[test]
@@ -869,6 +863,32 @@ mod tests {
869863
assert_eq!(to_string(" \u{001f} ").unwrap(), r#"" \u001F ""#);
870864
}
871865

866+
#[test]
867+
fn collect_str_can_be_used_in_custom_seralize_impl() {
868+
struct SpecialType {
869+
count: u32,
870+
on: bool,
871+
}
872+
873+
impl Serialize for SpecialType {
874+
// A custom Serialize implementation for SpecialType. SpecialType is giving us the chance to use
875+
// an efficient collect_str implementation that is better than allocating the String and running
876+
// serialize_str on it.
877+
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
878+
where
879+
S: Serializer,
880+
{
881+
serializer.collect_str(&format_args!("{}-{}", self.count, self.on))
882+
}
883+
}
884+
885+
let value = SpecialType {
886+
count: 123,
887+
on: false,
888+
};
889+
assert_eq!(to_string(&value).unwrap(), r#""123-false""#);
890+
}
891+
872892
#[test]
873893
fn newtype() {
874894
#[derive(Serialize)]

0 commit comments

Comments
 (0)