fashex 0.0.3

Conversion from bytes to hexadecimal string.
Documentation
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#![doc = include_str!("../README.md")]
#![no_std]
#![allow(clippy::inline_always, reason = "XXX")]
#![cfg_attr(feature = "portable-simd", feature(portable_simd))]
#![cfg_attr(
    all(feature = "experimental-loongarch64-simd", target_arch = "loongarch64"),
    feature(stdarch_loongarch)
)]

#[cfg(any(test, feature = "alloc"))]
extern crate alloc;

#[cfg(any(test, feature = "std"))]
extern crate std;

mod backend;
pub mod error;
#[cfg(feature = "fuzz")]
pub mod fuzz;
pub mod util;

use core::mem::MaybeUninit;

use crate::error::InvalidInput;

/// Encodes the input bytes to hexadecimal string and writes it to the output
/// buffer.
///
/// ## Examples
///
/// ```rust
/// use core::mem::MaybeUninit;
///
/// let input = b"Hello, world!";
/// let mut output = vec![MaybeUninit::<u8>::uninit(); input.len() * 2];
///
/// fashex::encode::<false>(input, &mut output).expect("infallible: the length must be valid");
///
/// #[allow(
///     unsafe_code,
///     reason = "We have encoded the input to hexadecimal string"
/// )]
/// let output = unsafe { output.assume_init_ref() };
///
/// assert_eq!(output, b"48656c6c6f2c20776f726c6421");
///
/// let mut output = vec![MaybeUninit::<u8>::uninit(); input.len() * 2];
///
/// fashex::encode::<true>(input, &mut output).expect("infallible: the length must be valid");
///
/// #[allow(
///     unsafe_code,
///     reason = "We have encoded the input to hexadecimal string"
/// )]
/// let output = unsafe { output.assume_init_ref() };
///
/// assert_eq!(output, b"48656C6C6F2C20776F726C6421");
/// ```
///
/// ## Errors
///
/// The length of the output buffer must be twice the length of the input
/// buffer.
///
/// We may relax this requirement in the future accepting a longer output
/// buffer, but for now, we require it for simplicity and performance.
pub fn encode<const UPPER: bool>(
    src: &[u8],
    dst: &mut [MaybeUninit<u8>],
) -> Result<(), InvalidInput> {
    backend::encode::<UPPER>(src, dst)
}

#[inline]
/// Decodes the input hexadecimal string to bytes and writes it to the output
/// buffer.
///
/// ```rust
/// use core::mem::MaybeUninit;
///
/// let input = b"48656c6c6f2c20776f726c6421";
/// let mut output = vec![MaybeUninit::<u8>::uninit(); input.len() / 2];
///
/// fashex::decode(input, &mut output).expect("infallible: the input must be valid here");
///
/// #[allow(
///     unsafe_code,
///     reason = "We have decoded the input hexadecimal string to bytes"
/// )]
/// let output = unsafe { output.assume_init_ref() };
///
/// assert_eq!(output, b"Hello, world!");
/// ```
///
/// ## Errors
///
/// 1. The input and output lengths do not match (`src.len() == 2 * dst.len()`).
/// 2. The input contains invalid hexadecimal characters.
/// 3. The input contains both uppercase and lowercase hexadecimal characters.
pub fn decode(src: &[u8], dst: &mut [MaybeUninit<u8>]) -> Result<(), InvalidInput> {
    backend::decode(src, dst)
}

/// [`encode()`] or [`decode()`], but const-evaluable at the cost of
/// performance.
///
/// Macro [`encode!`] is useful when you want to encode a byte array to
/// hexadecimal string in const contexts, such as creating a `const` variable or
/// a `static` variable.
///
/// ## Errors
///
/// The input and output lengths do not match (`2 * src.len() == dst.len()`).
pub const fn encode_generic<const UPPER: bool>(
    src: &[u8],
    dst: &mut [MaybeUninit<u8>],
) -> Result<(), InvalidInput> {
    if 2 * src.len() == dst.len() {
        #[allow(unsafe_code, reason = "The length is validated")]
        let dst: &mut [[MaybeUninit<u8>; 2]] = unsafe { dst.as_chunks_unchecked_mut() };

        #[allow(unsafe_code, reason = "The length is validated")]
        unsafe {
            backend::generic::encode_generic_unchecked::<UPPER>(src, dst);
        };

        Ok(())
    } else {
        Err(InvalidInput)
    }
}

/// [`decode()`], but const-evaluable at the cost of performance.
///
/// Macro [`decode!`] is useful when you want to decode hexadecimal string to a
/// byte array in const contexts, such as creating a `const` variable or a
/// `static` variable.
///
/// ## Errors
///
/// The input and output lengths do not match (`src.len() == 2 * dst.len()`), or
/// the input contains invalid hexadecimal characters.
pub const fn decode_generic(src: &[u8], dst: &mut [MaybeUninit<u8>]) -> Result<(), InvalidInput> {
    if src.len() == 2 * dst.len() {
        #[allow(unsafe_code, reason = "The length is validated")]
        let src: &[[u8; 2]] = unsafe { src.as_chunks_unchecked() };

        #[allow(unsafe_code, reason = "The length is validated")]
        unsafe {
            backend::generic::decode_generic_unchecked::<false>(src, dst)
        }
    } else {
        Err(InvalidInput)
    }
}

#[macro_export]
/// Helper macro for encoding hexadecimal string in const contexts.
///
/// ## Examples
///
/// ```rust
/// const HELLO_WORLD_LOWERCASE: &str = fashex::encode!(b"Hello, world!");
/// assert_eq!(HELLO_WORLD_LOWERCASE, "48656c6c6f2c20776f726c6421");
/// const HELLO_WORLD_UPPERCASE: &str = fashex::encode!(b"Hello, world!", true);
/// assert_eq!(HELLO_WORLD_UPPERCASE, "48656C6C6F2C20776F726C6421");
/// # const HELLO_WORLD_STR: &str = fashex::encode!("Hello, world!");
/// # assert_eq!(HELLO_WORLD_STR, "48656c6c6f2c20776f726c6421");
/// # const FROM_BYTES_LOWERCASE: &str = fashex::encode!([0x12, 0x34, 0xab, 0xcd]);
/// # assert_eq!(FROM_BYTES_LOWERCASE, "1234abcd");
/// ```
macro_rules! encode {
    ($bytes:expr) => {
        $crate::encode!($bytes, false)
    };
    ($bytes:expr, $uppercase:expr) => {{
        const ENCODED: [u8; $bytes.len() * 2] = {
            let buf: &mut [::core::mem::MaybeUninit<u8>; const { $bytes.len() * 2 }] =
                &mut [::core::mem::MaybeUninit::uninit(); _];

            #[allow(unsafe_code, reason = "XXX")]
            let bytes = unsafe { ::core::slice::from_raw_parts($bytes.as_ptr(), $bytes.len()) };

            match $crate::encode_generic::<{ $uppercase }>(bytes, buf) {
                Ok(()) => {}
                Err(_) => unreachable!(),
            };

            #[allow(unsafe_code, reason = "XXX")]
            unsafe {
                ::core::mem::transmute::<_, _>(*buf)
            }
        };

        #[allow(unsafe_code, reason = "XXX")]
        unsafe {
            ::core::str::from_utf8_unchecked(&ENCODED)
        }
    }};
}

#[macro_export]
/// Helper macro for decoding hexadecimal string in const contexts.
///
/// ## Examples
///
/// ```rust
/// const FOOBAR: &[u8] = fashex::decode!("48656c6c6f2c20776f726c6421");
/// assert_eq!(FOOBAR, b"Hello, world!");
/// # const FOOBAR_ARRAY: &[u8; 13] = fashex::decode!("48656c6c6f2c20776f726c6421");
/// # assert_eq!(FOOBAR_ARRAY, b"Hello, world!");
/// # const FOOBAR_RIG: &[u8; 13] = fashex::decode!("48656c6c6f2C20776F726c6421");
/// # assert_eq!(FOOBAR_RIG, b"Hello, world!");
/// ```
macro_rules! decode {
    ($bytes:expr) => {{
        const DECODED: [u8; $bytes.len() / 2] = {
            assert!(
                $bytes.len() % 2 == 0,
                "the length of the input must be even"
            );

            let buf: &mut [::core::mem::MaybeUninit<u8>; const { $bytes.len() / 2 }] =
                &mut [::core::mem::MaybeUninit::uninit(); _];

            #[allow(unsafe_code, reason = "XXX")]
            let bytes = unsafe { ::core::slice::from_raw_parts($bytes.as_ptr(), $bytes.len()) };

            match $crate::decode_generic(bytes, buf) {
                Ok(()) => {}
                Err(_) => panic!("invalid hexadecimal string"),
            };

            #[allow(unsafe_code, reason = "XXX")]
            unsafe {
                ::core::mem::transmute::<_, _>(*buf)
            }
        };

        &DECODED
    }};
}

#[cfg(test)]
mod smoking {
    #![allow(unsafe_code, reason = "XXX")]
    #![allow(unsafe_op_in_unsafe_fn, reason = "XXX")]
    #![allow(clippy::cognitive_complexity, reason = "XXX")]

    use alloc::string::String;
    use alloc::vec;
    use core::mem::MaybeUninit;
    use core::{slice, str};

    use super::{decode, decode_generic, encode, encode_generic};
    use crate::util::DIGITS_LOWER_16;

    macro_rules! test {
        (
            Encode = $encode_f:ident;
            Decode = $($decode_f:ident),*;
            Case = $i:expr
        ) => {{
            let input = $i;

            let expected = input
                .iter()
                .flat_map(|b| [
                    DIGITS_LOWER_16[(*b >> 4) as usize] as char,
                    DIGITS_LOWER_16[(*b & 0b1111) as usize] as char,
                ])
                .collect::<String>();

            let mut output = vec![MaybeUninit::<u8>::uninit(); input.len() * 2];

            $encode_f::<false>(input, &mut output).unwrap();

            let output = unsafe {
                slice::from_raw_parts(
                    output.as_ptr().cast::<u8>(),
                    output.len(),
                )
            };

            assert_eq!(
                output,
                expected.as_bytes(),
                "Encode error, expect \"{expected}\", got \"{}\" ({:?})",
                str::from_utf8(output).unwrap_or("<invalid utf-8>"),
                output
            );

            $({
                let mut decoded = vec![MaybeUninit::<u8>::uninit(); input.len()];

                $decode_f(output, &mut decoded).unwrap();

                unsafe {
                    assert_eq!(
                        decoded.assume_init_ref(),
                        input,
                        "Decode error for {}, expect {:?}, got {:?}",
                        stringify!($decode_f),
                        input,
                        decoded.assume_init_ref()
                    );
                }
            })+
        }};
    }

    #[test]
    fn test_encode() {
        const CASE: &[u8; 65] = &[
            0xA1, 0xA4, 0xA2, 0x49, 0x4A, 0x43, 0x03, 0x31, 0x5F, 0x60, 0xE7, 0x8F, 0x17, 0x36,
            0x31, 0xAD, 0xB3, 0xE4, 0xF2, 0x35, 0x33, 0x6F, 0x05, 0xF0, 0xAA, 0x52, 0xD2, 0x6F,
            0x3A, 0xB7, 0x4A, 0xAB, 0x66, 0x32, 0xB0, 0xD6, 0x1C, 0x8C, 0xED, 0x85, 0x9E, 0x03,
            0x90, 0x87, 0x16, 0x9C, 0xBA, 0x34, 0xAD, 0x59, 0x35, 0x66, 0xED, 0x80, 0x22, 0x85,
            0xDB, 0x54, 0x5E, 0x79, 0xD3, 0x9A, 0x6F, 0x24, 0x43,
        ];

        test!(
            Encode = encode_generic;
            Decode = decode_generic, decode;
            Case = &CASE[..15]
        );
        test!(
            Encode = encode_generic;
            Decode = decode_generic, decode;
            Case = &CASE[..16]
        );
        test!(
            Encode = encode_generic;
            Decode = decode_generic, decode;
            Case = &CASE[..17]
        );
        test!(
            Encode = encode_generic;
            Decode = decode_generic, decode;
            Case = &CASE[..31]
        );
        test!(
            Encode = encode_generic;
            Decode = decode_generic, decode;
            Case = &CASE[..32]
        );
        test!(
            Encode = encode_generic;
            Decode = decode_generic, decode;
            Case = &CASE[..33]
        );
        test!(
            Encode = encode_generic;
            Decode = decode_generic, decode;
            Case = &CASE[..63]
        );
        test!(
            Encode = encode_generic;
            Decode = decode_generic, decode;
            Case = &CASE[..64]
        );
        test!(
            Encode = encode_generic;
            Decode = decode_generic, decode;
            Case = &CASE[..65]
        );

        test!(
            Encode = encode;
            Decode = decode_generic, decode;
            Case = &CASE[..15]
        );
        test!(
            Encode = encode;
            Decode = decode_generic, decode;
            Case = &CASE[..16]
        );
        test!(
            Encode = encode;
            Decode = decode_generic, decode;
            Case = &CASE[..17]
        );
        test!(
            Encode = encode;
            Decode = decode_generic, decode;
            Case = &CASE[..31]
        );
        test!(
            Encode = encode;
            Decode = decode_generic, decode;
            Case = &CASE[..32]
        );
        test!(
            Encode = encode;
            Decode = decode_generic, decode;
            Case = &CASE[..33]
        );
        test!(
            Encode = encode;
            Decode = decode_generic, decode;
            Case = &CASE[..63]
        );
        test!(
            Encode = encode;
            Decode = decode_generic, decode;
            Case = &CASE[..64]
        );
        test!(
            Encode = encode;
            Decode = decode_generic, decode;
            Case = &CASE[..65]
        );
    }
}