Function const_base::decode [−][src]
pub const fn decode<const OUT: usize>(
input: &[u8],
config: Config
) -> Result<[u8; OUT], DecodeError>
Expand description
Decodes input
into a [u8; OUT]
with the encoding determined by config
.
Errors
This function returns these errors:
-
DecodeError::InvalidByte
: When one of the bytes isn’t in the char set for that encoding. Eg: a!
in an otherwise base 64 encoded string. -
DecodeError::MismatchedOutputLength
: WhenOUT
doesn’t equaldecoded_len(input, config)
. -
DecodeError::InvalidInputLength
: Wheninput.len()
is not a valid length for that encoding. For base 64 that is wheninput.len() % 4
equals1
.
Example
Base 64
use const_base::{ Config, DecodeError, decode, unwrap_or, utils::repeated, }; { const OUT: [u8; 5] = unwrap_or!(decode(b"cm9ja28=", Config::B64), repeated(0xFF)); assert_eq!(OUT, *b"rocko"); } { const OUT: Result<[u8; 4], DecodeError> = decode(b"bGlmZQ", Config::B64.end_padding(false)); assert_eq!(OUT, Ok(*b"life")); } { const DECODED_A: Result<[u8; 4], DecodeError> = decode(b"bGl!ZQ", Config::B64); const DECODED_B: Result<[u8; 8], DecodeError> = decode(b"AAAAAA", Config::B64); const DECODED_C: Result<[u8; 6], DecodeError> = decode(b"AAAAA", Config::B64); assert!(matches!(DECODED_A, Err(DecodeError::InvalidByte(_)))); assert!(matches!(DECODED_B, Err(DecodeError::MismatchedOutputLength(_)))); assert!(matches!(DECODED_C, Err(DecodeError::InvalidInputLength(_)))); }
Base 32
use const_base::{ Config, DecodeError, decode, unwrap_or, utils::repeated, }; { const OUT: [u8; 3] = unwrap_or!(decode(b"MNQXI===", Config::B32), repeated(0xFF)); assert_eq!(OUT, *b"cat"); } { const OUT: [u8; 3] = unwrap_or!(decode(b"MNQXI", Config::B32.end_padding(false)), repeated(0xFF)); assert_eq!(OUT, *b"cat"); }
Hexadecimal
use const_base::{ Config, DecodeError, decode, unwrap_or, utils::repeated, }; const OUT: [u8; 4] = unwrap_or!(decode(b"f09f918d", Config::HEX), repeated(0xFF)); assert_eq!(OUT, "👍".as_bytes());