Skip to content

Commit

Permalink
Merge pull request #58 from Luro02/const_generics
Browse files Browse the repository at this point in the history
Use const-generics to implement FromHex trait
  • Loading branch information
KokaKiwi committed Nov 19, 2024
2 parents 6dca9ce + ba43579 commit 765de1d
Showing 1 changed file with 7 additions and 36 deletions.
43 changes: 7 additions & 36 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,44 +196,15 @@ impl FromHex for Vec<u8> {
}
}

// Helper macro to implement the trait for a few fixed sized arrays. Once Rust
// has type level integers, this should be removed.
macro_rules! from_hex_array_impl {
($($len:expr)+) => {$(
impl FromHex for [u8; $len] {
type Error = FromHexError;

fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
let mut out = [0_u8; $len];
decode_to_slice(hex, &mut out as &mut [u8])?;
Ok(out)
}
}
)+}
}

from_hex_array_impl! {
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
160 192 200 224 256 384 512 768 1024 2048 4096 8192 16384 32768
}
impl<const N: usize> FromHex for [u8; N] {
type Error = FromHexError;

#[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
from_hex_array_impl! {
65536 131072 262144 524288 1048576 2097152 4194304 8388608
16777216 33554432 67108864 134217728 268435456 536870912
1073741824 2147483648
}
fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
let mut out = [0_u8; N];
decode_to_slice(hex, &mut out as &mut [u8])?;

#[cfg(target_pointer_width = "64")]
from_hex_array_impl! {
4294967296
Ok(out)
}
}

/// Encodes `data` as hex string using lowercase characters.
Expand Down

0 comments on commit 765de1d

Please sign in to comment.