Skip to content

Commit 20ec78c

Browse files
rfaelru
andauthored
serialize_bytes is not unreachable now (#51)
* serialize_bytes is not unreachable now * serialize bytes test added * test_serialize_bytes fustfmt fixed * changelog updated Co-authored-by: ru <[email protected]>
1 parent c3460e6 commit 20ec78c

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
99
### Changed
1010
- Floating point numbers terminated by EOF may now be deserialized
1111
- [ryu](https://github.com/dtolnay/ryu) is used to serialize `f32` and `f64`
12+
- Added missing implementation for `serialize_bytes` method
1213

1314
## [v0.2.0] - 2020-12-11
1415
### Added

src/ser/mod.rs

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -304,8 +304,8 @@ impl<'a, 'b: 'a> ser::Serializer for &'a mut Serializer<'b> {
304304
self.push(b'"')
305305
}
306306

307-
fn serialize_bytes(self, _v: &[u8]) -> Result<Self::Ok> {
308-
unreachable!()
307+
fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok> {
308+
self.extend_from_slice(v)
309309
}
310310

311311
fn serialize_none(self) -> Result<Self::Ok> {
@@ -795,4 +795,32 @@ mod tests {
795795
r#"{"A":{"x":54,"y":720}}"#
796796
);
797797
}
798+
799+
#[test]
800+
fn test_serialize_bytes() {
801+
use core::fmt::Write;
802+
use heapless::{consts::U48, String};
803+
804+
pub struct SimpleDecimal(f32);
805+
806+
impl serde::Serialize for SimpleDecimal {
807+
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
808+
where
809+
S: serde::Serializer,
810+
{
811+
let mut aux: String<U48> = String::new();
812+
write!(aux, "{:.2}", self.0).unwrap();
813+
serializer.serialize_bytes(&aux.as_bytes())
814+
}
815+
}
816+
817+
let sd1 = SimpleDecimal(1.55555);
818+
assert_eq!(&*crate::to_string::<N, _>(&sd1).unwrap(), r#"1.56"#);
819+
820+
let sd2 = SimpleDecimal(0.000);
821+
assert_eq!(&*crate::to_string::<N, _>(&sd2).unwrap(), r#"0.00"#);
822+
823+
let sd3 = SimpleDecimal(22222.777777);
824+
assert_eq!(&*crate::to_string::<N, _>(&sd3).unwrap(), r#"22222.78"#);
825+
}
798826
}

0 commit comments

Comments
 (0)