prefix_hex/
data.rs

1// Copyright 2022 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4use alloc::{boxed::Box, format, string::String, vec::Vec};
5
6use crate::{strip_prefix, Error, FromHexPrefixed, ToHexPrefixed};
7
8impl FromHexPrefixed for Vec<u8> {
9    fn from_hex_prefixed(hex: impl AsRef<str>) -> Result<Self, Error> {
10        let hex = strip_prefix(hex.as_ref())?;
11        hex::decode(hex).map_err(Into::into)
12    }
13}
14
15impl FromHexPrefixed for Box<[u8]> {
16    fn from_hex_prefixed(hex: impl AsRef<str>) -> Result<Self, Error> {
17        let hex = strip_prefix(hex.as_ref())?;
18        hex::decode(hex).map(Vec::into_boxed_slice).map_err(Into::into)
19    }
20}
21
22impl<const N: usize> FromHexPrefixed for [u8; N]
23where
24    Self: hex::FromHex,
25{
26    fn from_hex_prefixed(hex: impl AsRef<str>) -> Result<Self, Error> {
27        let hex = strip_prefix(hex.as_ref())?;
28        let mut buffer = [0; N];
29        hex::decode_to_slice(hex, &mut buffer).map_err(|e| match e {
30            hex::FromHexError::InvalidStringLength | hex::FromHexError::OddLength => Error::InvalidStringLengthSlice {
31                expected: N * 2,
32                actual: hex.len(),
33            },
34            _ => e.into(),
35        })?;
36        Ok(buffer)
37    }
38}
39
40impl<const N: usize> ToHexPrefixed for [u8; N]
41where
42    Self: hex::ToHex,
43{
44    fn to_hex_prefixed(self) -> String {
45        format!("0x{}", hex::encode(self))
46    }
47}
48
49impl<const N: usize> ToHexPrefixed for &[u8; N]
50where
51    [u8; N]: hex::ToHex,
52{
53    fn to_hex_prefixed(self) -> String {
54        format!("0x{}", hex::encode(self))
55    }
56}
57
58macro_rules! impl_to_hex {
59    ($type:ty) => {
60        impl ToHexPrefixed for $type {
61            fn to_hex_prefixed(self) -> String {
62                format!("0x{}", hex::encode(self))
63            }
64        }
65    };
66}
67
68impl_to_hex!(Box<[u8]>);
69impl_to_hex!(&Box<[u8]>);
70impl_to_hex!(&[u8]);
71impl_to_hex!(Vec<u8>);
72impl_to_hex!(&Vec<u8>);