dpp/util/
vec.rs

1use std::num::ParseIntError;
2
3use crate::InvalidVectorSizeError;
4
5fn byte_to_hex(byte: &u8) -> String {
6    format!("{:02x}", byte)
7}
8
9pub fn encode_hex<T: Clone + Into<Vec<u8>>>(bytes: &T) -> String {
10    let hex_vec: Vec<String> = bytes.clone().into().iter().map(byte_to_hex).collect();
11
12    hex_vec.join("")
13}
14
15pub fn decode_hex(s: &str) -> Result<Vec<u8>, ParseIntError> {
16    (0..s.len())
17        .step_by(2)
18        .map(|i| u8::from_str_radix(&s[i..i + 2], 16))
19        .collect()
20}
21
22#[derive(Debug)]
23pub enum DecodeError {
24    ParseIntError(ParseIntError),
25    InvalidVectorSizeError(InvalidVectorSizeError),
26}
27
28impl From<InvalidVectorSizeError> for DecodeError {
29    fn from(err: InvalidVectorSizeError) -> Self {
30        Self::InvalidVectorSizeError(err)
31    }
32}
33
34impl From<ParseIntError> for DecodeError {
35    fn from(err: ParseIntError) -> Self {
36        Self::ParseIntError(err)
37    }
38}
39
40pub fn decode_hex_bls_sig(s: &str) -> Result<[u8; 96], DecodeError> {
41    hex_to_array::<96>(s)
42}
43
44pub fn decode_hex_sha256(s: &str) -> Result<[u8; 32], DecodeError> {
45    hex_to_array::<32>(s)
46}
47
48pub fn hex_to_array<const N: usize>(s: &str) -> Result<[u8; N], DecodeError> {
49    let vec = decode_hex(s)?;
50    Ok(vec_to_array::<N>(&vec)?)
51}
52
53pub fn vec_to_array<const N: usize>(vec: &[u8]) -> Result<[u8; N], InvalidVectorSizeError> {
54    let mut v: [u8; N] = [0; N];
55    // let mut v: T = T::default();
56    if v.len() != vec.len() {
57        return Err(InvalidVectorSizeError::new(v.len(), vec.len()));
58    }
59    for i in 0..vec.len() {
60        if let Some(n) = vec.get(i) {
61            v[i] = *n;
62        } else {
63            return Err(InvalidVectorSizeError::new(v.len(), vec.len()));
64        }
65    }
66    Ok(v)
67}