devela/data/codec/radix/define.rs
1// devela/src/data/codec/radix/define.rs
2//
3//! Defines [`Radix`].
4//
5
6#[doc = crate::_tags!(codec)]
7/// A configurable radix-based binary-to-text codec.
8#[doc = crate::_doc_meta!{
9 location("data/codec", struct Radix),
10 test_size_of(Radix<16> = 1|8; niche !Option),
11}]
12/// `Radix<BASE>` groups binary-to-text codecs by numeric base, with associated
13/// constants selecting a concrete encoding configuration.
14///
15/// Operations are allocation-free, use caller-provided output storage, and
16/// are available in `const` contexts.
17///
18/// # Supported codecs
19///
20/// - `Radix<16>`
21/// - `HEX`: RFC 4648 Base16, uppercase output.
22/// - `HEX_LOWER`: RFC 4648 Base16, lowercase output.
23/// - `Radix<32>`
24/// - `STD`, `STD_UNPADDED`: RFC 4648 Base32.
25/// - `HEX`, `HEX_UNPADDED`: RFC 4648 Base32hex.
26/// - `CROCKFORD`: Crockford Base32 / Base32 for Humans.
27/// - `Radix<64>`
28/// - `STD`, `STD_UNPADDED`: RFC 4648 Base64.
29/// - `URL`, `URL_UNPADDED`: RFC 4648 Base64url.
30///
31/// # Methods
32///
33/// Each supported radix provides:
34///
35/// - `encode_to_slice`: encodes bytes into caller-provided ASCII storage.
36/// - `decode_from_slice`: decodes the selected canonical representation.
37/// - `decode_array`: decodes into an exact-size byte array.
38///
39/// Base32 and Base64 also provide:
40///
41/// - `decode_from_slice_relaxed`: accepts equivalent relaxed input forms.
42/// - `decode_array_relaxed`: the exact-size array counterpart.
43///
44/// # Example
45///
46/// ```
47/// use devela::Radix;
48///
49/// let mut encoded = [0; 4];
50/// let len = Radix::<64>::URL_UNPADDED
51/// .encode_to_slice(&[0xfb, 0xff], &mut encoded)
52/// .unwrap();
53///
54/// assert_eq!(&encoded[..len], b"-_8");
55///
56/// let decoded = Radix::<64>::URL_UNPADDED
57/// .decode_array::<2>(&encoded[..len])
58/// .unwrap();
59///
60/// assert_eq!(decoded, [0xfb, 0xff]);
61/// ```
62///
63/// # References
64///
65/// - [RFC 4648: Base16, Base32, Base32hex, Base64 and Base64url]
66/// - [Base32 for Humans], an active specification of Crockford Base32.
67///
68/// [RFC 4648: Base16, Base32, Base32hex, Base64 and Base64url]:
69/// https://www.rfc-editor.org/rfc/rfc4648.html
70/// [Base32 for Humans]: https://datatracker.ietf.org/doc/draft-crockford-davis-base32-for-humans/
71#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
72pub struct Radix<const BASE: u8> {
73 pub(super) cfg: u8,
74}
75
76impl<const BASE: u8> Radix<BASE> {
77 /// The numeric base.
78 pub const BASE: u8 = BASE;
79
80 pub(super) const fn configured(cfg: u8) -> Self {
81 Self { cfg }
82 }
83}