Crate const_decoder[][src]

Constant functions for converting hex- and base64-encoded strings into bytes. Works on stable Rust and in no-std environments.

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.

Limitations

  • 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.
  • 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.

Alternatives

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 panics, const mutable refs, etc.) it should become possible to use “ordinary” encoding crates, such as hex.

Examples

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::parse::<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=",
);

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");

Structs

Pem

Decoder for the PEM file format (Base64 with additional header / trailer lines).

SkipWhitespace

Decoder wrapper that skips whitespace during decoding instead of panicking.

Enums

Decoder

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