Unverified Commit eed4a13d authored by Andrew Jones's avatar Andrew Jones Committed by GitHub
Browse files

[metadata] add 0x prefix to hex string if not present (#522)

* Add 0x prefix if missing

* Fmt
parent 1765a49f
Pipeline #110775 failed with stages
in 5 minutes and 13 seconds
......@@ -17,7 +17,10 @@ mod tests;
use crate::{
serde_hex,
utils::serialize_as_byte_str,
utils::{
deserialize_from_byte_str,
serialize_as_byte_str,
},
};
use derive_more::From;
use ink_prelude::collections::btree_map::BTreeMap;
......@@ -265,13 +268,13 @@ pub struct HashingStrategy {
/// An optional prefix to the computed hash.
#[serde(
serialize_with = "serialize_as_byte_str",
deserialize_with = "serde_hex::deserialize"
deserialize_with = "deserialize_from_byte_str"
)]
prefix: Vec<u8>,
/// An optional postfix to the computed hash.
#[serde(
serialize_with = "serialize_as_byte_str",
deserialize_with = "serde_hex::deserialize"
deserialize_with = "deserialize_from_byte_str"
)]
postfix: Vec<u8>,
}
......
......@@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::serde_hex;
/// Serializes the given bytes as byte string.
pub fn serialize_as_byte_str<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
where
......@@ -21,5 +23,36 @@ where
// Return empty string without prepended `0x`.
return serializer.serialize_str("")
}
crate::serde_hex::serialize(bytes, serializer)
serde_hex::serialize(bytes, serializer)
}
/// Deserializes the given hex string with optional `0x` prefix.
pub fn deserialize_from_byte_str<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
where
D: serde::Deserializer<'de>,
{
struct Visitor;
impl<'b> serde::de::Visitor<'b> for Visitor {
type Value = Vec<u8>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(formatter, "hex string with optional 0x prefix")
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
let result = if v.starts_with("0x") {
serde_hex::from_hex(v)
} else {
serde_hex::from_hex(&format!("0x{}", v))
};
result.map_err(E::custom)
}
fn visit_string<E: serde::de::Error>(self, v: String) -> Result<Self::Value, E> {
self.visit_str(&v)
}
}
deserializer.deserialize_str(Visitor)
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment