macro_toolset/string_v2/
hex.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
//! Number to Hex string
//!
//! Actually just with [`NumStr`](crate::string_v2::NumStr) you can do so.
//! However for fixed length hex string, [`const_hex`] does better.

use super::{StringExtT, StringT};

#[derive(Debug, Clone)]
/// Hex string with fixed length.
///
/// # Generic
///
/// - N: Length of target buffer, the length of the final string is 2*N (+1 if
///   with prefix).
/// - P: Prefix `0x`, default false
/// - U: Uppercase, default false
///
/// For hex string with non-fixed length, use [`NumStr`](super::NumStr).
pub enum HexStr<'s, const N: usize, const P: bool = false, const U: bool = false> {
    /// Owned
    Owned(Vec<u8>),

    /// Borrowed
    Borrowed(&'s [u8]),
}

impl<'s, const N: usize, const P: bool, const U: bool> HexStr<'s, N, P, U> {
    #[inline]
    /// Create a new hex string from give slice.
    pub const fn new(value: &'s [u8]) -> Self {
        Self::Borrowed(value)
    }

    #[inline]
    /// Create a new hex string from given owned slice.
    pub const fn new_owned(value: Vec<u8>) -> Self {
        Self::Owned(value)
    }

    #[inline]
    /// Set with prefix `0x`
    pub fn set_with_prefix<const NP: bool>(self) -> HexStr<'s, N, NP, U> {
        match self {
            Self::Borrowed(value) => HexStr::Borrowed(value),
            Self::Owned(value) => HexStr::Owned(value),
        }
    }

    #[inline]
    /// Set to uppercase
    pub fn set_uppercase<const NU: bool>(self) -> HexStr<'s, N, P, NU> {
        match self {
            Self::Borrowed(value) => HexStr::Borrowed(value),
            Self::Owned(value) => HexStr::Owned(value),
        }
    }

    #[inline]
    /// Encode to string
    fn encode<T>(&self, string: &mut T)
    where
        T: for<'a> Extend<&'a u8>,
    {
        let mut buffer = [0; N];

        for (idx, &i) in (0..N).rev().zip(
            match self {
                Self::Borrowed(value) => value,
                Self::Owned(value) => value.as_slice(),
            }
            .iter()
            .rev(),
        ) {
            buffer[idx] = i
        }

        if U {
            string.extend(
                const_hex::Buffer::<N, P>::new()
                    .const_format_upper(&buffer)
                    .as_bytes(),
            );
        } else {
            string.extend(
                const_hex::Buffer::<N, P>::new()
                    .const_format(&buffer)
                    .as_bytes(),
            );
        }
    }
}

impl<const N: usize, const P: bool, const U: bool> StringT for HexStr<'_, N, P, U> {
    #[inline]
    fn encode_to_buf(self, string: &mut Vec<u8>) {
        self.encode(string);
    }

    #[inline]
    fn encode_to_buf_with_separator(self, string: &mut Vec<u8>, separator: &str) {
        self.encode(string);
        string.extend(separator.as_bytes());
    }

    #[inline]
    #[cfg(feature = "feat-string-ext-bytes")]
    fn encode_to_bytes_buf(self, string: &mut bytes::BytesMut) {
        self.encode(string);
    }

    #[inline]
    #[cfg(feature = "feat-string-ext-bytes")]
    fn encode_to_bytes_buf_with_separator(self, string: &mut bytes::BytesMut, separator: &str) {
        self.encode(string);
        string.extend(separator.as_bytes());
    }
}

impl<const N: usize, const P: bool, const U: bool> StringExtT for HexStr<'_, N, P, U> {}

impl<const N: usize, const P: bool> StringT for const_hex::Buffer<N, P> {
    #[inline]
    fn encode_to_buf(self, string: &mut Vec<u8>) {
        string.extend(self.as_bytes());
    }

    #[inline]
    fn encode_to_buf_with_separator(self, string: &mut Vec<u8>, separator: &str) {
        string.extend(self.as_bytes());
        string.extend(separator.as_bytes());
    }

    #[inline]
    #[cfg(feature = "feat-string-ext-bytes")]
    fn encode_to_bytes_buf(self, string: &mut bytes::BytesMut) {
        string.extend(self.as_bytes());
    }

    #[inline]
    #[cfg(feature = "feat-string-ext-bytes")]
    fn encode_to_bytes_buf_with_separator(self, string: &mut bytes::BytesMut, separator: &str) {
        string.extend(self.as_bytes());
        string.extend(separator.as_bytes());
    }
}

impl<const N: usize, const P: bool> StringExtT for const_hex::Buffer<N, P> {}

#[cfg(test)]
mod test {
    use crate::string_v2::{HexStr, StringExtT};

    #[test]
    fn test() {
        assert_eq!(
            HexStr::<0>::new(&[0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]).to_string_ext(),
            ""
        );
        assert_eq!(
            HexStr::<7>::new(&[0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]).to_string_ext(),
            "01020304050607"
        );
        assert_eq!(
            HexStr::<8>::new(&[0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]).to_string_ext(),
            "0001020304050607"
        );
        assert_eq!(
            HexStr::<9>::new(&[0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]).to_string_ext(),
            "000001020304050607"
        );
    }

    #[test]
    fn test_with_prefix() {
        assert_eq!(
            HexStr::<0>::new(&[0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07])
                .set_with_prefix::<true>()
                .to_string_ext(),
            "0x"
        );
        assert_eq!(
            HexStr::<7>::new(&[0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07])
                .set_with_prefix::<true>()
                .to_string_ext(),
            "0x01020304050607"
        );
        assert_eq!(
            HexStr::<8>::new(&[0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07])
                .set_with_prefix::<true>()
                .to_string_ext(),
            "0x0001020304050607"
        );
        assert_eq!(
            HexStr::<9>::new(&[0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07])
                .set_with_prefix::<true>()
                .to_string_ext(),
            "0x000001020304050607"
        );
    }

    #[test]
    fn test_uppcase() {
        assert_eq!(
            HexStr::<7>::new(&[0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0xa7])
                .set_with_prefix::<true>()
                .set_uppercase::<true>()
                .to_string_ext(),
            "0x010203040506A7"
        );
        assert_eq!(
            HexStr::<8>::new(&[0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0xa7])
                .set_with_prefix::<true>()
                .set_uppercase::<true>()
                .to_string_ext(),
            "0x00010203040506A7"
        );
        assert_eq!(
            HexStr::<9>::new(&[0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0xa7])
                .set_with_prefix::<true>()
                .set_uppercase::<true>()
                .to_string_ext(),
            "0x0000010203040506A7"
        );
    }
}