Crate const_decoder

source ·
Expand description

Constant functions for converting hex- and base64-encoded strings into bytes. Works on stable Rust and in no-std environments. Base-(2,4,8,16,32,64) encodings with custom alphabets are supported as well via Encoding.

Decoder is the base type encapsulating decoding logic, with SkipWhitespace and Pem types providing its variations with slightly different properties. (For example, Pem allows to parse PEM files.)

Conversions are primarily useful for testing, but can be used in other contexts as well.


  • Length of the output byte array needs to be specified, either in its type, or using turbofish syntax (see the examples below). This could be seen as a positive in some cases; e.g., keys in cryptography frequently have an expected length, and specifying it can prevent key mix-up.


hex-literal and binary_macros crates expose similar functionality as procedural macros. Because of this, macros cannot be used in no-std environments, while this approach can.

In the longer-term (after stabilizing const mutable refs, etc.) it should become possible to use “ordinary” encoding crates, such as hex.


use const_decoder::Decoder;
// An Ed25519 secret key.
const SECRET_KEY: [u8; 64] = Decoder::Hex.decode(

include_bytes! macro works as well, although it is necessary to specify bytes length.

const CERT: &[u8] = &Pem::decode::<888>(include_bytes!("certificate.crt"));

Naturally, all code works in the runtime context as well.

let public_key: [u8; 32] = Decoder::Hex.decode(
let other_public_key: [u8; 32] = Decoder::Base64.decode(

Compile-time errors

The code will fail to compile if there is an error in the literal:

// The provided hex string is too short
const BOGUS: [u8; 32] = Decoder::Hex.decode(b"c0ffee");
// The provided hex string is too long
const BOGUS: [u8; 3] = Decoder::Hex.decode(b"c01dbeef");
// The provided string contains invalid chars
const BOGUS: [u8; 5] = Decoder::Hex.decode(b"c0ffeecup");


Custom encoding scheme based on a certain alphabet (mapping between a subset of ASCII chars and digits in 0..P, where P is a power of 2).
Decoder for the PEM file format (Base64 with additional header / trailer lines).
Decoder wrapper that skips whitespace during decoding instead of panicking.


Decoder of a human-friendly encoding, such as hex or base64, into bytes.