diff --git a/CHANGELOG.md b/CHANGELOG.md index dff2f4c..3c1adcc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All significant changes to this project will be documented in this file. ### Features +* Add `policy::PaddedOptional` and `policy::UnpaddedOptional` for Base32 and Base64. Both accept complete padding or none when decoding and emit padded and unpadded output, respectively. * Add `encode_into_uninit` and `decode_into_uninit` to all profiles and the `Codec` trait. They write into caller-provided `MaybeUninit` storage and return the initialized prefix. ## v0.1.1 (2026-11-17) diff --git a/bases/ARCHITECTURE.md b/bases/ARCHITECTURE.md index 6d5215c..bc10327 100644 --- a/bases/ARCHITECTURE.md +++ b/bases/ARCHITECTURE.md @@ -4,7 +4,7 @@ Bases separates observable encoding semantics from execution strategy. ## Public layers -- Parameterized zero-sized family types (`base16::Base16`, `base32::Base32`, `base64::Base64`) combined with `policy` markers (`Padded`, `Unpadded`, `Lower`, `Upper`, `Mixed`, `Strict`) define an alphabet, padding policy, and case policy, alongside ten crate-root aliases (`Base16Lower`, `Base16Upper`, `Base32`, `Base32Unpadded`, `Base32Hex`, `Base32HexUnpadded`, `Base64`, `Base64Unpadded`, `Base64Url`, `Base64UrlUnpadded`). +- Parameterized zero-sized family types (`base16::Base16`, `base32::Base32`, `base64::Base64`) combined with `policy` markers (`Padded`, `Unpadded`, `PaddedOptional`, `UnpaddedOptional`, `Lower`, `Upper`, `Mixed`, `Strict`) define an alphabet, padding policy, and case policy, alongside ten crate-root aliases (`Base16Lower`, `Base16Upper`, `Base32`, `Base32Unpadded`, `Base32Hex`, `Base32HexUnpadded`, `Base64`, `Base64Unpadded`, `Base64Url`, `Base64UrlUnpadded`). - Concrete family types provide direct inherent methods, including `const fn` sizing and constructors (`new`, `name`, `encoded_len`, `max_decoded_len`, `display`, `encoder`, `decoder`), while the sealed `Codec` trait provides the shared contract for generic `C: Codec` callers. - Caller-buffer operations accept initialized slices (`encode_into`, `decode_into`) or `MaybeUninit` slices (`encode_into_uninit`, `decode_into_uninit`). Both `decode_in_place` and `decode_array` also operate without allocation. The `alloc` feature adds `encode`, `encode_append`, `decode`, and transactional `decode_append`. The `serde` feature adds `serialize`, `deserialize_array`, and, with `alloc`, `deserialize`. - `Encoder` and `Decoder` preserve one partial quantum for incremental operation without allocation; `std` adds `bases::io::{EncoderWriter, DecoderReader}` over `std::io::{Write, Read}`. diff --git a/bases/README.md b/bases/README.md index 1763a0d..6fb14b0 100644 --- a/bases/README.md +++ b/bases/README.md @@ -39,6 +39,17 @@ Ten crate-root aliases cover standard encoding profiles: Every profile exposes inherent methods without requiring trait imports, and implements the sealed `Codec` trait for generic callers. Configurable zero-sized family types (`base16::Base16`, `base32::Base32`, and `base64::Base64`) accept `policy` markers for other combinations, such as strict single-case Base16 or RFC 5155 Base32Hex with lowercase output and case-insensitive decoding. See the [API reference](https://docs.rs/bases) for types, methods, and their contracts. +For Base32 and Base64, the second type parameter selects the padding policy. The table shows how each policy handles the same byte with the standard Base64 alphabet. + +| Padding policy | Encodes `b"f"` as | Accepts for `b"f"` | +| -------------------------- | ----------------- | ------------------ | +| `policy::Padded` | `Zg==` | `Zg==` | +| `policy::Unpadded` | `Zg` | `Zg` | +| `policy::PaddedOptional` | `Zg==` | `Zg==`, `Zg` | +| `policy::UnpaddedOptional` | `Zg` | `Zg==`, `Zg` | + +For example, use `base64::Base64` for gRPC binary metadata. Both optional policies reject partial padding such as `Zg=`, excess padding, and non-zero unused trailing bits. + ## API layers and features - **Caller buffers (`no_std`):** `encoded_len`, `max_decoded_len`, `encode_into`, `decode_into`, `decode_in_place`, and `decode_array` operate without allocation. Concrete profiles provide `const fn` constructors and sizing methods. diff --git a/bases/src/base16.rs b/bases/src/base16.rs index 41a8bec..558a3ed 100644 --- a/bases/src/base16.rs +++ b/bases/src/base16.rs @@ -47,6 +47,7 @@ use crate::io::DecoderReader; use crate::io::EncoderWriter; use crate::policy; use crate::policy::sealed::DecodeCasePolicy; +use crate::policy::sealed::DecodePadding; use crate::policy::sealed::LetterCase; #[cfg(feature = "serde")] use crate::serde; @@ -355,7 +356,7 @@ where const NAME: &'static str = Self::name(); const INPUT_QUANTUM: usize = 1; const ENCODED_QUANTUM: usize = 2; - const PADDED: bool = false; + const DECODE_PADDING: DecodePadding = DecodePadding::Forbidden; #[inline] fn encoded_len_impl(input_len: usize) -> Option { diff --git a/bases/src/base32.rs b/bases/src/base32.rs index 7bdd1cd..578fece 100644 --- a/bases/src/base32.rs +++ b/bases/src/base32.rs @@ -47,8 +47,10 @@ use crate::io::DecoderReader; use crate::io::EncoderWriter; use crate::policy; use crate::policy::sealed::DecodeCasePolicy; +use crate::policy::sealed::DecodePadding; use crate::policy::sealed::LetterCase; use crate::policy::sealed::PaddingPolicy; +use crate::policy::sealed::profile_name; #[cfg(feature = "serde")] use crate::serde; @@ -80,7 +82,8 @@ pub(crate) mod sealed { /// [`Standard`]), padding policy (`Padding`, defaulting to /// [`policy::Padded`]), encoded letter case (`Case`, defaulting to /// [`policy::Upper`]), and decoding case policy (`DecodeCase`, defaulting to -/// [`policy::Strict`]). +/// [`policy::Strict`]). Use [`policy::PaddedOptional`] or [`policy::UnpaddedOptional`] to accept +/// both input forms while emitting padded or unpadded output, respectively. pub struct Base32< Alphabet = Standard, Padding = policy::Padded, @@ -144,28 +147,15 @@ where #[must_use] #[inline] pub const fn name() -> &'static str { - match ( - Alphabet::EXTENDED_HEX, - Padding::PADDED, - Case::UPPERCASE, - DecodeCase::STRICT, - ) { - (false, true, true, true) => "base32", - (false, false, true, true) => "base32-unpadded", - (false, true, false, true) => "base32-lower", - (false, false, false, true) => "base32-lower-unpadded", - (false, true, true, false) => "base32-mixed", - (false, false, true, false) => "base32-mixed-unpadded", - (false, true, false, false) => "base32-lower-mixed", - (false, false, false, false) => "base32-lower-mixed-unpadded", - (true, true, true, true) => "base32hex", - (true, false, true, true) => "base32hex-unpadded", - (true, true, false, true) => "base32hex-lower", - (true, false, false, true) => "base32hex-lower-unpadded", - (true, true, true, false) => "base32hex-mixed", - (true, false, true, false) => "base32hex-mixed-unpadded", - (true, true, false, false) => "base32hex-lower-mixed", - (true, false, false, false) => "base32hex-lower-mixed-unpadded", + match (Alphabet::EXTENDED_HEX, Case::UPPERCASE, DecodeCase::STRICT) { + (false, true, true) => profile_name!("base32", Padding), + (false, false, true) => profile_name!("base32-lower", Padding), + (false, true, false) => profile_name!("base32-mixed", Padding), + (false, false, false) => profile_name!("base32-lower-mixed", Padding), + (true, true, true) => profile_name!("base32hex", Padding), + (true, false, true) => profile_name!("base32hex-lower", Padding), + (true, true, false) => profile_name!("base32hex-mixed", Padding), + (true, false, false) => profile_name!("base32hex-lower-mixed", Padding), } } @@ -178,7 +168,7 @@ where /// that a buffer of that size can be allocated. #[inline] pub const fn encoded_len(input_len: usize) -> Result { - let len = if Padding::PADDED { + let len = if Padding::ENCODE_PADDED { backend::base32::encoded_len::(input_len) } else { backend::base32::encoded_len::(input_len) @@ -413,11 +403,11 @@ where const NAME: &'static str = Self::name(); const INPUT_QUANTUM: usize = 5; const ENCODED_QUANTUM: usize = 8; - const PADDED: bool = Padding::PADDED; + const DECODE_PADDING: DecodePadding = Padding::DECODE_PADDING; #[inline] fn encoded_len_impl(input_len: usize) -> Option { - if Padding::PADDED { + if Padding::ENCODE_PADDED { backend::base32::encoded_len::(input_len) } else { backend::base32::encoded_len::(input_len) @@ -431,7 +421,7 @@ where #[inline] fn decode_plan_impl(input: &[u8]) -> Result { - if Padding::PADDED { + if Padding::DECODE_PADDING.uses_padded_decoder(input) { backend::base32::decode_plan::(input) } else { backend::base32::decode_plan::(input) @@ -440,7 +430,11 @@ where #[inline] fn encode_impl(input: &[u8], output: &mut [MaybeUninit]) -> usize { - match (Alphabet::EXTENDED_HEX, Padding::PADDED, Case::UPPERCASE) { + match ( + Alphabet::EXTENDED_HEX, + Padding::ENCODE_PADDED, + Case::UPPERCASE, + ) { (false, false, false) => backend::base32::encode::(input, output), (false, false, true) => backend::base32::encode::(input, output), (false, true, false) => backend::base32::encode::(input, output), @@ -533,7 +527,7 @@ where fn decode_in_place_impl(buf: &mut [u8]) -> Result { match ( Alphabet::EXTENDED_HEX, - Padding::PADDED, + Padding::DECODE_PADDING.uses_padded_decoder(buf), Case::UPPERCASE, DecodeCase::STRICT, ) { diff --git a/bases/src/base64.rs b/bases/src/base64.rs index a555f8e..4cda078 100644 --- a/bases/src/base64.rs +++ b/bases/src/base64.rs @@ -46,7 +46,9 @@ use crate::io::DecoderReader; #[cfg(feature = "std")] use crate::io::EncoderWriter; use crate::policy; +use crate::policy::sealed::DecodePadding; use crate::policy::sealed::PaddingPolicy; +use crate::policy::sealed::profile_name; #[cfg(feature = "serde")] use crate::serde; @@ -76,7 +78,8 @@ pub(crate) mod sealed { /// /// The type parameters select the alphabet (`Alphabet`, defaulting to /// [`Standard`]) and padding policy (`Padding`, defaulting to -/// [`policy::Padded`]). +/// [`policy::Padded`]). Use [`policy::PaddedOptional`] or [`policy::UnpaddedOptional`] to accept +/// both input forms while emitting padded or unpadded output, respectively. pub struct Base64(PhantomData<(Alphabet, Padding)>); impl Clone for Base64 { @@ -129,11 +132,10 @@ where #[must_use] #[inline] pub const fn name() -> &'static str { - match (Alphabet::URL_SAFE, Padding::PADDED) { - (false, true) => "base64", - (false, false) => "base64-unpadded", - (true, true) => "base64url", - (true, false) => "base64url-unpadded", + if Alphabet::URL_SAFE { + profile_name!("base64url", Padding) + } else { + profile_name!("base64", Padding) } } @@ -146,7 +148,7 @@ where /// that a buffer of that size can be allocated. #[inline] pub const fn encoded_len(input_len: usize) -> Result { - let len = if Padding::PADDED { + let len = if Padding::ENCODE_PADDED { backend::base64::encoded_len::(input_len) } else { backend::base64::encoded_len::(input_len) @@ -379,11 +381,11 @@ where const NAME: &'static str = Self::name(); const INPUT_QUANTUM: usize = 3; const ENCODED_QUANTUM: usize = 4; - const PADDED: bool = Padding::PADDED; + const DECODE_PADDING: DecodePadding = Padding::DECODE_PADDING; #[inline] fn encoded_len_impl(input_len: usize) -> Option { - if Padding::PADDED { + if Padding::ENCODE_PADDED { backend::base64::encoded_len::(input_len) } else { backend::base64::encoded_len::(input_len) @@ -397,7 +399,7 @@ where #[inline] fn decode_plan_impl(input: &[u8]) -> Result { - if Padding::PADDED { + if Padding::DECODE_PADDING.uses_padded_decoder(input) { backend::base64::decode_plan::(input) } else { backend::base64::decode_plan::(input) @@ -406,7 +408,7 @@ where #[inline] fn encode_impl(input: &[u8], output: &mut [MaybeUninit]) -> usize { - match (Alphabet::URL_SAFE, Padding::PADDED) { + match (Alphabet::URL_SAFE, Padding::ENCODE_PADDED) { (false, false) => backend::base64::encode::(input, output), (false, true) => backend::base64::encode::(input, output), (true, false) => backend::base64::encode::(input, output), @@ -450,7 +452,10 @@ where #[inline] fn decode_in_place_impl(buf: &mut [u8]) -> Result { - match (Alphabet::URL_SAFE, Padding::PADDED) { + match ( + Alphabet::URL_SAFE, + Padding::DECODE_PADDING.uses_padded_decoder(buf), + ) { (false, false) => backend::base64::decode_in_place::(buf), (false, true) => backend::base64::decode_in_place::(buf), (true, false) => backend::base64::decode_in_place::(buf), diff --git a/bases/src/codec.rs b/bases/src/codec.rs index ac0e910..0c39453 100644 --- a/bases/src/codec.rs +++ b/bases/src/codec.rs @@ -591,6 +591,7 @@ pub(crate) mod sealed { use crate::DecodeError; use crate::backend::DecodePlan; + use crate::policy::sealed::DecodePadding; /// A direct `Codec: Profile` bound would let downstream generic code skip /// padding and output-capacity checks: @@ -619,7 +620,7 @@ pub(crate) mod sealed { const NAME: &'static str; const INPUT_QUANTUM: usize; const ENCODED_QUANTUM: usize; - const PADDED: bool; + const DECODE_PADDING: DecodePadding; fn encoded_len_impl(input_len: usize) -> Option; fn max_decoded_len_impl(input_len: usize) -> usize; diff --git a/bases/src/lib.rs b/bases/src/lib.rs index 8fbe3e2..1d4a17b 100644 --- a/bases/src/lib.rs +++ b/bases/src/lib.rs @@ -61,6 +61,10 @@ //! profile exposes inherent methods directly without requiring trait imports, and implements the //! sealed [`Codec`] trait for generic callers. //! +//! To decode both fully padded and unpadded Base32 or Base64 input, choose +//! [`policy::PaddedOptional`] for padded output or [`policy::UnpaddedOptional`] for unpadded +//! output. +//! //! # API layers //! //! - **Sizing and caller buffers (`no_std`)**: `encoded_len`, `max_decoded_len`, `encode_into`, diff --git a/bases/src/policy.rs b/bases/src/policy.rs index f8280e4..7c7feca 100644 --- a/bases/src/policy.rs +++ b/bases/src/policy.rs @@ -13,6 +13,30 @@ // limitations under the License. //! Policy markers for encoding and decoding profiles. +//! +//! For Base32 and Base64, [`PaddedOptional`] and [`UnpaddedOptional`] select the encoded +//! output. Both accept input with complete padding or with the padding omitted. +//! +//! ``` +//! use bases::base64; +//! use bases::policy; +//! +//! type Padded = base64::Base64; +//! type Unpadded = base64::Base64; +//! +//! let mut output = [0; 4]; +//! assert_eq!(Padded::encode_into(b"f", &mut output).unwrap(), "Zg=="); +//! assert_eq!(Unpadded::encode_into(b"f", &mut output).unwrap(), "Zg"); +//! +//! for input in ["Zg", "Zg=="] { +//! assert_eq!(Padded::decode_array(input), Ok(*b"f")); +//! assert_eq!(Unpadded::decode_array(input), Ok(*b"f")); +//! } +//! assert!(Padded::decode_array::<1>("Zg=").is_err()); +//! assert!(Unpadded::decode_array::<1>("Zg=").is_err()); +//! ``` + +use crate::policy::sealed::DecodePadding; /// Padding policy that requires and emits canonical `=` padding. #[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] @@ -22,6 +46,20 @@ pub struct Padded; #[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] pub struct Unpadded; +/// Emits canonical `=` padding. Decoding accepts complete padding or none. +/// +/// For example, standard Base64 encodes `b"f"` as `Zg==` and accepts both `Zg==` and `Zg`. +/// Partial padding such as `Zg=` is invalid. See [`UnpaddedOptional`] for unpadded output. +#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] +pub struct PaddedOptional; + +/// Omits `=` padding. Decoding accepts complete padding or none. +/// +/// For example, standard Base64 encodes `b"f"` as `Zg` and accepts both `Zg` and `Zg==`. +/// Partial padding such as `Zg=` is invalid. See [`PaddedOptional`] for padded output. +#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] +pub struct UnpaddedOptional; + /// Letter case policy that emits lowercase ASCII letters. #[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] pub struct Lower; @@ -39,11 +77,23 @@ pub struct Mixed; pub struct Strict; impl sealed::PaddingPolicy for Padded { - const PADDED: bool = true; + const ENCODE_PADDED: bool = true; + const DECODE_PADDING: DecodePadding = DecodePadding::Required; } impl sealed::PaddingPolicy for Unpadded { - const PADDED: bool = false; + const ENCODE_PADDED: bool = false; + const DECODE_PADDING: DecodePadding = DecodePadding::Forbidden; +} + +impl sealed::PaddingPolicy for PaddedOptional { + const ENCODE_PADDED: bool = true; + const DECODE_PADDING: DecodePadding = DecodePadding::Optional; +} + +impl sealed::PaddingPolicy for UnpaddedOptional { + const ENCODE_PADDED: bool = false; + const DECODE_PADDING: DecodePadding = DecodePadding::Optional; } impl sealed::LetterCase for Lower { @@ -63,9 +113,43 @@ impl sealed::DecodeCasePolicy for Strict { } pub(crate) mod sealed { + #[derive(Clone, Copy)] + pub enum DecodePadding { + Required, + Forbidden, + Optional, + } + + impl DecodePadding { + #[inline] + pub fn uses_padded_decoder(self, input: &[u8]) -> bool { + match self { + Self::Required => true, + Self::Forbidden => false, + Self::Optional => input.last() == Some(&b'='), + } + } + } + pub trait PaddingPolicy: 'static { - const PADDED: bool; + const ENCODE_PADDED: bool; + const DECODE_PADDING: DecodePadding; + } + + macro_rules! profile_name { + ($base:literal, $padding:ty) => {{ + use $crate::policy::sealed::DecodePadding; + match <$padding>::DECODE_PADDING { + DecodePadding::Required => $base, + DecodePadding::Forbidden => concat!($base, "-unpadded"), + DecodePadding::Optional if <$padding>::ENCODE_PADDED => { + concat!($base, "-padded-optional") + } + DecodePadding::Optional => concat!($base, "-unpadded-optional"), + } + }}; } + pub(crate) use profile_name; pub trait LetterCase: 'static { const UPPERCASE: bool; diff --git a/bases/src/stream.rs b/bases/src/stream.rs index 2429c0b..ae886b2 100644 --- a/bases/src/stream.rs +++ b/bases/src/stream.rs @@ -23,6 +23,7 @@ use crate::FinishError; use crate::backend::DecodePlan; use crate::codec; use crate::codec::sealed::Profile; +use crate::policy::sealed::DecodePadding; const MAX_INPUT_QUANTUM: usize = 5; const MAX_ENCODED_QUANTUM: usize = 8; @@ -349,15 +350,14 @@ impl Decoder { let process_len = combined_len / encoded_quantum * encoded_quantum; let pending_offset = self.pending_offset(); - let (padding, padding_reduction, padding_index) = if C::Profile::PADDED { - analyze_padding::( + let (padding, padding_reduction, padding_index) = match C::Profile::DECODE_PADDING { + DecodePadding::Forbidden => (0, 0, None), + DecodePadding::Required | DecodePadding::Optional => analyze_padding::( &self.pending[..self.pending_len], input, process_len, pending_offset, - )? - } else { - (0, 0, None) + )?, }; let input_quantum = C::Profile::INPUT_QUANTUM; @@ -457,8 +457,8 @@ impl Decoder { /// On error, [`FinishError::into_inner`] recovers the unchanged decoder. /// Output contents are unspecified on error. /// - /// Padded profiles require a complete final quantum; unpadded profiles - /// accept the partial lengths defined by their encoding. + /// Profiles that require padding need a complete final quantum. Profiles + /// that allow padding to be omitted accept canonical unpadded fragments. /// /// # Errors /// diff --git a/tests-integration/tests/contracts.rs b/tests-integration/tests/contracts.rs index c6a81d6..7b0813d 100644 --- a/tests-integration/tests/contracts.rs +++ b/tests-integration/tests/contracts.rs @@ -25,8 +25,10 @@ mod serialization; #[path = "contracts/streaming.rs"] mod streaming; +use bases::Codec; use bases::base16; use bases::base32; +use bases::base64; use bases::policy; use data_encoding::Encoding; use data_encoding::Specification; @@ -60,6 +62,70 @@ fn payload(len: usize) -> Vec { .collect() } +#[test] +fn optional_padding_accepts_only_canonical_tail_lengths() { + fn check_decode(wire: &str, expected: Option<&[u8]>) { + let mut out = vec![0; C::max_decoded_len(wire.len())]; + assert_eq!( + C::decode_into(wire, &mut out).ok().as_deref(), + expected, + "{wire}" + ); + let mut in_place = wire.as_bytes().to_vec(); + assert_eq!( + C::decode_in_place(&mut in_place).ok().as_deref(), + expected, + "{wire}" + ); + for chunk in 1..=wire.len().max(1) { + assert_eq!( + streaming::decode::(wire.as_bytes(), chunk) + .ok() + .as_deref(), + expected, + "{wire}, chunk {chunk}" + ); + } + } + + fn check(reference: &Encoding) { + for len in 0..=10 { + let raw = payload(len); + let padded = reference.encode(&raw); + let bare = padded.trim_end_matches('='); + assert_eq!(Padded::encode(&raw), padded); + assert_eq!(Unpadded::encode(&raw), bare); + assert_eq!(streaming::encode::(&raw, 1), padded); + assert_eq!(streaming::encode::(&raw, 1), bare); + + let required = padded.len() - bare.len(); + for count in 0..=required + 1 { + let wire = format!("{bare}{}", "=".repeat(count)); + let expected = (count == 0 || count == required).then_some(raw.as_slice()); + check_decode::(&wire, expected); + check_decode::(&wire, expected); + } + } + } + + check::< + base64::Base64, + base64::Base64, + >(&data_encoding::BASE64); + check::< + base64::Base64, + base64::Base64, + >(&data_encoding::BASE64URL); + check::< + base32::Base32, + base32::Base32, + >(&data_encoding::BASE32); + check::< + base32::Base32, + base32::Base32, + >(&data_encoding::BASE32HEX); +} + macro_rules! profile { ($name:ident, $codec:ty, $alphabet:expr, $padded:literal, $mixed:literal) => { mod $name { diff --git a/tests-integration/tests/contracts/malformed.rs b/tests-integration/tests/contracts/malformed.rs index 0bb5678..a2f7a14 100644 --- a/tests-integration/tests/contracts/malformed.rs +++ b/tests-integration/tests/contracts/malformed.rs @@ -17,12 +17,47 @@ use core::mem::MaybeUninit; use bases::Codec; use bases::DecodeError; use bases::DecodeSliceError; +use bases::base32; +use bases::base64; +use bases::policy; use data_encoding::Encoding; use googletest::prelude::*; use crate::payload; use crate::streaming; +#[test] +fn optional_padding_preserves_alphabet_and_trailing_bit_errors() { + type Base64 = base64::Base64; + type Base32 = base32::Base32; + + for wire in [b"Zm9vZh".as_slice(), b"Zm9vZh=="] { + assert_error::(wire, DecodeError::NonCanonical { index: 5 }); + } + assert_error::( + b"Z ==", + DecodeError::InvalidByte { + index: 1, + byte: b' ', + }, + ); + assert_error::(b"Zg==AAAA", DecodeError::InvalidPadding { index: 2 }); + for wire in [b"MZ".as_slice(), b"MZ======"] { + assert_error::(wire, DecodeError::NonCanonical { index: 1 }); + } + assert_error::( + b"my======", + DecodeError::InvalidByte { + index: 0, + byte: b'm', + }, + ); + assert_error::( + b"MY======AAAAAAAA", + DecodeError::InvalidPadding { index: 2 }, + ); +} + pub fn differential(reference: &Encoding) { let mut output = vec![0; 256]; let mut in_place = Vec::new(); diff --git a/tests-integration/tests/contracts/streaming.rs b/tests-integration/tests/contracts/streaming.rs index d69af37..6df1ab5 100644 --- a/tests-integration/tests/contracts/streaming.rs +++ b/tests-integration/tests/contracts/streaming.rs @@ -54,7 +54,7 @@ pub fn check(reference: &Encoding) { retry_invalid_update::(reference); } -fn encode(raw: &[u8], chunk: usize) -> String { +pub fn encode(raw: &[u8], chunk: usize) -> String { let mut encoder = C::encoder(); let mut encoded = String::new(); for part in raw.chunks(chunk) {