jujutsu_lib/
hex_util.rs

1// Copyright 2023 The Jujutsu Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14fn to_reverse_hex_digit(b: u8) -> Option<u8> {
15    let value = match b {
16        b'0'..=b'9' => b - b'0',
17        b'A'..=b'F' => b - b'A' + 10,
18        b'a'..=b'f' => b - b'a' + 10,
19        _ => return None,
20    };
21    Some(b'z' - value)
22}
23
24fn to_forward_hex_digit(b: u8) -> Option<u8> {
25    let value = match b {
26        b'k'..=b'z' => b'z' - b,
27        b'K'..=b'Z' => b'Z' - b,
28        _ => return None,
29    };
30    if value < 10 {
31        Some(b'0' + value)
32    } else {
33        Some(b'a' + value - 10)
34    }
35}
36
37pub fn to_forward_hex(reverse_hex: &str) -> Option<String> {
38    reverse_hex
39        .bytes()
40        .map(|b| to_forward_hex_digit(b).map(char::from))
41        .collect()
42}
43
44pub fn to_reverse_hex(forward_hex: &str) -> Option<String> {
45    forward_hex
46        .bytes()
47        .map(|b| to_reverse_hex_digit(b).map(char::from))
48        .collect()
49}
50
51#[cfg(test)]
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn test_reverse_hex() {
58        // Empty string
59        assert_eq!(to_reverse_hex(""), Some("".to_string()));
60        assert_eq!(to_forward_hex(""), Some("".to_string()));
61
62        // Single digit
63        assert_eq!(to_reverse_hex("0"), Some("z".to_string()));
64        assert_eq!(to_forward_hex("z"), Some("0".to_string()));
65
66        // All digits
67        assert_eq!(
68            to_reverse_hex("0123456789abcdefABCDEF"),
69            Some("zyxwvutsrqponmlkponmlk".to_string())
70        );
71        assert_eq!(
72            to_forward_hex("zyxwvutsrqponmlkPONMLK"),
73            Some("0123456789abcdefabcdef".to_string())
74        );
75
76        // Invalid digit
77        assert_eq!(to_reverse_hex("g"), None);
78        assert_eq!(to_forward_hex("j"), None);
79    }
80}