Skip to main content

EncodableBytes

Trait EncodableBytes 

Source
pub trait EncodableBytes { }
Available on crate features encoding-base32 or encoding-base64 or encoding-bech32 or encoding-hex only.
Expand description

Marker for types that may be encoded: byte-shaped sources.

Available whenever any encoding feature is on (encoding-hex, encoding-base32, encoding-base64, or encoding-bech32).

Every encoding trait in this module is blanket-implemented for T: AsRef<[u8]> + EncodableBytes. The second bound is what keeps string-shaped types out, and it is load-bearing rather than decorative — removing it changes which calls compile.

§Why the extra bound exists

str and String implement AsRef<[u8]>, so an AsRef<[u8]>-only blanket made every string an encoding input — even though strings are this crate’s decoding input. Two silent wrong answers followed from that:

  • encoded.to_hex() compiled for an EncodedSecret, which derefs to str. It hex-encoded the encoded text: a 32-byte key came back as 124 hex characters, with no signature or name to suggest anything was wrong.
  • "text".to_hex() encoded a string’s UTF-8 bytes, which is occasionally what someone means and usually not.

Both are now compile errors. Write .as_bytes() when you did mean the UTF-8.

§Implementing it

Implemented here for [u8], [u8; N] and Vec<u8>. It is an opt-in marker in the same family as CloneableSecret and SerializableSecret: implement it for your own byte-shaped newtype to make it encodable.

use secure_gate::{EncodableBytes, ToHex};

struct Nonce([u8; 12]);
impl AsRef<[u8]> for Nonce {
    fn as_ref(&self) -> &[u8] { &self.0 }
}
impl EncodableBytes for Nonce {}

assert_eq!(Nonce([0xAB; 12]).to_hex().len(), 24);

The orphan rule means no downstream crate can implement it for str or String, so the hole cannot be reopened from outside.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl EncodableBytes for Vec<u8>

Available on crate feature alloc only.
Source§

impl EncodableBytes for [u8]

Source§

impl<const N: usize> EncodableBytes for [u8; N]

Implementors§