Macro const_base::decode

source ·
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[E0080]: evaluation of constant value failed
 --> src/codec_macros.rs:67:1
  |
5 | decode!("A", Config::B64);
  | ^^^^^^^^^^^^^^^^^^^^^^^^^ the evaluated program panicked at '

invalid input length for base-64: 1

', src/codec_macros.rs:5:1

In this case, the error is WrongInputLength, because the input string can’t be 4 * n + 1 bytes long (n can be any positive integer).