workflow_core/
hex.rs

1//! Hex serialization traits
2
3use serde::{Deserialize, Deserializer, Serializer};
4use std::str;
5
6pub trait ToHex {
7    fn to_hex(&self) -> String;
8}
9
10pub fn serialize<S, T>(this: T, serializer: S) -> Result<S::Ok, S::Error>
11where
12    S: Serializer,
13    T: ToHex,
14{
15    let hex = this.to_hex();
16    serializer.serialize_str(&hex)
17}
18
19pub trait FromHex: Sized {
20    type Error: std::fmt::Display;
21    fn from_hex(hex_str: &str) -> Result<Self, Self::Error>;
22}
23
24pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
25where
26    D: Deserializer<'de>,
27    T: FromHex,
28{
29    use serde::de::Error;
30    let buff: &[u8] = Deserialize::deserialize(deserializer)?;
31    T::from_hex(str::from_utf8(buff).unwrap()).map_err(D::Error::custom)
32}
33
34/// Little endian format of full slice content
35/// (so string lengths are always even).
36impl ToHex for &[u8] {
37    fn to_hex(&self) -> String {
38        // an empty vector is allowed
39        if self.is_empty() {
40            return "".to_string();
41        }
42
43        let mut hex = vec![0u8; self.len() * 2];
44        faster_hex::hex_encode(self, hex.as_mut_slice())
45            .expect("The output is exactly twice the size of the input");
46        let result = unsafe { str::from_utf8_unchecked(&hex) };
47        result.to_string()
48    }
49}
50
51/// Little endian format of full content
52/// (so string lengths are always even).
53impl ToHex for Vec<u8> {
54    fn to_hex(&self) -> String {
55        (&**self).to_hex()
56    }
57}
58
59/// Little endian format of full content
60/// (so string lengths must be even).
61impl FromHex for Vec<u8> {
62    type Error = faster_hex::Error;
63    fn from_hex(hex_str: &str) -> Result<Self, Self::Error> {
64        // an empty string is allowed
65        if hex_str.is_empty() {
66            return Ok(vec![]);
67        }
68
69        let mut bytes = vec![0u8; hex_str.len() / 2];
70        faster_hex::hex_decode(hex_str.as_bytes(), bytes.as_mut_slice())?;
71        Ok(bytes)
72    }
73}