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
use crate::{Error, Signature};
use core::{fmt, str};
impl fmt::LowerHex for Signature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for component in [&self.R, &self.s] {
for byte in component {
write!(f, "{:02x}", byte)?;
}
}
Ok(())
}
}
impl fmt::UpperHex for Signature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for component in [&self.R, &self.s] {
for byte in component {
write!(f, "{:02X}", byte)?;
}
}
Ok(())
}
}
impl str::FromStr for Signature {
type Err = Error;
fn from_str(hex: &str) -> signature::Result<Self> {
if hex.as_bytes().len() != Signature::BYTE_SIZE * 2 {
return Err(Error::new());
}
let mut upper_case = None;
for &byte in hex.as_bytes() {
match byte {
b'0'..=b'9' => (),
b'a'..=b'z' => match upper_case {
Some(true) => return Err(Error::new()),
Some(false) => (),
None => upper_case = Some(false),
},
b'A'..=b'Z' => match upper_case {
Some(true) => (),
Some(false) => return Err(Error::new()),
None => upper_case = Some(true),
},
_ => return Err(Error::new()),
}
}
let mut result = [0u8; Self::BYTE_SIZE];
for (digit, byte) in hex.as_bytes().chunks_exact(2).zip(result.iter_mut()) {
*byte = str::from_utf8(digit)
.ok()
.and_then(|s| u8::from_str_radix(s, 16).ok())
.ok_or_else(Error::new)?;
}
Self::try_from(&result[..])
}
}