Skip to content

Commit

Permalink
Merge pull request #55 from CosmWasm/fix-collect_str
Browse files Browse the repository at this point in the history
Test collect_str and let it use the default implementation
  • Loading branch information
webmaster128 authored Apr 11, 2023
2 parents e0f5cc4 + d92b365 commit 1c0fdbb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 8 deletions.
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ project adheres to [Semantic Versioning](http://semver.org/).

### Added

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

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

## [0.5.0] - 2022-12-06

Expand Down
34 changes: 27 additions & 7 deletions src/ser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -428,13 +428,6 @@ impl<'a> ser::Serializer for &'a mut Serializer {
self.buf.push(b':');
self.serialize_struct(name, len)
}

fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok>
where
T: fmt::Display,
{
self.serialize_str(&value.to_string())
}
}

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

use super::to_string;
use serde::{Serialize, Serializer};
use serde_derive::{Deserialize, Serialize};

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

#[test]
fn collect_str_can_be_used_in_custom_seralize_impl() {
struct SpecialType {
count: u32,
on: bool,
}

impl Serialize for SpecialType {
// A custom Serialize implementation for SpecialType. SpecialType is giving us the chance to use
// an efficient collect_str implementation that is better than allocating the String and running
// serialize_str on it.
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.collect_str(&format_args!("{}-{}", self.count, self.on))
}
}

let value = SpecialType {
count: 123,
on: false,
};
assert_eq!(to_string(&value).unwrap(), r#""123-false""#);
}

#[test]
fn newtype() {
#[derive(Serialize)]
Expand Down

0 comments on commit 1c0fdbb

Please sign in to comment.