KokaKiwi / rust-hex

A basic crate to encode values to hexadecimal representation. Originally extracted from rustc-serialize.
https://crates.io/crates/hex
Apache License 2.0
201 stars 55 forks source link

hex::FromHex for Vec<Vec<u8>>? #68

Closed sr-gi closed 2 years ago

sr-gi commented 2 years ago

Is there any way of serializing a Vec<Vec<u8>> into a Vec<T> where each T is a hex encoded string?

Sorry if it has been asked before but I couldn't find any related issue.

KokaKiwi commented 2 years ago

If you mean converting a Vec<String> to a Vec<Vec<u8>> i believe doing something like hex_strings.into_iter().map(|s| hex::decode(s)).collect::<Result<Vec<_>>() would do the trick

sr-gi commented 2 years ago

Sorry, the question was not properly formatted, my bad.

I actually mean doing it the other way around. I have a collection of Vec<u8> that needs to be serialized to a collection of hex encoded Strings, so that's be Vec<Vec<u8>> -> Vec<String>

KokaKiwi commented 2 years ago

Well the answer would be kinda the same, but also the other way around :p

bytes_collection.into_iter().map(hex::encode).collect::<Vec<_>>()
sr-gi commented 2 years ago

I just realised I should have been way more precise with my question.

What I'm aiming for is being able to use it with serde so I can derive the serialization of such a field in a struct.

The issue I'm facing is that the trait is not implement for Vec<Vec<u8>> (hence my question regarding if it was possible) nor can it be implemented externally to hex.

Is the only option to define such a function in my crate and then use #[serde(serialize_with = "path")] in the struct to link it?

sr-gi commented 2 years ago

Is the only option to define such a function in my crate and then use #[serde(serialize_with = "path")] in the struct to link it?

I was able to make it work following this approach, not sure it there is a cleaner way to do it.

pub fn serialize_vec_vec_u8<S>(v: &Vec<Vec<u8>>, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    let mut seq = s.serialize_seq(Some(v.len()))?;
    for element in v.iter() {
        seq.serialize_element(&hex::encode(element))?;
    }
    seq.end()
}