From 5664c35299d1b3281bde0fb94ae6b590f89191c3 Mon Sep 17 00:00:00 2001 From: Alex Povel Date: Wed, 10 Jul 2024 18:10:54 +0200 Subject: [PATCH] Documentation example for constant-space validity checking Methods like `Engine::decode` require allocations sized to fit all output. For use cases where (potentially large) base64 input merely needs to be validated as correctly shaped (alphabet, padding), this approach relaxes memory requirements. --- src/lib.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 579a722..73821e4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -188,6 +188,33 @@ //! # } //! ``` //! +//! This also allows for constant-space validity checking of encoded data, using a +//! statically allocated buffer: +//! +#![cfg_attr(feature = "std", doc = "```")] +#![cfg_attr(not(feature = "std"), doc = "```ignore")] +//! # use std::io::{self, Read}; +//! use base64::{engine::general_purpose::STANDARD, read::DecoderReader}; +//! +//! # fn main() -> Result<(), Box> { +//! let mut invalid_input = "dt=="; +//! let mut decoder = DecoderReader::new(io::Cursor::new(&mut invalid_input), &STANDARD); +//! +//! let mut buf = [0u8; 128]; +//! +//! let is_valid = loop { +//! match decoder.read(&mut buf) { +//! Ok(0) => break true, // Read to end w/o error +//! Ok(_) => continue, +//! Err(_) => break false, +//! } +//! }; +//! +//! assert!(!is_valid); +//! # Ok(()) +//! # } +//! ``` +//! //! #### Encoding //! #![cfg_attr(feature = "std", doc = "```")]