From 9e971ae5cf8ea11749bc1500e6955e76cec1a11d Mon Sep 17 00:00:00 2001 From: Yin Guanhao Date: Mon, 4 Sep 2023 18:31:25 +0800 Subject: [PATCH] fix: fix deserializing owned hex string and don't depend on serde derive, and don't export faster_hex_serde_macros --- Cargo.toml | 2 +- src/serde.rs | 22 +++++++++++++++++----- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e666027..143e871 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,7 +17,7 @@ exclude = [ ] [dependencies] -serde = { version = "1.0", optional = true, features = ["derive"]} +serde = { version = "1.0", optional = true } [features] default = ["std", "serde"] diff --git a/src/serde.rs b/src/serde.rs index 49b0f48..eeea577 100644 --- a/src/serde.rs +++ b/src/serde.rs @@ -7,6 +7,7 @@ mod internal { decode::{hex_decode_with_case, CheckCase}, encode::hex_encode_custom, }; + use alloc::borrow::Cow; use serde::{de::Error, Deserializer, Serializer}; use std::iter::FromIterator; @@ -50,16 +51,16 @@ mod internal { D: Deserializer<'de>, T: FromIterator, { - let raw_src: &[u8] = serde::Deserialize::deserialize(deserializer)?; - if with_prefix && (raw_src.len() < 2 || raw_src[0] != b'0' || raw_src[1] != b'x') { + let raw_src: Cow = serde::Deserialize::deserialize(deserializer)?; + if with_prefix && !raw_src.starts_with("0x") { return Err(D::Error::custom("invalid prefix".to_string())); } let src: &[u8] = { if with_prefix { - &raw_src[2..] + raw_src[2..].as_bytes() } else { - raw_src + raw_src.as_bytes() } }; @@ -94,7 +95,6 @@ where } /// Generate module with serde methods -#[macro_export] macro_rules! faster_hex_serde_macros { ($mod_name:ident, $with_pfx:expr, $check_case:expr) => { /// Serialize and deserialize with or without 0x-prefix, @@ -162,6 +162,18 @@ mod tests { bar: Vec, } + #[test] + fn test_deserialize_escaped() { + // 0x03 but escaped. + let x: Simple = serde_json::from_str( + r#"{ + "bar": "\u0030x\u00303" + }"#, + ) + .unwrap(); + assert_eq!(x.bar, b"\x03"); + } + fn _test_simple(src: &str) { let simple = Simple { bar: src.into() }; let result = serde_json::to_string(&simple);