### Decoding Examples Source: https://docs.rs/bech32/0.11.1/src/bech32/lib.rs.html Illustrates how to decode Bech32 encoded strings, including those with checksums and segwit addresses. Provides examples for general decoding, segwit address decoding, and no-allocation decoding using `CheckedHrpstring`. ```APIDOC ## Decoding Examples ### Description Illustrates how to decode Bech32 encoded strings, including those with checksums and segwit addresses. Provides examples for general decoding, segwit address decoding, and no-allocation decoding using `CheckedHrpstring`. ### Usage - **General Decoding**: Use `bech32::decode(encoded_string)` to decode a Bech32 string, returning the human-readable part and the data. - **Segwit Decoding**: Use `bech32::segwit::decode(address)` to decode segwit addresses, returning the HRP, version, and program. - **No-Allocation Decoding**: Use `bech32::primitives::decode::CheckedHrpstring::new::(encoded_string)` for decoding without allocations, allowing iteration over the decoded bytes. ### Examples #### General Decoding ```rust # #[cfg(feature = "alloc")] { use bech32::primitives::decode::{CheckedHrpstring, SegwitHrpstring}; use bech32::{hrp, segwit, Hrp, Bech32m}; const DATA: [u8; 20] = [0xab; 20]; // Arbitrary data to be encoded. const STRING: &str = "abc14w46h2at4w46h2at4w46h2at4w46h2at958ngu"; let (decoded_hrp, decoded_data) = bech32::decode(&STRING).expect("failed to decode"); assert_eq!(decoded_hrp, Hrp::parse("abc").unwrap()); assert_eq!(decoded_data, DATA); # } ``` #### Segwit Decoding (Taproot Address) ```rust # #[cfg(feature = "alloc")] { use bech32::primitives::decode::{CheckedHrpstring, SegwitHrpstring}; use bech32::{hrp, segwit, Hrp, Bech32m}; const DATA: [u8; 20] = [0xab; 20]; // Arbitrary data to be encoded. const TAP_ADDR: &str = "bc1p4w46h2at4w46h2at4w46h2at4w46h2at5kreae"; let (_hrp, _version, program) = segwit::decode(&TAP_ADDR).expect("valid address"); assert_eq!(program, DATA); # } ``` #### No-Allocation Decoding with `CheckedHrpstring` ```rust # #[cfg(feature = "alloc")] { use bech32::primitives::decode::{CheckedHrpstring, SegwitHrpstring}; use bech32::{hrp, segwit, Hrp, Bech32m}; const DATA: [u8; 20] = [0xab; 20]; // Arbitrary data to be encoded. const STRING: &str = "abc14w46h2at4w46h2at4w46h2at4w46h2at958ngu"; let p = CheckedHrpstring::new::(&STRING).expect("failed to parse string"); assert_eq!(p.hrp(), Hrp::parse("abc").unwrap()); assert!(p.byte_iter().eq(DATA.iter().cloned())); // We yield bytes not references. # } ``` #### No-Allocation Decoding of Segwit Address ```rust # #[cfg(feature = "alloc")] { use bech32::primitives::decode::{CheckedHrpstring, SegwitHrpstring}; use bech32::{hrp, segwit, Hrp, Bech32m}; const DATA: [u8; 20] = [0xab; 20]; // Arbitrary data to be encoded. const TAP_ADDR: &str = "bc1p4w46h2at4w46h2at4w46h2at4w46h2at5kreae"; let taproot = SegwitHrpstring::new(&TAP_ADDR).expect("valid address"); // Do something with the encoded data. let _ = taproot.byte_iter(); # } ``` ``` -------------------------------- ### Encoding Examples Source: https://docs.rs/bech32/0.11.1/src/bech32/lib.rs.html Demonstrates how to encode arbitrary data into Bech32 format using different checksum algorithms and human-readable parts. Includes examples for general encoding, segwit addresses, and no-allocation encoding. ```APIDOC ## Encoding Examples ### Description Demonstrates how to encode arbitrary data into Bech32 format using different checksum algorithms and human-readable parts. Includes examples for general encoding, segwit addresses, and no-allocation encoding. ### Usage - **General Encoding**: Use `bech32::encode::(hrp, data)` for encoding with a specified checksum type (e.g., `Bech32m`). - **Segwit Encoding**: Use `bech32::segwit::encode(hrp, version, program)` for encoding segwit addresses. - **No-Allocation Encoding**: Use `bech32::encode_to_fmt::(buffer, hrp, data)` to encode directly into a mutable buffer without intermediate allocations. ### Examples #### General Encoding with Bech32m ```rust # #[cfg(feature = "alloc")] { use bech32::{hrp, segwit, Hrp, Bech32m}; const DATA: [u8; 20] = [0xab; 20]; // Arbitrary data to be encoded. const STRING: &str = "abc14w46h2at4w46h2at4w46h2at4w46h2at958ngu"; let hrp = Hrp::parse("abc").expect("valid hrp"); let encoded_string = bech32::encode::(hrp, &DATA).expect("failed to encode string"); assert_eq!(encoded_string, STRING); # } ``` #### Segwit Encoding (Taproot Address) ```rust # #[cfg(feature = "alloc")] { use bech32::{hrp, segwit, Hrp, Bech32m}; const DATA: [u8; 20] = [0xab; 20]; // Arbitrary data to be encoded. const TAP_ADDR: &str = "bc1p4w46h2at4w46h2at4w46h2at4w46h2at5kreae"; let taproot_address = segwit::encode(hrp::BC, segwit::VERSION_1, &DATA).expect("valid witness version and program"); assert_eq!(taproot_address, TAP_ADDR); # } ``` #### No-Allocation Encoding to String Buffer ```rust # #[cfg(feature = "alloc")] { use bech32::{hrp, segwit, Hrp, Bech32m}; const DATA: [u8; 20] = [0xab; 20]; // Arbitrary data to be encoded. const STRING: &str = "abc14w46h2at4w46h2at4w46h2at4w46h2at958ngu"; let mut buf = String::new(); let hrp = Hrp::parse("abc").expect("valid hrp"); bech32::encode_to_fmt::(&mut buf, hrp, &DATA).expect("failed to encode to buffer"); assert_eq!(buf, STRING); # } ``` ``` -------------------------------- ### Segwit Address Encoding and Decoding Source: https://docs.rs/bech32/0.11.1/bech32/segwit/index.html Examples demonstrating how to encode and decode Segwit addresses using the bech32 library. ```APIDOC ## Module segwit Segregated Witness API - enables typical usage for encoding and decoding segwit addresses. ### Functions #### `encode_v1(hrp: Hrp, witness_program: &[u8]) -> String` Encodes a taproot address suitable for use on mainnet. #### `encode_v0(hrp: Hrp, witness_program: &[u8]) -> String` Encodes a segwit v0 address suitable for use on testnet. #### `encode(hrp: Hrp, witness_version: u8, witness_program: &[u8]) -> String` Encodes a segwit address when the witness version is already known. #### `decode(address: &str) -> Result<(Hrp, u8, Vec), DecodeError>` Decodes a Bitcoin bech32 segwit address, returning the Human-Readable Part (HRP), witness version, and witness program. ### Examples ```rust use bech32::{hrp, segwit, Fe32, Hrp}; let witness_prog = [ 0x75, 0x1e, 0x76, 0xe8, 0x19, 0x91, 0x96, 0xd4, 0x54, 0x94, 0x1c, 0x45, 0xd1, 0xb3, 0xa3, 0x23, 0xf1, 0x43, 0x3b, 0xd6, ]; // Encode a taproot address suitable for use on mainnet. let _ = segwit::encode_v1(hrp::BC, &witness_prog); // Encode a segwit v0 address suitable for use on testnet. let _ = segwit::encode_v0(hrp::TB, &witness_prog); // If you have the witness version already you can use: let _ = segwit::encode(hrp::BC, witness_version, &witness_prog); // Decode a Bitcoin bech32 segwit address. let address = "bc1q2s3rjwvam9dt2ftt4sqxqjf3twav0gdx0k0q2etxflx38c3x8tnssdmnjq"; let (hrp, witness_version, witness_program) = segwit::decode(address).expect("failed to decode address"); ``` ``` -------------------------------- ### Bech32 String Validation Examples Source: https://docs.rs/bech32/0.11.1/src/bech32/primitives/decode.rs.html Demonstrates how to use `UncheckedHrpstring`, `CheckedHrpstring`, and `SegwitHrpstring` to validate Bech32 strings with varying levels of checksum and segwit checks. ```rust use bech32::{Bech32, Bech32m, Fe32, Hrp}; use bech32::primitives::decode::{CheckedHrpstring, SegwitHrpstring, UncheckedHrpstring}; use bech32::segwit::VERSION_1; // An arbitrary HRP and a string of valid bech32 characters. let s = "abcd143hj65vxw49rts6kcw35u6r6tgzguyr03vvveeewjqpn05efzq444444"; assert!(UncheckedHrpstring::new(s).is_ok()); // But it has an invalid checksum. assert!(CheckedHrpstring::new::(s).is_err()); assert!(CheckedHrpstring::new::(s).is_err()); assert!(SegwitHrpstring::new(s).is_err()); // An arbitrary HRP, a string of valid bech32 characters, and a valid bech32 checksum. let s = "abcd14g08d6qejxtdg4y5r3zarvary0c5xw7kxugcx9"; assert!(UncheckedHrpstring::new(s).is_ok()); assert!(CheckedHrpstring::new::(s).is_ok()); // But not a valid segwit address. assert!(SegwitHrpstring::new(s).is_err()); // And not a valid bech32m checksum. assert!(CheckedHrpstring::new::(s).is_err()); // A valid Bitcoin taproot address. let s = "bc1pdp43hj65vxw49rts6kcw35u6r6tgzguyr03vvveeewjqpn05efzq7un9w0"; assert!(UncheckedHrpstring::new(s).is_ok()); assert!(CheckedHrpstring::new::(s).is_ok()); assert!(SegwitHrpstring::new(s).is_ok()); // But not a valid segwit v0 checksum. assert!(CheckedHrpstring::new::(s).is_err()); // Get the HRP, witness version, and encoded data. let address = "bc1pdp43hj65vxw49rts6kcw35u6r6tgzguyr03vvveeewjqpn05efzq7un9w0"; let segwit = SegwitHrpstring::new(address).expect("valid segwit address"); let _encoded_data = segwit.byte_iter(); assert_eq!(segwit.hrp(), Hrp::parse("bc").unwrap()); assert_eq!(segwit.witness_version(), VERSION_1); ``` -------------------------------- ### Checksum Engine Initialization Source: https://docs.rs/bech32/0.11.1/src/bech32/primitives/checksum.rs.html Initializes a new checksum engine for computing or verifying checksums. The engine starts with a residue of `ONE`. ```rust impl Default for Engine { fn default() -> Self { Self::new() } } impl Engine { /// Constructs a new checksum engine with no data input. #[inline] pub fn new() -> Self { Engine { residue: Ck::MidstateRepr::ONE } } ``` -------------------------------- ### Custom Checksum Implementation Source: https://docs.rs/bech32/0.11.1/src/bech32/lib.rs.html Provides an example of how to implement the `Checksum` trait to define and use a custom checksum algorithm, such as `Codex32`. ```APIDOC ## Custom Checksum ### Description Provides an example of how to implement the `Checksum` trait to define and use a custom checksum algorithm, such as `Codex32`. ### Usage To define a custom checksum algorithm, implement the `bech32::Checksum` trait. This involves specifying the `MidstateRepr`, `CHECKSUM_LENGTH`, `CODE_LENGTH`, and the `polymod` function. ### Example: `Codex32` Checksum ```rust # #[cfg(feature = "alloc")] { use bech32::Checksum; /// The codex32 checksum algorithm, defined in BIP-93. #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Codex32 {} impl Checksum for Codex32 { type MidstateRepr = u128; const CHECKSUM_LENGTH: usize = 13; const CODE_LENGTH: usize = 93; // Copied from BIP-93 fn polymod(data: &mut [u32]) { // Implementation details for the polymod function would go here. // This is a placeholder based on the provided snippet. let mut generator = [1u32, 0x3b6a57b2, 0x26508e6d, 0x1ff35a3d, 0x09090909]; let top = data[0]; let length = data.len(); for i in 0..length { let v = (top >> 25) & 0x1f; data[i] = (data[i] << 5) | v; if i + 5 < length { data[i+5] ^= generator[(v as usize) >> 21 & 0x03]; } if i + 4 < length { data[i+4] ^= generator[(v as usize) >> 16 & 0x03]; } if i + 3 < length { data[i+3] ^= generator[(v as usize) >> 11 & 0x03]; } if i + 2 < length { data[i+2] ^= generator[(v as usize) >> 6 & 0x03]; } if i + 1 < length { data[i+1] ^= generator[(v as usize) & 0x03]; } } data[0] = 0; for i in 0..length { if data[i] == top { data[i] = 1; } else if data[i] > top { data[i] -= 1; } } data[length - 1] = top; } } # } ``` ``` -------------------------------- ### Engine::new() - Construct a new checksum engine Source: https://docs.rs/bech32/0.11.1/bech32/primitives/checksum/struct.Engine.html Use this function to create a new `Engine` instance. It initializes the engine with no data input, ready to start checksum computation. ```rust pub fn new() -> Self ``` -------------------------------- ### Error Handling with EncodeIoError Source: https://docs.rs/bech32/0.11.1/bech32/enum.EncodeIoError.html This example demonstrates how to handle EncodeIoError, including its variants. It shows the use of pattern matching to differentiate between `TooLong` and `Write` errors, and how to access the underlying error if available. ```APIDOC ## Handling EncodeIoError When working with bech32 encoding, you might encounter `EncodeIoError`. Here's how you can handle it: ```rust use bech32::EncodeIoError; use std::error::Error; fn process_encoding_error(err: EncodeIoError) { match err { EncodeIoError::TooLong(e) => { println!("Encoding error: String too long. Details: {}", e); } EncodeIoError::Write(e) => { println!("Encoding error: Failed to write. Details: {}", e); // You can also access the source error if it exists if let Some(source) = e.source() { println!(" Underlying error: {}", source); } } // Since the enum is non-exhaustive, a wildcard arm is recommended // for future-proofing, though not strictly necessary if you only // care about the known variants. // _ => println!("An unknown encoding error occurred."), } } ``` ### Variants Handled: * `EncodeIoError::TooLong(CodeLengthError)`: Catches errors where the encoded string exceeds the maximum allowed length. * `EncodeIoError::Write(Error)`: Catches errors that occur during the writing process, potentially allowing access to the underlying error source. ``` -------------------------------- ### Encoding Data to Bech32 Characters Source: https://docs.rs/bech32/0.11.1/bech32/primitives/encode/struct.Encoder.html This example demonstrates how to encode a byte array into a bech32 address string. It converts bytes to field elements, calculates the checksum using the Bech32 standard, and then obtains the character iterator for the final encoded address. Ensure the HRP is valid. ```rust use bech32::{Bech32, ByteIterExt, Fe32IterExt, Hrp}; let data = [0x75, 0x1e, 0x76, 0xe8, 0x19, 0x91, 0x96, 0xd4]; let hrp = Hrp::parse("abc").expect("bc is valid hrp string"); let chars = data .iter() .copied() .bytes_to_fes() .with_checksum::(&hrp) .chars(); ``` -------------------------------- ### Define a custom checksum algorithm (Codex32) Source: https://docs.rs/bech32/0.11.1/src/bech32/lib.rs.html Example of implementing the `Checksum` trait to define a custom checksum algorithm, such as Codex32 from BIP-93. This involves specifying the midstate representation and checksum/code lengths. ```rust use bech32::Checksum; /// The codex32 checksum algorithm, defined in BIP-93. #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Codex32 {} impl Checksum for Codex32 { type MidstateRepr = u128; const CHECKSUM_LENGTH: usize = 13; const CODE_LENGTH: usize = 93; // Copied from BIP-93 ``` -------------------------------- ### type_id Source: https://docs.rs/bech32/0.11.1/bech32/primitives/hrp/struct.CharIter.html Gets the TypeId of self. ```APIDOC ## fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. ``` -------------------------------- ### Error::cause for EncodeError (Deprecated) Source: https://docs.rs/bech32/0.11.1/bech32/segwit/enum.EncodeError.html Deprecated method to get the cause of the error. Replaced by Error::source. ```rust fn cause(&self) -> Option<&dyn Error>; ``` -------------------------------- ### take Source: https://docs.rs/bech32/0.11.1/bech32/primitives/checksum/struct.HrpFe32Iter.html Creates an iterator that yields the first `n` elements. ```APIDOC ## fn take(self, n: usize) -> Take ### Description Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. ### Parameters * **n** (usize) - The maximum number of elements to yield. ``` -------------------------------- ### WitnessVersionIter::new Source: https://docs.rs/bech32/0.11.1/bech32/primitives/encode/struct.WitnessVersionIter.html Creates a new WitnessVersionIter, optionally prepending a witness version character to an existing iterator. ```APIDOC ## WitnessVersionIter::new ### Description Creates a `WitnessVersionIter`. ### Signature ```rust pub fn new(witness_version: Option, iter: I) -> Self ``` ### Parameters * `witness_version`: An optional `Fe32` representing the witness version to prepend. * `iter`: An iterator providing the stream of `Fe32` elements. ``` -------------------------------- ### enumerate Source: https://docs.rs/bech32/0.11.1/bech32/primitives/hrp/struct.ByteIter.html Creates an iterator that yields pairs of (index, element). The index starts at 0 and increments with each element. ```APIDOC ## fn enumerate(self) -> Enumerate ### Description Creates an iterator which gives the current iteration count as well as the next value. ### Returns A new iterator yielding tuples of (index, element). ``` -------------------------------- ### Create and Check Checksum for UncheckedHrpstring Source: https://docs.rs/bech32/0.11.1/bech32/primitives/decode/struct.UncheckedHrpstring.html Demonstrates how to create an UncheckedHrpstring and check for valid checksums using both Bech32 and Bech32m algorithms. If a valid checksum is found, it shows how to remove it to obtain a CheckedHrpstring. ```rust use bech32::{Bech32, Bech32m, primitives::decode::UncheckedHrpstring}; let addr = "BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4"; let unchecked = UncheckedHrpstring::new(addr).expect("valid bech32 character encoded string"); if unchecked.has_valid_checksum::() { // Remove the checksum and do something with the data. let checked = unchecked.remove_checksum::(); let _ = checked.byte_iter(); } else if unchecked.has_valid_checksum::() { // Remove the checksum and do something with the data as above. } else { // Checksum is not valid for either the bech32 or bech32 checksum algorithms. } ``` -------------------------------- ### try_from Source: https://docs.rs/bech32/0.11.1/bech32/primitives/hrp/struct.CharIter.html Performs the conversion. ```APIDOC ## fn try_from(value: U) -> Result>::Error> Performs the conversion. ``` -------------------------------- ### Get Field Element as u8 Source: https://docs.rs/bech32/0.11.1/src/bech32/primitives/gf32.rs.html Returns the underlying 5-bit unsigned integer representation of the Fe32 field element. ```rust pub fn to_u8(self) -> u8 { self.0 } ``` -------------------------------- ### Create WitnessVersionIter Source: https://docs.rs/bech32/0.11.1/bech32/primitives/encode/struct.WitnessVersionIter.html Creates a new `WitnessVersionIter` instance. This is used to prepend an optional witness version character to an existing iterator of field elements. ```rust pub fn new(witness_version: Option, iter: I) -> Self ``` -------------------------------- ### Error::cause for CodeLengthError (Deprecated) Source: https://docs.rs/bech32/0.11.1/bech32/primitives/decode/struct.CodeLengthError.html Deprecated method for getting the cause of the error. Use Error::source instead. ```rust fn cause(&self) -> Option<&dyn Error> { // Implementation details omitted for brevity } ``` -------------------------------- ### Generic Blanket Implementations Source: https://docs.rs/bech32/0.11.1/bech32/primitives/hrp/struct.Hrp.html Demonstrates generic implementations that apply to Hrp due to its nature, such as Any, Borrow, CloneToUninit, From, Into, ToOwned, ToString, TryFrom, and TryInto. ```APIDOC ### impl Any for T Provides access to the `TypeId` of a type. #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. ### impl Borrow for T Allows immutable borrowing. #### fn borrow(&self) -> &T Immutably borrows from an owned value. ### impl BorrowMut for T Allows mutable borrowing. #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. ### impl CloneToUninit for T (Nightly-only experimental API) Performs copy-assignment to an uninitialized destination. #### unsafe fn clone_to_uninit(&self, dest: *mut u8) Performs copy-assignment from `self` to `dest`. ### impl From for T Provides a way to create a type from itself. #### fn from(t: T) -> T Returns the argument unchanged. ### impl Into for T Provides a way to convert a type into another type that can be created from it. #### fn into(self) -> U Calls `U::from(self)`. ### impl ToOwned for T Provides a way to create an owned version of a borrowed type. #### type Owned = T The resulting type after obtaining ownership. #### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. #### fn clone_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. ### impl ToString for T Provides a way to convert a type into a `String`. #### fn to_string(&self) -> String Converts the given value to a `String`. ### impl TryFrom for T Provides a fallible way to convert a type into another type. #### type Error = Infallible The type returned in the event of a conversion error. #### fn try_from(value: U) -> Result>::Error> Performs the conversion. ### impl TryInto for T Provides a fallible way to convert a type into another type. #### type Error = >::Error The type returned in the event of a conversion error. #### fn try_into(self) -> Result>::Error> Performs the conversion. ``` -------------------------------- ### Error::description for EncodeError (Deprecated) Source: https://docs.rs/bech32/0.11.1/bech32/segwit/enum.EncodeError.html Deprecated method to get a description of the error. Use the Display impl or to_string() instead. ```rust fn description(&self) -> &str; ``` -------------------------------- ### Error::description for CodeLengthError (Deprecated) Source: https://docs.rs/bech32/0.11.1/bech32/primitives/decode/struct.CodeLengthError.html Deprecated method for getting a description of the error. Use the Display implementation or to_string() instead. ```rust fn description(&self) -> &str { // Implementation details omitted for brevity } ``` -------------------------------- ### Fe32 TryFrom Implementations Source: https://docs.rs/bech32/0.11.1/bech32/struct.Fe32.html Demonstrates the `try_from` methods available for converting various integer types into the Fe32 type. These methods return a Result, indicating success or a conversion error. ```APIDOC ## `impl TryFrom for Fe32` ### Description Tries to create an `Fe32` type from a signed 64-bit integer source number. ### Method `fn try_from(value: i64) -> Result` ### Errors Returns an error if `value` is outside of the range of an `Fe32`. #### Type `Error` `TryFromError` - The type returned in the event of a conversion error. ## `impl TryFrom for Fe32` ### Description Tries to create an `Fe32` type from a signed 8-bit integer source number. ### Method `fn try_from(value: i8) -> Result` ### Errors Returns an error if `value` is outside of the range of an `Fe32`. #### Type `Error` `TryFromError` - The type returned in the event of a conversion error. ## `impl TryFrom for Fe32` ### Description Tries to create an `Fe32` type from an unsigned 128-bit integer source number. ### Method `fn try_from(value: u128) -> Result` ### Errors Returns an error if `value` is outside of the range of an `Fe32`. #### Type `Error` `TryFromError` - The type returned in the event of a conversion error. ## `impl TryFrom for Fe32` ### Description Tries to create an `Fe32` type from an unsigned 16-bit integer source number. ### Method `fn try_from(value: u16) -> Result` ### Errors Returns an error if `value` is outside of the range of an `Fe32`. #### Type `Error` `TryFromError` - The type returned in the event of a conversion error. ## `impl TryFrom for Fe32` ### Description Tries to create an `Fe32` type from an unsigned 32-bit integer source number. ### Method `fn try_from(value: u32) -> Result` ### Errors Returns an error if `value` is outside of the range of an `Fe32`. #### Type `Error` `TryFromError` - The type returned in the event of a conversion error. ## `impl TryFrom for Fe32` ### Description Tries to create an `Fe32` type from an unsigned 64-bit integer source number. ### Method `fn try_from(value: u64) -> Result` ### Errors Returns an error if `value` is outside of the range of an `Fe32`. #### Type `Error` `TryFromError` - The type returned in the event of a conversion error. ## `impl TryFrom for Fe32` ### Description Tries to create an `Fe32` type from an unsigned 8-bit integer source number. ### Method `fn try_from(value: u8) -> Result` ### Errors Returns an error if `value` is outside of the range of an `Fe32`. #### Type `Error` `TryFromError` - The type returned in the event of a conversion error. ``` -------------------------------- ### Encode and Decode Segwit Addresses Source: https://docs.rs/bech32/0.11.1/bech32/segwit/index.html Demonstrates encoding Segwit v1 (Taproot) and v0 addresses for mainnet and testnet, respectively. Also shows how to encode using a provided witness version and decode a Bech32 Segwit address. ```rust use bech32::{hrp, segwit, Fe32, Hrp}; let witness_prog = [ 0x75, 0x1e, 0x76, 0xe8, 0x19, 0x91, 0x96, 0xd4, 0x54, 0x94, 0x1c, 0x45, 0xd1, 0xb3, 0xa3, 0x23, 0xf1, 0x43, 0x3b, 0xd6, ]; // Encode a taproot address suitable for use on mainnet. let _ = segwit::encode_v1(hrp::BC, &witness_prog); // Encode a segwit v0 address suitable for use on testnet. let _ = segwit::encode_v0(hrp::TB, &witness_prog); // If you have the witness version already you can use: let _ = segwit::encode(hrp::BC, witness_version, &witness_prog); // Decode a Bitcoin bech32 segwit address. let address = "bc1q2s3rjwvam9dt2ftt4sqxqjf3twav0gdx0k0q2etxflx38c3x8tnssdmnjq"; let (hrp, witness_version, witness_program) = segwit::decode(address).expect("failed to decode address"); ``` -------------------------------- ### Get Hrp Length Source: https://docs.rs/bech32/0.11.1/bech32/primitives/hrp/struct.Hrp.html Returns the number of characters in the human-readable part. The length is guaranteed to be between 1 and 83, inclusive, as per BIP-173. ```rust pub fn len(&self) -> usize ``` -------------------------------- ### Fe32 TryFrom Implementation Source: https://docs.rs/bech32/0.11.1/src/bech32/primitives/gf32.rs.html Demonstrates the implementation of `try_from` for `Fe32`, allowing conversion from signed and unsigned integer types. It includes error handling for values outside the valid range [0, 31]. ```APIDOC /// Tries to create an [`Fe32`] type from a signed source number type. /// /// # Errors /// /// Returns an error if `value` is outside of the range of an `Fe32`. #[inline] fn try_from(value: $ty) -> Result ``` -------------------------------- ### Encode Bech32m Source: https://docs.rs/bech32/0.11.1/src/bech32/lib.rs.html Encodes data into a Bech32m string. Requires a Hrp (Human-Readable Part) and the data to encode. Assumes valid inputs for this example. ```rust let hrp = Hrp::parse_unchecked("test"); let got = encode::(hrp, &DATA).expect("failed to encode"); let want = "test1lu08d6qejxtdg4y5r3zarvary0c5xw7kmz4lky"; assert_eq!(got, want); ``` -------------------------------- ### try_into Source: https://docs.rs/bech32/0.11.1/bech32/primitives/hrp/struct.CharIter.html Performs the conversion. ```APIDOC ## fn try_into(self) -> Result>::Error> Performs the conversion. ``` -------------------------------- ### Hrp Type Conversion and Ownership Source: https://docs.rs/bech32/0.11.1/bech32/hrp/struct.Hrp.html Demonstrates how Hrp instances can be converted to other types and how ownership is handled. ```APIDOC ## fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. ### Method `type_id` ### Returns - `TypeId` - The unique identifier for the type of `self`. ## fn borrow(&self) -> &T Immutably borrows from an owned value. ### Method `borrow` ### Returns - `&T` - An immutable reference to the borrowed value. ## fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. ### Method `borrow_mut` ### Returns - `&mut T` - A mutable reference to the borrowed value. ## unsafe fn clone_to_uninit(&self, dest: *mut u8) Performs copy-assignment from `self` to `dest`. ### Method `clone_to_uninit` ### Parameters - `dest`: `*mut u8` - A raw pointer to the destination memory location. ### Safety This is a nightly-only experimental API. The caller must ensure that `dest` is a valid, allocated memory location of sufficient size to hold a `Hrp` instance. ## fn from(t: T) -> T Returns the argument unchanged. ### Method `from` ### Parameters - `t`: `T` - The value to be converted. ### Returns - `T` - The original value. ## fn into(self) -> U Calls `U::from(self)`. ### Method `into` ### Returns - `U` - The converted value. ## type Owned = T The resulting type after obtaining ownership. ## fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. ### Method `to_owned` ### Returns - `T` - An owned version of the data. ## fn clone_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. ### Method `clone_into` ### Parameters - `target`: `&mut T` - A mutable reference to the target to be updated. ## fn to_string(&self) -> String Converts the given value to a `String`. ### Method `to_string` ### Returns - `String` - The string representation of the value. ## type Error = Infallible The type returned in the event of a conversion error. ## fn try_from(value: U) -> Result>::Error> Performs the conversion. ### Method `try_from` ### Parameters - `value`: `U` - The value to convert. ### Returns - `Result>::Error>` - A `Result` containing the converted value or an error. ## type Error = >::Error The type returned in the event of a conversion error. ## fn try_into(self) -> Result>::Error> Performs the conversion. ### Method `try_into` ### Returns - `Result>::Error>` - A `Result` containing the converted value or an error. ``` -------------------------------- ### Get Minimum of Two Hrp Values Source: https://docs.rs/bech32/0.11.1/bech32/primitives/hrp/struct.Hrp.html Returns the minimum of two Hrp values based on case-insensitive comparison. This is part of the `Ord` trait. ```rust fn min(self, other: Self) -> Self where Self: Sized, ``` -------------------------------- ### Get Maximum of Two Hrp Values Source: https://docs.rs/bech32/0.11.1/bech32/primitives/hrp/struct.Hrp.html Returns the maximum of two Hrp values based on case-insensitive comparison. This is part of the `Ord` trait. ```rust fn max(self, other: Self) -> Self where Self: Sized, ``` -------------------------------- ### take Source: https://docs.rs/bech32/0.11.1/bech32/primitives/decode/struct.AsciiToFe32Iter.html Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. ```APIDOC ## fn take(self, n: usize) -> Take ### Description Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. ### Parameters * `n`: The maximum number of elements to yield. ``` -------------------------------- ### Get Hrp as String Slice Source: https://docs.rs/bech32/0.11.1/bech32/primitives/hrp/struct.Hrp.html Returns a string slice (`&str`) representing the human-readable part. This is the most straightforward way to access the HRP as text. ```rust pub fn as_str(&self) -> &str ``` -------------------------------- ### Encode and Decode Segwit Addresses Source: https://docs.rs/bech32/0.11.1/src/bech32/segwit.rs.html Demonstrates encoding segwit v0 and v1 addresses, and decoding a segwit address. Requires the 'alloc' feature. ```rust use bech32::{hrp, segwit, Fe32, Hrp}; let witness_prog = [ 0x75, 0x1e, 0x76, 0xe8, 0x19, 0x91, 0x96, 0xd4, 0x54, 0x94, 0x1c, 0x45, 0xd1, 0xb3, 0xa3, 0x23, 0xf1, 0x43, 0x3b, 0xd6, ]; // Encode a taproot address suitable for use on mainnet. let _ = segwit::encode_v1(hrp::BC, &witness_prog); // Encode a segwit v0 address suitable for use on testnet. let _ = segwit::encode_v0(hrp::TB, &witness_prog); // If you have the witness version already you can use: let witness_version = segwit::VERSION_0; let _ = segwit::encode(hrp::BC, witness_version, &witness_prog); // Decode a Bitcoin bech32 segwit address. let address = "bc1q2s3rjwvam9dt2ftt4sqxqjf3twav0gdx0k0q2etxflx38c3x8tnssdmnjq"; let (hrp, witness_version, witness_program) = segwit::decode(address).expect("failed to decode address"); ``` -------------------------------- ### Experimental Iteration Utilities (Nightly Only) Source: https://docs.rs/bech32/0.11.1/bech32/primitives/encode/struct.ByteIter.html Experimental methods for iteration, available only on nightly Rust builds. ```APIDOC ## fn partial_cmp_by(self, other: I, partial_cmp: F) -> Option ### Description Lexicographically compares the elements of this `Iterator` with those of another with respect to the specified comparison function. This is a nightly-only experimental API. ### Method `partial_cmp_by` ### Parameters - `other`: An `IntoIterator` to compare against. - `partial_cmp`: A closure that defines the comparison logic between elements. ### Returns - `Option`: The ordering result if determinable, otherwise `None`. ``` ```APIDOC ## fn eq_by(self, other: I, eq: F) -> bool ### Description Determines if the elements of this `Iterator` are equal to those of another with respect to the specified equality function. This is a nightly-only experimental API. ### Method `eq_by` ### Parameters - `other`: An `IntoIterator` to compare against. - `eq`: A closure that defines the equality logic between elements. ### Returns - `bool`: `true` if the iterators are equal according to the equality function, `false` otherwise. ``` ```APIDOC ## fn exactly_one(self) -> Option ### Description Checks if the iterator contains _exactly_ one element. If so, returns this one element. This is a nightly-only experimental API. ### Method `exactly_one` ### Returns - `Option`: The single element if it exists, otherwise `None`. ``` ```APIDOC ## fn collect_array(self) -> Option<[Self::Item; N]> ### Description Checks if an iterator has _exactly_ `N` elements. If so, returns those `N` elements in an array. This is a nightly-only experimental API. ### Method `collect_array` ### Parameters - `N`: The expected number of elements. ### Returns - `Option<[Self::Item; N]>`: An array containing the elements if the iterator has exactly `N` elements, otherwise `None`. ``` -------------------------------- ### into Source: https://docs.rs/bech32/0.11.1/bech32/primitives/hrp/struct.CharIter.html Calls U::from(self). That is, this conversion is whatever the implementation of From for U chooses to do. ```APIDOC ## fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From for U` chooses to do. ``` -------------------------------- ### Test HRP Parsing Success Source: https://docs.rs/bech32/0.11.1/src/bech32/primitives/hrp.rs.html Tests that various valid HRP strings can be successfully parsed. These examples cover different character sets and lengths. ```rust macro_rules! check_parse_ok { ($($test_name:ident, $hrp:literal);* $(;)?) => { $( #[test] fn $test_name() { assert!(Hrp::parse($hrp).is_ok()); } )* } } check_parse_ok! { parse_ok_0, "a"; parse_ok_1, "A"; parse_ok_2, "abcdefg"; parse_ok_3, "ABCDEFG"; parse_ok_4, "abc123def"; parse_ok_5, "ABC123DEF"; parse_ok_6, "!\"#$%&'()*+,-./"; parse_ok_7, "1234567890"; } ``` -------------------------------- ### Get witness version Source: https://docs.rs/bech32/0.11.1/src/bech32/primitives/decode.rs.html Returns the segwit witness version if the first character of the data part is a valid version (0-16). Does not modify the data part. ```rust pub fn witness_version(&self) -> Option { let data_part = self.data_part_ascii_no_checksum(); if data_part.is_empty() { return None; } // unwrap ok because we know we gave valid bech32 characters. let witness_version = Fe32::from_char(data_part[0].into()).unwrap(); if witness_version.to_u8() > 16 { return None; } Some(witness_version) } ``` -------------------------------- ### Cloning and Conversion Methods Source: https://docs.rs/bech32/0.11.1/bech32/primitives/enum.Bech32m.html Provides methods for creating owned data from borrowed data and for replacing owned data with borrowed data, typically through cloning. It also includes implementations for `TryFrom` and `TryInto` for type conversions. ```APIDOC ## fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. ## fn clone_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. ## impl TryFrom for T where U: Into, ### type Error = Infallible The type returned in the event of a conversion error. ### fn try_from(value: U) -> Result>::Error> Performs the conversion. ## impl TryInto for T where U: TryFrom, ### type Error = >::Error The type returned in the event of a conversion error. ### fn try_into(self) -> Result>::Error> Performs the conversion. ``` -------------------------------- ### Get Hrp as Bytes Source: https://docs.rs/bech32/0.11.1/bech32/primitives/hrp/struct.Hrp.html Returns a slice of bytes representing the human-readable part. This can be used for low-level processing or when interacting with APIs that expect byte arrays. ```rust pub fn as_bytes(&self) -> &[u8] ``` -------------------------------- ### Engine::residue() - Get current checksum residue Source: https://docs.rs/bech32/0.11.1/bech32/primitives/checksum/struct.Engine.html Returns a reference to the current checksum residue. The type of the residue depends on the `Checksum` implementation used. ```rust pub fn residue(&self) -> &Ck::MidstateRepr ``` -------------------------------- ### WitnessVersionIter size_hint() method Source: https://docs.rs/bech32/0.11.1/src/bech32/primitives/encode.rs.html Provides size hints for `WitnessVersionIter`. If a witness version is present, it adds 1 to the minimum and maximum size hints from the underlying iterator. ```rust fn size_hint(&self) -> (usize, Option) { let (min, max) = self.iter.size_hint(); match self.witness_version { Some(_) => (min + 1, max.map(|max| max + 1)), None => (min, max), } } ``` -------------------------------- ### Get data part as ASCII bytes Source: https://docs.rs/bech32/0.11.1/bech32/primitives/decode/struct.CheckedHrpstring.html Retrieve the data part of a `CheckedHrpstring` as ASCII bytes, excluding the checksum. This is useful for inspecting the raw data before further processing. ```rust use bech32::{Bech32, primitives::decode::CheckedHrpstring}; let addr = "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq"; let ascii = "qar0srrr7xfkvy5l643lydnw9re59gtzz"; let checked = CheckedHrpstring::new::(&addr).unwrap(); assert!(checked.data_part_ascii_no_checksum().iter().eq(ascii.as_bytes().iter())) ```