Macro const_base::decode [−][src]
macro_rules! decode { ($slice : expr, $config : expr $(,) *) => { ... }; }
Expand description
Decodes the $slice
constant into a &[u8; N]
with the encoding determined by $config
.
$slice
can be a &'static str
, &'static [u8; N]
, or &'static [u8]
.
Compile-time Errors
When this macro is passed a malformed slice, it’ll produce compile-time errors in the
same situations where crate::decode
would return an error.
For an example of what those look like, look down here
Examples
Base 64
use const_base::{decode, Config}; { const OUT: &[u8] = decode!("SGVsbG8sIHdvcmxkIQ==", Config::B64); assert_eq!(OUT, b"Hello, world!"); } { const BYTES: &[u8] = b"TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ"; // this macro can decode non-literal constants const OUT: &[u8; 26] = decode!(BYTES, Config::B64_URL_SAFE.end_padding(false)); assert_eq!(OUT, b"Lorem ipsum dolor sit amet"); }
Base 32
use const_base::{decode, Config}; const OUT: &[u8] = decode!("MZXCA3LBNFXCQKJAPN6Q====", Config::B32); assert_eq!(OUT, b"fn main() {}");
Hexadecimal
use const_base::{decode, Config}; const OUT: &[u8] = decode!("F00B", Config::HEX); assert_eq!(OUT, &[0xF0, 0x0B]);
Erroring
Malformed inputs like this
ⓘ
use const_base::{decode, Config}; decode!("A", Config::B64);
produce compile-time errors that look like this:
error[E0308]: mismatched types --> src/codec_macros.rs:39:1 | 5 | decode!("A", Config::B64); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `IsOk`, found struct `const_base::msg::InvalidInputLength` | = note: expected struct `IsOk` found struct `const_base::msg::InvalidInputLength<length<1_usize>>` = note: this error originates in the macro `$crate::__result_tuple_to_singleton` (in Nightly builds, run with -Z macro-backtrace for more info)
This macro emulates panics using type errors like those.
In this case, the error is InvalidInputLength
,
because the input string can’t be 4 * n + 1
bytes long (n
can be any positive integer).