1
0
Fork 0

Update serde_aux for fix in vityafx/serde-aux#26

gh-action
Bo Jeanes 2022-09-06 08:50:56 +10:00
parent 8d7ee31a73
commit f87fcec1cf
2 changed files with 9 additions and 45 deletions

4
Cargo.lock generated
View File

@ -1174,9 +1174,9 @@ dependencies = [
[[package]] [[package]]
name = "serde-aux" name = "serde-aux"
version = "3.1.0" version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0a77223b653fa95f3f9864f3eb25b93e4ed170687eb42d85b6b98af21d5e1de" checksum = "730ba304b6ac130bf8aafc51b048f00431ef37601ab2b483a8e01e4f172ef2fb"
dependencies = [ dependencies = [
"chrono", "chrono",
"serde", "serde",

View File

@ -523,29 +523,18 @@ impl From<SungrowResult> for Result<()> {
// //
// Modbus uses u16 "words" instead of bytes, and the data above should always represent this, so we can take groups // Modbus uses u16 "words" instead of bytes, and the data above should always represent this, so we can take groups
// of 2 and consume them as a hex-represented u16. // of 2 and consume them as a hex-represented u16.
//
// TODO: can be simpler once https://github.com/vityafx/serde-aux/issues/26 is resolved
fn words_from_string<'de, D>(deserializer: D) -> std::result::Result<Vec<u16>, D::Error> fn words_from_string<'de, D>(deserializer: D) -> std::result::Result<Vec<u16>, D::Error>
where where
D: serde::Deserializer<'de>, D: serde::Deserializer<'de>,
{ {
StringOrVecToVec::with_separator(' ').into_deserializer()(deserializer).map( StringOrVecToVec::new(' ', |s| u8::from_str_radix(s, 16), true).into_deserializer()(
|vec: Vec<String>| { deserializer,
vec.chunks_exact(2)
.map(|chunk| {
let bytes: [u8; 2] = chunk
.iter()
.map(|byte_str| {
u8::from_str_radix(byte_str, 16).expect("API shouldn't return bad hex")
})
.collect::<Vec<u8>>()
.try_into()
.expect("we always have two elements, because of `chunks_exact`");
u16::from_be_bytes(bytes)
})
.collect::<Vec<u16>>()
},
) )
.map(|vec| {
vec.chunks_exact(2)
.map(|bytes| u16::from_be_bytes(bytes.try_into().unwrap()))
.collect()
})
} }
#[test] #[test]
@ -563,28 +552,3 @@ fn test_words_from_string() {
&[0x00AA, 0x0001, 0x000D, 0x001E, 0x000F, 0x0000, 0x0055] &[0x00AA, 0x0001, 0x000D, 0x001E, 0x000F, 0x0000, 0x0055]
); );
} }
#[test]
#[ignore] // For a bug report in serde_aux: https://github.com/vityafx/serde-aux/issues/26
fn test_bytes_from_string() {
fn bytes_from_string<'de, D>(deserializer: D) -> std::result::Result<Vec<u8>, D::Error>
where
D: serde::Deserializer<'de>,
{
StringOrVecToVec::new(' ', |s| {
println!("{:?}", &s);
u8::from_str_radix(s, 16)
})
.into_deserializer()(deserializer)
}
#[derive(serde::Deserialize, Debug)]
struct MyStruct {
#[serde(deserialize_with = "bytes_from_string")]
list: Vec<u8>,
}
let s = r#" { "list": "a1 b2 c3 d4 " } "#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert_eq!(&a.list, &[0xa1, 0xb2, 0xc3, 0xd4]);
}