did_toolkit/
string.rs

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
use anyhow::anyhow;

/// Implements percent-encoding of byte arrays. It is not suggested, despite it's public access,
/// that you use this function. Instead, feed the byte array directly to the member data for the
/// type you wish to have encoded, it will do it automatically on output.
///
/// Encode portions of the URL according to <https://www.w3.org/TR/did-core/#did-syntax>
#[inline]
pub fn url_encoded(input: &[u8]) -> String {
    url_encoded_internal(input, true)
}

#[inline]
/// Encode the method_id, which has slightly different rules surrounding the colon.
pub(crate) fn method_id_encoded(input: &[u8]) -> String {
    url_encoded_internal(input, false)
}

#[inline]
fn url_encoded_internal(input: &[u8], escape_colon: bool) -> String {
    let mut ret: Vec<u8> = Vec::new();

    for idx in input {
        match *idx as char {
            '0'..='9' | 'A'..='Z' | 'a'..='z' | '.' | '-' | '_' => ret.push(*idx),
            ':' => {
                if escape_colon {
                    for i in format!("%{:02X}", idx).bytes() {
                        ret.push(i)
                    }
                } else {
                    ret.push(*idx)
                }
            }
            _ => {
                for i in format!("%{:02X}", idx).bytes() {
                    ret.push(i)
                }
            }
        }
    }

    String::from_utf8(ret).unwrap()
}

/// Decode portions of the URL according to <https://www.w3.org/TR/did-core/#did-syntax>
#[inline]
pub(crate) fn url_decoded(s: &[u8]) -> Vec<u8> {
    let mut hexval: u8 = 0;
    let mut hexleft = true;
    let mut ret = Vec::new();
    let mut in_pct = false;

    for idx in s {
        match *idx as char {
            '%' => in_pct = true,
            '0'..='9' | 'a'..='f' | 'A'..='F' => {
                if in_pct {
                    let val: u8 = (*idx as char).to_digit(16).unwrap() as u8;

                    hexval |= if hexleft { val << 4 } else { val };

                    if hexleft {
                        hexleft = false;
                    } else {
                        ret.push(hexval);
                        in_pct = false;
                        hexleft = true;
                        hexval = 0;
                    }
                } else {
                    ret.push(*idx)
                }
            }
            _ => ret.push(*idx),
        }
    }

    ret
}

/// Validate method names fit within the proper ASCII range according to
/// https://www.w3.org/TR/did-core/#did-syntax. Return an error if any characters fall outside of
/// it.
#[inline]
pub(crate) fn validate_method_name(s: &[u8]) -> Result<(), anyhow::Error> {
    for idx in s {
        if !(&0x61..=&0x7a).contains(&idx) && !('0'..='9').contains(&(*idx as char)) {
            return Err(anyhow!(
                "Method name has invalid characters (not in 0x61 - 0x7a)"
            ));
        }
    }

    Ok(())
}

mod tests {
    #[test]
    fn test_encode_decode() {
        let encoded = super::url_encoded("text with spaces".as_bytes());
        assert_eq!(encoded, String::from("text%20with%20spaces"));
        assert_eq!(
            super::url_decoded(encoded.as_bytes()),
            "text with spaces".as_bytes()
        );
    }

    #[test]
    fn test_battery_encode() {
        use rand::Fill;

        let mut rng = rand::thread_rng();

        for _ in 1..100000 {
            let mut array: [u8; 100] = [0; 100];
            array.try_fill(&mut rng).unwrap();
            let encoded = super::url_encoded(&array);
            assert_eq!(super::url_decoded(encoded.as_bytes()), array, "{}", encoded);
        }
    }

    #[test]
    fn test_validate_method_name() {
        assert!(super::validate_method_name("erik".as_bytes()).is_ok());
        assert!(super::validate_method_name("not valid".as_bytes()).is_err());
    }
}