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
Conversions are primarily useful for testing, but can be used in other contexts as well.
- Compile-time assertions rely on a hack since const panics are not stable yet
as of Rust 1.51. This produces sort of reasonable error messages in compile time,
but in runtime the error messages could be better. This can be avoided
nightlycrate feature, but it only works with nightly toolchains.
- 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 a positive in some cases; e.g., keys in cryptography frequently have an expected length, and specifying it can prevent key mix-up.
Enables unstable Rust features to produce clearer panic messages. Requires a nightly Rust toolchain.
use const_decoder::Decoder; // An Ed25519 secret key. const SECRET_KEY: [u8; 64] = Decoder::Hex.decode( b"9e55d1e1aa1f455b8baad9fdf975503655f8b359d542fa7e4ce84106d625b352\ 06fac1f22240cffd637ead6647188429fafda9c9cb7eae43386ac17f61115075", );
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, although panic messages may be not quite comprehensible.
let public_key: [u8; 32] = Decoder::Hex.decode( b"06fac1f22240cffd637ead6647188429fafda9c9cb7eae43386ac17f61115075", ); let other_public_key: [u8; 32] = Decoder::Base64.decode( b"6IcUt5J4tArK8SR8SpBZb8Rp7E7kyvaTfv9N8WlOinw=", );
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
P is a power of 2).
Decoder for the PEM file format (Base64 with additional header / trailer lines).
Decoder of a human-friendly encoding, such as hex or base64, into bytes.