### Validating Result with Predicate Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example of using is_ok_and to check a Result against a predicate. ```rust let x: Result = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Cloning Result Contents Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html Examples of using the cloned method on Result types containing references. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` -------------------------------- ### Unwrap Unchecked Examples Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search= Demonstrates the use of unwrap_unchecked to retrieve values without safety checks. Calling this on an Err variant results in undefined behavior. ```rust let x: Result = Ok(2); assert_eq!(unsafe { x.unwrap_unchecked() }, 2); ``` ```rust let x: Result = Err("emergency failure"); unsafe { x.unwrap_unchecked() }; // Undefined behavior! ``` -------------------------------- ### Copying Result Contents Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html Examples of using the copied method on Result types containing references. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` -------------------------------- ### Checking Result Status Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Examples of checking if a Result is Ok or Err. ```rust let x: Result = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result = Err("Some error message"); assert_eq!(x.is_ok(), false); ``` ```rust let x: Result = Ok(-3); assert_eq!(x.is_err(), false); let x: Result = Err("Some error message"); assert_eq!(x.is_err(), true); ``` -------------------------------- ### Unwrap Err Unchecked Examples Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search= Demonstrates the use of unwrap_err_unchecked to retrieve error values without safety checks. Calling this on an Ok variant results in undefined behavior. ```rust let x: Result = Ok(2); unsafe { x.unwrap_err_unchecked() }; // Undefined behavior! ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure"); ``` -------------------------------- ### into_ok Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=std%3A%3Avec Returns the contained Ok value without panicking. ```APIDOC ## pub const fn into_ok(self) -> T ### Description Returns the contained `Ok` value, but never panics. This is a nightly-only experimental API. ### Parameters - **self** (Result) - Required - The Result instance. ### Example ```rust let s: String = only_good_news().into_ok(); ``` ``` -------------------------------- ### into_ok Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search= Returns the contained Ok value without panicking. ```APIDOC ## pub const fn into_ok(self) -> T ### Description Returns the contained `Ok` value, but never panics. This is a nightly-only experimental API. ``` -------------------------------- ### Library Module Exports Source: https://docs.rs/base32ct/0.3.1/src/base32ct/lib.rs.html?search=u32+-%3E+bool The main entry point for the crate, exposing alphabet variants, encoding traits, and error handling types. ```rust pub use crate::{ alphabet::rfc4648::{Base32, Base32Unpadded, Base32Upper, Base32UpperUnpadded}, encoding::{Encoding, encoded_len}, error::{Error, Result}, }; ``` -------------------------------- ### Into Ok Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search= Extracts the Ok value without panicking, intended for infallible results. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Library Module Configuration Source: https://docs.rs/base32ct/0.3.1/src/base32ct/lib.rs.html?search= The core library configuration including no_std support, feature flags, and public API exports. ```rust 1//! Pure Rust implementation of Base32 ([RFC 4648]). 2//! 3//! Implements Base32 variants without data-dependent branches 4//! or lookup tables, thereby providing portable "best effort" constant-time 5//! operation. Not constant-time with respect to message length (only data). 6//! 7//! Supports `no_std` environments and avoids heap allocations in the core API 8//! (but also provides optional `alloc` support for convenience). 9//! 10//! Adapted from: 11//! 12//! [RFC 4648]: https://tools.ietf.org/html/rfc4648 13 14// Copyright (c) 2016 - 2018 Paragon Initiative Enterprises. 15// Copyright (c) 2014 Steve "Sc00bz" Thomas (steve at tobtu dot com). 16// 17// Permission is hereby granted, free of charge, to any person obtaining a copy 18// of this software and associated documentation files (the "Software"), to deal 19// in the Software without restriction, including without limitation the rights 20// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 21// copies of the Software, and to permit persons to whom the Software is 22// furnished to do so, subject to the following conditions: 23// 24// The above copyright notice and this permission notice shall be included in all 25// copies or substantial portions of the Software. 26// 27// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 28// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 29// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 30// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 31// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 32// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 33// SOFTWARE. 34 35#![no_std] 36#![cfg_attr(docsrs, feature(doc_cfg))] 37#![doc( 38 html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg", 39 html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg" 40)] 41#![warn( 42 clippy::mod_module_files, 43 clippy::unwrap_used, 44 missing_docs, 45 rust_2018_idioms, 46 unused_lifetimes, 47 unused_qualifications 48)] 49 50#[cfg(feature = "alloc")] 51#[macro_use] 52extern crate alloc; 53 54mod alphabet; 55mod encoding; 56mod error; 57 58pub use crate::{ 59 alphabet::rfc4648::{Base32, Base32Unpadded, Base32Upper, Base32UpperUnpadded}, 60 encoding::{Encoding, encoded_len}, 61 error::{Error, Result}, 62}; ``` -------------------------------- ### expect Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Returns the contained Ok value, or panics if the result is Err. ```APIDOC ## pub fn expect(self, msg: &str) -> T ### Description Returns the contained `Ok` value, consuming the `self` value. Panics if the value is an `Err`, with a panic message including the passed message, and the content of the `Err`. ``` -------------------------------- ### Fallback to alternative Result with or Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Returns the current Result if it is Ok, otherwise returns the provided alternative Result. ```rust let x: Result = Ok(2); let y: Result = Err("late error"); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("early error"); let y: Result = Ok(2); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("not a 2"); let y: Result = Err("late error"); assert_eq!(x.or(y), Err("late error")); let x: Result = Ok(2); let y: Result = Ok(100); assert_eq!(x.or(y), Ok(2)); ``` -------------------------------- ### Chain Results with And Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Returns the provided result if the current one is Ok, otherwise returns the Err. ```rust let x: Result = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); let x: Result = Err("early error"); let y: Result<&str, &str> = Ok("foo"); assert_eq!(x.and(y), Err("early error")); let x: Result = Err("not a 2"); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("not a 2")); let x: Result = Ok(2); let y: Result<&str, &str> = Ok("different result type"); assert_eq!(x.and(y), Ok("different result type")); ``` -------------------------------- ### unwrap Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=std%3A%3Avec Returns the contained Ok value, consuming the self value. Panics if the value is an Err. ```APIDOC ## pub fn unwrap(self) -> T ### Description Returns the contained `Ok` value, consuming the `self` value. Because this function may panic, its use is generally discouraged. ### Parameters - **self** (Result) - Required - The Result instance to unwrap. ### Example ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` ``` -------------------------------- ### unwrap Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search= Returns the contained Ok value, consuming the self value. Panics if the value is an Err. ```APIDOC ## pub fn unwrap(self) -> T ### Description Returns the contained `Ok` value, consuming the `self` value. Because this function may panic, its use is generally discouraged. ### Panics Panics if the value is an `Err`, with a panic message provided by the `Err`’s value. ``` -------------------------------- ### Provide default value with unwrap_or Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Returns the contained Ok value or the provided default value if the result is Err. ```rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` -------------------------------- ### encode_string Source: https://docs.rs/base32ct/0.3.1/base32ct/struct.Base32.html?search=std%3A%3Avec Encodes input byte slice into a String containing Base32. Requires the 'alloc' feature. ```APIDOC ## fn encode_string(input: &[u8]) -> String ### Description Encode input byte slice into a `String` containing Base32. Available on crate feature `alloc` only. ``` -------------------------------- ### Base32 String Encoding Source: https://docs.rs/base32ct/0.3.1/src/base32ct/encoding.rs.html Allocates a new String for the Base32 encoded output. Requires the 'alloc' feature. ```rust #[cfg(feature = "alloc")] fn encode_string(input: &[u8]) -> String { let elen = Self::encoded_len(input); let mut dst = vec![0u8; elen]; let res = Self::encode(input, &mut dst).expect("encoding error"); debug_assert_eq!(elen, res.len()); debug_assert!(str::from_utf8(&dst).is_ok()); // SAFETY: `dst` is fully written and contains only valid one-byte UTF-8 chars #[allow(unsafe_code)] unsafe { String::from_utf8_unchecked(dst) } } ``` -------------------------------- ### Encoding::encode_string Source: https://docs.rs/base32ct/0.3.1/base32ct/struct.Base32Upper.html?search=std%3A%3Avec Encodes an input byte slice into a String containing Base32. Requires the 'alloc' crate feature. ```APIDOC fn encode_string(input: &[u8]) -> String ``` -------------------------------- ### Define RFC4648 Base32 Alphabet Structures Source: https://docs.rs/base32ct/0.3.1/src/base32ct/alphabet/rfc4648.rs.html Implementations for lower and upper case Base32 alphabets with optional padding. ```rust //! RFC4648 Base32 alphabet. use super::{Alphabet, DecodeStep, EncodeStep}; /// RFC4648 lower case Base32 encoding with `=` padding. /// /// ```text /// [a-z] [2-7] /// 0x61-0x7a, 0x32-0x37 /// ``` #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct Base32; impl Alphabet for Base32 { const BASE: u8 = b'a'; const DECODER: &'static [DecodeStep] = DECODE_LOWER; const ENCODER: &'static [EncodeStep] = ENCODE_LOWER; const PADDED: bool = true; } /// RFC4648 lower case Base32 encoding *without* padding. /// /// ```text /// [a-z] [2-7] /// 0x61-0x7a, 0x32-0x37 /// ``` #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct Base32Unpadded; impl Alphabet for Base32Unpadded { const BASE: u8 = b'a'; const DECODER: &'static [DecodeStep] = DECODE_LOWER; const ENCODER: &'static [EncodeStep] = ENCODE_LOWER; const PADDED: bool = false; } /// Lower-case Base32 decoder. const DECODE_LOWER: &[DecodeStep] = &[DecodeStep(b'a'..=b'z', -96), DecodeStep(b'2'..=b'7', -23)]; /// Standard Base64 encoder const ENCODE_LOWER: &[EncodeStep] = &[EncodeStep(25, 73)]; /// RFC4648 upper case Base32 encoding with `=` padding. /// /// ```text /// [A-Z] [2-7] /// 0x41-0x5a, 0x32-0x37 /// ``` #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct Base32Upper; impl Alphabet for Base32Upper { const BASE: u8 = b'A'; const DECODER: &'static [DecodeStep] = &[DecodeStep(b'A'..=b'Z', -64), DecodeStep(b'2'..=b'7', -23)]; const ENCODER: &'static [EncodeStep] = &[EncodeStep(25, 41)]; const PADDED: bool = true; } /// RFC4648 upper case Base32 encoding *without* padding. /// /// ```text /// [A-Z] [2-7] /// 0x41-0x5a, 0x32-0x37 /// ``` #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct Base32UpperUnpadded; impl Alphabet for Base32UpperUnpadded { const BASE: u8 = b'A'; const DECODER: &'static [DecodeStep] = &[DecodeStep(b'A'..=b'Z', -64), DecodeStep(b'2'..=b'7', -23)]; const ENCODER: &'static [EncodeStep] = &[EncodeStep(25, 41)]; const PADDED: bool = false; } ``` -------------------------------- ### encode_string Source: https://docs.rs/base32ct/0.3.1/base32ct/struct.Base32UpperUnpadded.html?search=std%3A%3Avec Encodes an input byte slice into a String. Requires the 'alloc' feature. ```APIDOC ## fn encode_string(input: &[u8]) -> String ### Description Encode input byte slice into a String containing Base32. Available on crate feature 'alloc' only. ``` -------------------------------- ### fn encode_string Source: https://docs.rs/base32ct/0.3.1/base32ct/trait.Encoding.html?search= Encodes a byte slice into a String. Requires the 'alloc' feature. ```APIDOC ### fn encode_string(input: &[u8]) -> String Encode input byte slice into a `String` containing Base32. Available on crate feature `alloc` only. ``` -------------------------------- ### unwrap_or_default Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search= Returns the contained Ok value or a default value if the result is Err. ```APIDOC ## pub fn unwrap_or_default(self) -> T ### Description Consumes the `self` argument then, if `Ok`, returns the contained value, otherwise if `Err`, returns the default value for that type. ``` -------------------------------- ### pub fn unwrap_or(self, default: T) -> T Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the contained Ok value or a provided default value. ```APIDOC ## pub fn unwrap_or(self, default: T) -> T ### Description Returns the contained `Ok` value or a provided default. Arguments passed to `unwrap_or` are eagerly evaluated. ### Parameters - **default** (T) - Required - The default value to return if the result is Err. ``` -------------------------------- ### Length Calculation Utilities Source: https://docs.rs/base32ct/0.3.1/src/base32ct/encoding.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Functions to determine the required buffer sizes for encoding and decoding. ```rust #[inline] fn encoded_len(bytes: &[u8]) -> usize { encoded_len::(bytes.len()) } /// Get the length of the output from decoding the provided *unpadded* /// Base32-encoded input. /// /// Note that this function does not fully validate the Base32 is well-formed /// and may return incorrect results for malformed Base32. // TODO(tarcieri): checked/overflow-proof arithmetic #[inline(always)] fn decoded_len(input_len: usize) -> usize { (input_len * 5) / 8 } /// Get the length of Base32 produced by encoding the given amount of bytes. pub const fn encoded_len(length: usize) -> usize { if length == 0 { 0 } else if T::PADDED { ((length - 1) / 5 + 1) * 8 } else { (length * 8).div_ceil(5) } } ``` -------------------------------- ### encode Source: https://docs.rs/base32ct/0.3.1/base32ct/struct.Base32UpperUnpadded.html?search=std%3A%3Avec Encodes the input byte slice as Base32 into the provided destination buffer. ```APIDOC ## fn encode<'a>(src: &[u8], dst: &'a mut [u8]) -> Result<&'a str, Error> ### Description Encode the input byte slice as Base32. ``` -------------------------------- ### unwrap_or_default Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=std%3A%3Avec Returns the contained Ok value or a default value if the result is an Err. ```APIDOC ## pub fn unwrap_or_default(self) -> T ### Description Consumes the `self` argument then, if `Ok`, returns the contained value, otherwise if `Err`, returns the default value for that type. ### Parameters - **self** (Result) - Required - The Result instance to process. ### Example ```rust let good_year = "1909".parse().unwrap_or_default(); let bad_year = "190blarg".parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` ``` -------------------------------- ### Reference conversion with as_ref and as_mut Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Converts a Result to a Result containing references to the original values. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### Encoding::encode Source: https://docs.rs/base32ct/0.3.1/base32ct/struct.Base32Upper.html?search=std%3A%3Avec Encodes the input byte slice as Base32 into the provided destination buffer. ```APIDOC fn encode<'a>(src: &[u8], dst: &'a mut [u8]) -> Result<&'a str, Error> ``` -------------------------------- ### Lower-case Base32 Decoder and Encoder Constants Source: https://docs.rs/base32ct/0.3.1/src/base32ct/alphabet/rfc4648.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Constants defining the decoding steps and encoding steps for lower-case Base32. ```rust /// Lower-case Base32 decoder. const DECODE_LOWER: &[DecodeStep] = &[DecodeStep(b'a'..=b'z', -96), DecodeStep(b'2'..=b'7', -23)]; /// Standard Base64 encoder const ENCODE_LOWER: &[EncodeStep] = &[EncodeStep(25, 73)]; ``` -------------------------------- ### pub fn unwrap_or_else(self, op: F) -> T Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the contained Ok value or computes it from a provided closure. ```APIDOC ## pub fn unwrap_or_else(self, op: F) -> T ### Description Returns the contained `Ok` value or computes it from a closure if the result is `Err`. ### Parameters - **op** (FnOnce(E) -> T) - Required - The closure to execute to compute the default value if the result is Err. ``` -------------------------------- ### Unwrap with Default Value Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Returns the Ok value or the default value of the type if the result is an Err. ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` -------------------------------- ### pub fn or(self, res: Result) -> Result Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the provided result if the current result is Err, otherwise returns the Ok value of the current result. ```APIDOC ## pub fn or(self, res: Result) -> Result ### Description Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`. Arguments passed to `or` are eagerly evaluated. ### Parameters - **res** (Result) - Required - The result to return if the current result is Err. ``` -------------------------------- ### Expect Result Value Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Returns the Ok value or panics with a provided message if the Result is Err. ```rust let x: Result = Err("emergency failure"); x.expect("Testing expect"); // panics with `Testing expect: emergency failure` ``` ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### Convert Result to Option Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Methods to convert Result into Option by either keeping the Ok value or the Err value. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` ```rust let x: Result = Ok(2); assert_eq!(x.err(), None); let x: Result = Err("Nothing here"); assert_eq!(x.err(), Some("Nothing here")); ``` -------------------------------- ### Inspect Ok Value Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Executes a closure with a reference to the Ok value without modifying the result. ```rust let x: u8 = "4" .parse::() .inspect(|x| println!("original: {x}")) .map(|x| x.pow(3)) .expect("failed to parse number"); ``` -------------------------------- ### Into Ok Infallible Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Extracts the Ok value without risk of panicking, useful for compile-time safety. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Map Result to default or fallback Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Methods to handle Result by providing a default value or a fallback function. ```rust let x: Result<_, &str> = Ok("foo"); assert_eq!(x.map_or(42, |v| v.len()), 3); let x: Result<&str, _> = Err("bar"); assert_eq!(x.map_or(42, |v| v.len()), 42); ``` ```rust let k = 21; let x : Result<_, &str> = Ok("foo"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3); let x : Result<&str, _> = Err("bar"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42); ``` ```rust let x: Result<_, &str> = Ok("foo"); let y: Result<&str, _> = Err("bar"); assert_eq!(x.map_or_default(|x| x.len()), 3); assert_eq!(y.map_or_default(|y| y.len()), 0); ``` -------------------------------- ### Base32 Length Utilities Source: https://docs.rs/base32ct/0.3.1/src/base32ct/encoding.rs.html?search=std%3A%3Avec Helper functions to calculate decoded length and remove padding from Base32 inputs. ```rust #[inline(always)] fn decoded_len(input_len: usize) -> usize { (input_len * 5) / 8 } /// Remove padding from the provided input. fn remove_padding(mut input: &[u8]) -> Result<&[u8]> { // TODO(tarcieri): properly validate padding if input.len() % 8 != 0 { return Err(Error::InvalidEncoding); } for _ in 0..6 { match input.split_last() { Some((b'=', rest)) => input = rest, _ => break, } } Ok(input) } /// Get the length of Base32 produced by encoding the given amount of bytes. pub const fn encoded_len(length: usize) -> usize { if length == 0 { 0 } else if T::PADDED { ((length - 1) / 5 + 1) * 8 } else { (length * 8).div_ceil(5) } } ``` -------------------------------- ### decode Source: https://docs.rs/base32ct/0.3.1/base32ct/struct.Base32UpperUnpadded.html?search=std%3A%3Avec Decodes a Base32-encoded string into the provided output buffer. ```APIDOC ## fn decode(src: impl AsRef<[u8]>, dst: &mut [u8]) -> Result<&[u8], Error> ### Description Decode a Base32-encoded string into the provided output buffer, returning a slice containing the decoded data. ``` -------------------------------- ### and_then Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=std%3A%3Avec Calls op if the result is Ok, otherwise returns the Err value of self. ```APIDOC ## pub fn and_then(self, op: F) -> Result ### Description Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`. This function can be used for control flow based on `Result` values. ### Parameters - **self** (Result) - Required - The Result instance. - **op** (F) - Required - A function that takes the Ok value and returns a new Result. ### Example ```rust fn sq_then_to_string(x: u32) -> Result { x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") } ``` ``` -------------------------------- ### and_then Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search= Calls op if the result is Ok, otherwise returns the Err value of self. ```APIDOC ## pub fn and_then(self, op: F) -> Result ### Description Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`. This function can be used for control flow based on `Result` values. ``` -------------------------------- ### Unwrap Error Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Returns the Err value or panics if the result is an Ok. ```rust let x: Result = Ok(2); x.unwrap_err(); // panics with `2` ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### into_err Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=std%3A%3Avec Returns the contained Err value without panicking. ```APIDOC ## pub const fn into_err(self) -> E ### Description Returns the contained `Err` value, but never panics. This is a nightly-only experimental API. ### Parameters - **self** (Result) - Required - The Result instance. ### Example ```rust let error: String = only_bad_news().into_err(); ``` ``` -------------------------------- ### into_err Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search= Returns the contained Err value without panicking. ```APIDOC ## pub const fn into_err(self) -> E ### Description Returns the contained `Err` value, but never panics. This is a nightly-only experimental API. ``` -------------------------------- ### Copying and Cloning Result Contents Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Methods to map Result<&T, E> or Result<&mut T, E> to Result by copying or cloning the inner value. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` -------------------------------- ### Collect Result from Iterator Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Demonstrates how collecting an iterator of Results short-circuits upon encountering the first Err variant. ```rust let v = vec![1, 2]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_add(1).ok_or("Overflow!") ).collect(); assert_eq!(res, Ok(vec![2, 3])); ``` ```rust let v = vec![1, 2, 0]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!") ).collect(); assert_eq!(res, Err("Underflow!")); ``` ```rust let v = vec![3, 2, 1, 10]; let mut shared = 0; let res: Result, &'static str> = v.iter().map(|x: &u32| { shared += x; x.checked_sub(2).ok_or("Underflow!") }).collect(); assert_eq!(res, Err("Underflow!")); assert_eq!(shared, 6); ``` -------------------------------- ### Unwrap Result with Closure Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html Demonstrates using unwrap_or_else to provide a fallback value via a closure. ```rust assert_eq!(Ok(2).unwrap_or_else(count), 2); assert_eq!(Err("foo").unwrap_or_else(count), 3); ``` -------------------------------- ### Expect Error Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Returns the Err value or panics with a custom message if the result is an Ok. ```rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` -------------------------------- ### as_deref_mut Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Converts from Result to Result<&mut ::Target, &mut E>. ```APIDOC ## pub fn as_deref_mut(&mut self) -> Result<&mut ::Target, &mut E> ### Description Converts from `Result` (or `&mut Result`) to `Result<&mut ::Target, &mut E>`. Coerces the `Ok` variant of the original `Result` via `DerefMut` and returns the new `Result`. ``` -------------------------------- ### and Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=std%3A%3Avec Returns res if the result is Ok, otherwise returns the Err value of self. ```APIDOC ## pub fn and(self, res: Result) -> Result ### Description Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`. ### Parameters - **self** (Result) - Required - The Result instance. - **res** (Result) - Required - The result to return if self is Ok. ### Example ```rust let x: Result = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); ``` ``` -------------------------------- ### and Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search= Returns res if the result is Ok, otherwise returns the Err value of self. ```APIDOC ## pub fn and(self, res: Result) -> Result ### Description Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`. ``` -------------------------------- ### inspect Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Calls a function with a reference to the contained value if Ok, returning the original result. ```APIDOC ## pub fn inspect(self, f: F) -> Result ### Description Calls a function with a reference to the contained value if `Ok`. Returns the original result. ``` -------------------------------- ### Base32 Length Utilities Source: https://docs.rs/base32ct/0.3.1/src/base32ct/encoding.rs.html Helper functions to calculate decoded length and encoded length for Base32 data. ```rust #[inline] fn encoded_len(bytes: &[u8]) -> usize { encoded_len::(bytes.len()) } #[inline(always)] fn decoded_len(input_len: usize) -> usize { (input_len * 5) / 8 } pub const fn encoded_len(length: usize) -> usize { if length == 0 { 0 } else if T::PADDED { ((length - 1) / 5 + 1) * 8 } else { (length * 8).div_ceil(5) } } ``` -------------------------------- ### Encoding Trait Methods Source: https://docs.rs/base32ct/0.3.1/base32ct/trait.Encoding.html?search=std%3A%3Avec The Encoding trait provides methods for Base32 conversion. Note that decode_vec and encode_string require the 'alloc' feature. ```APIDOC ## fn decode(src: impl AsRef<[u8]>, dst: &mut [u8]) -> Result<&[u8]> ### Description Decodes a Base32-encoded string into the provided output buffer, returning a slice containing the decoded data. ## fn decode_vec(input: &str) -> Result> ### Description Decodes a Base32 string into a byte vector. Requires the 'alloc' feature. ## fn encode<'a>(src: &[u8], dst: &'a mut [u8]) -> Result<&'a str> ### Description Encodes the input byte slice as Base32, writing the result into the provided destination slice and returning the resulting ASCII-encoded string. ## fn encode_string(input: &[u8]) -> String ### Description Encodes an input byte slice into a String containing Base32. Requires the 'alloc' feature. ## fn encoded_len(bytes: &[u8]) -> usize ### Description Calculates the length of the Base32 string produced by encoding the given bytes. ``` -------------------------------- ### Encoding Trait Methods Source: https://docs.rs/base32ct/0.3.1/base32ct/trait.Encoding.html The Encoding trait provides methods for Base32 encoding and decoding. Note that some methods require the 'alloc' feature. ```APIDOC ## fn decode(src: impl AsRef<[u8]>, dst: &mut [u8]) -> Result<&[u8]> ### Description Decode a Base32-encoded string into the provided output buffer, returning a slice containing the decoded data. ## fn decode_vec(input: &str) -> Result> ### Description Decode a Base32 string into a byte vector. Available on crate feature `alloc` only. ## fn encode<'a>(src: &[u8], dst: &'a mut [u8]) -> Result<&'a str> ### Description Encode the input byte slice as Base32. Writes the result into the provided destination slice, returning an ASCII-encoded Base32 string value. ## fn encode_string(input: &[u8]) -> String ### Description Encode input byte slice into a `String` containing Base32. Available on crate feature `alloc` only. ## fn encoded_len(bytes: &[u8]) -> usize ### Description Get the length of Base32 produced by encoding the given bytes. ``` -------------------------------- ### Encoding Trait Methods Source: https://docs.rs/base32ct/0.3.1/base32ct/trait.Encoding.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E The Encoding trait provides methods for Base32 encoding and decoding. Note that some methods require the 'alloc' feature. ```APIDOC ## fn decode(src: impl AsRef<[u8]>, dst: &mut [u8]) -> Result<&[u8]> ### Description Decodes a Base32-encoded string into the provided output buffer. ## fn decode_vec(input: &str) -> Result> ### Description Decodes a Base32 string into a byte vector. Requires 'alloc' feature. ## fn encode<'a>(src: &[u8], dst: &'a mut [u8]) -> Result<&'a str> ### Description Encodes the input byte slice as Base32 into the provided destination slice. ## fn encode_string(input: &[u8]) -> String ### Description Encodes input byte slice into a String containing Base32. Requires 'alloc' feature. ## fn encoded_len(bytes: &[u8]) -> usize ### Description Calculates the length of the Base32 output produced by encoding the given bytes. ``` -------------------------------- ### as_deref Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Converts from Result to Result<&::Target, &E>. ```APIDOC ## pub fn as_deref(&self) -> Result<&::Target, &E> ### Description Converts from `Result` (or `&Result`) to `Result<&::Target, &E>`. Coerces the `Ok` variant of the original `Result` via `Deref` and returns the new `Result`. ``` -------------------------------- ### fn decode Source: https://docs.rs/base32ct/0.3.1/base32ct/trait.Encoding.html?search= Decodes a Base32-encoded input into a provided destination buffer. ```APIDOC ### fn decode(src: impl AsRef<[u8]>, dst: &mut [u8]) -> Result<&[u8]> Decodes a Base32-encoded string into the provided output buffer, returning a slice containing the decoded data. ``` -------------------------------- ### Map Result values Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Applies a function to the contained Ok value. ```rust let line = "1\n2\n3\n4\n"; for num in line.lines() { match num.parse::().map(|i| i * 2) { Ok(n) => println!("{n}"), Err(..) => {} } } ``` -------------------------------- ### Into Error Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search= Extracts the Err value without panicking, intended for infallible results. ```rust fn only_bad_news() -> Result { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` -------------------------------- ### fn encode Source: https://docs.rs/base32ct/0.3.1/base32ct/trait.Encoding.html?search= Encodes a byte slice into a provided destination buffer as a Base32 string. ```APIDOC ### fn encode<'a>(src: &[u8], dst: &'a mut [u8]) -> Result<&'a str> Encode the input byte slice as Base32. Writes the result into the provided destination slice, returning an ASCII-encoded Base32 string value. ``` -------------------------------- ### Encoding::decode Source: https://docs.rs/base32ct/0.3.1/base32ct/struct.Base32Upper.html?search=std%3A%3Avec Decodes a Base32-encoded string into the provided output buffer. ```APIDOC fn decode(src: impl AsRef<[u8]>, dst: &mut [u8]) -> Result<&[u8], Error> ``` -------------------------------- ### pub fn or_else(self, op: O) -> Result Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Calls the provided closure if the result is Err, otherwise returns the Ok value of the current result. ```APIDOC ## pub fn or_else(self, op: O) -> Result ### Description Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`. This function is lazily evaluated and useful for control flow based on result values. ### Parameters - **op** (FnOnce(E) -> Result) - Required - The closure to execute if the result is Err. ``` -------------------------------- ### Base32 Struct Definition Source: https://docs.rs/base32ct/0.3.1/base32ct/struct.Base32.html The primary struct definition for the Base32 encoder/decoder. ```rust pub struct Base32; ``` -------------------------------- ### Compute default value with unwrap_or_else Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Returns the contained Ok value or computes a default value using a closure if the result is Err. ```rust fn count(x: &str) -> usize { x.len() } ``` -------------------------------- ### Test Padded Base32 Encoded Length Source: https://docs.rs/base32ct/0.3.1/src/base32ct/encoding.rs.html?search=u32+-%3E+bool Verifies that the padded encoded length includes the padding length in addition to the data groups. ```rust #[test] fn padded_encoded_len() { let mut buf = vec![]; assert_eq!(Base32::encoded_len(&buf), 0); for _ in 0..10 { buf.push(b'a'); let LenData { forty_bit_groups_len, last_group_len, padding_len, } = get_len_data(buf.len()); assert_eq!( Base32::encoded_len(&buf), forty_bit_groups_len + last_group_len + padding_len, ); } } ``` -------------------------------- ### Encoding Trait Methods Source: https://docs.rs/base32ct/0.3.1/base32ct/trait.Encoding.html?search=u32+-%3E+bool Methods provided by the Encoding trait for Base32 data transformation. ```APIDOC ## fn decode(src: impl AsRef<[u8]>, dst: &mut [u8]) -> Result<&[u8]> ### Description Decodes a Base32-encoded string into the provided output buffer. ## fn decode_vec(input: &str) -> Result> ### Description Decodes a Base32 string into a byte vector. Requires the `alloc` feature. ## fn encode<'a>(src: &[u8], dst: &'a mut [u8]) -> Result<&'a str> ### Description Encodes the input byte slice as Base32 into the provided destination slice, returning the resulting ASCII-encoded string slice. ## fn encode_string(input: &[u8]) -> String ### Description Encodes an input byte slice into a String containing Base32. Requires the `alloc` feature. ## fn encoded_len(bytes: &[u8]) -> usize ### Description Calculates the length of the Base32 output produced by encoding the given bytes. ``` -------------------------------- ### Test Helper for Length Calculation Source: https://docs.rs/base32ct/0.3.1/src/base32ct/encoding.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Helper function used in tests to calculate length data for Base32 groups. ```rust fn get_len_data(data_len: usize) -> LenData { // More information about the calculation can be found at // https://www.rfc-editor.org/rfc/rfc4648#section-6 let forty_bit_groups_len = data_len / 5 * 8; let (last_group_len, padding_len) = match data_len % 5 { 0 => (0, 0), ``` -------------------------------- ### Test Unpadded Base32 Encoded Length Source: https://docs.rs/base32ct/0.3.1/src/base32ct/encoding.rs.html?search=u32+-%3E+bool Verifies that the unpadded encoded length matches the sum of forty-bit groups and the last group length. ```rust #[test] fn unpadded_encoded_len() { let mut buf = vec![]; assert_eq!(Base32Unpadded::encoded_len(&buf), 0); for _ in 0..10 { buf.push(b'a'); let LenData { forty_bit_groups_len, last_group_len, padding_len: _, } = get_len_data(buf.len()); assert_eq!( Base32Unpadded::encoded_len(&buf), forty_bit_groups_len + last_group_len ); } } ``` -------------------------------- ### Chain Results with And Then Source: https://docs.rs/base32ct/0.3.1/base32ct/type.Result.html?search=u32+-%3E+bool Calls a function if the result is Ok, allowing for lazy evaluation and control flow. ```rust fn sq_then_to_string(x: u32) -> Result { x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") } ``` -------------------------------- ### Test Base32 Encoded Length Calculations Source: https://docs.rs/base32ct/0.3.1/src/base32ct/encoding.rs.html?search= Unit tests verifying that encoded length matches the sum of forty-bit groups, last group length, and padding for both padded and unpadded variants. ```rust #[test] fn unpadded_encoded_len() { let mut buf = vec![]; assert_eq!(Base32Unpadded::encoded_len(&buf), 0); for _ in 0..10 { buf.push(b'a'); let LenData { forty_bit_groups_len, last_group_len, padding_len: _, } = get_len_data(buf.len()); assert_eq!( Base32Unpadded::encoded_len(&buf), forty_bit_groups_len + last_group_len ); } } ``` ```rust #[test] fn padded_encoded_len() { let mut buf = vec![]; assert_eq!(Base32::encoded_len(&buf), 0); for _ in 0..10 { buf.push(b'a'); let LenData { forty_bit_groups_len, last_group_len, padding_len, } = get_len_data(buf.len()); assert_eq!( Base32::encoded_len(&buf), forty_bit_groups_len + last_group_len + padding_len, ); } } ```