askar_crypto/buffer/
string.rs

1use core::fmt::{self, Debug, Display, Formatter, Write};
2
3/// A utility type used to print or serialize a byte string as hex
4#[derive(Debug)]
5pub struct HexRepr<B>(pub B);
6
7impl<B: AsRef<[u8]>> Display for HexRepr<B> {
8    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
9        for c in self.0.as_ref() {
10            f.write_fmt(format_args!("{:02x}", c))?;
11        }
12        Ok(())
13    }
14}
15
16// Compare to another hex value as [u8]
17impl<B: AsRef<[u8]>> PartialEq<[u8]> for HexRepr<B> {
18    fn eq(&self, other: &[u8]) -> bool {
19        struct CmpWrite<'s>(::core::slice::Iter<'s, u8>);
20
21        impl Write for CmpWrite<'_> {
22            fn write_str(&mut self, s: &str) -> fmt::Result {
23                for c in s.as_bytes() {
24                    if self.0.next() != Some(c) {
25                        return Err(fmt::Error);
26                    }
27                }
28                Ok(())
29            }
30        }
31
32        write!(&mut CmpWrite(other.iter()), "{}", self).is_ok()
33    }
34}
35
36impl<B: AsRef<[u8]>> PartialEq<&str> for HexRepr<B> {
37    fn eq(&self, other: &&str) -> bool {
38        self == other.as_bytes()
39    }
40}
41
42/// A utility type for debug printing of byte strings
43pub struct MaybeStr<'a>(pub &'a [u8]);
44
45impl Debug for MaybeStr<'_> {
46    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
47        if let Ok(sval) = core::str::from_utf8(self.0) {
48            write!(f, "{:?}", sval)
49        } else {
50            write!(f, "<{}>", HexRepr(self.0))
51        }
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn hex_repr_output() {
61        assert_eq!(format!("{}", HexRepr(&[])), "");
62        assert_eq!(format!("{}", HexRepr(&[255, 0, 255, 0])), "ff00ff00");
63    }
64
65    #[test]
66    fn hex_repr_cmp() {
67        assert_eq!(HexRepr(&[0, 255, 0, 255]), "00ff00ff");
68        assert_ne!(HexRepr(&[100, 101, 102]), "00ff00ff");
69    }
70
71    #[test]
72    fn maybe_str_output() {
73        assert_eq!(format!("{:?}", MaybeStr(&[])), "\"\"");
74        assert_eq!(format!("{:?}", MaybeStr(&[255, 0])), "<ff00>");
75    }
76}