### get example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Shows how to use get with an index or range to safely access elements or subslices, returning None for out-of-bounds. ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` -------------------------------- ### starts_with example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Returns `true` if the slice starts with the given needle or is equal to it. Always returns `true` for an empty needle. ```rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(v.starts_with(&v)); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); ``` -------------------------------- ### binary_search_by_key example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Example of using binary_search_by_key to search a slice of pairs by their second element. The example looks up four keys and asserts the results, including Ok and Err variants. ```rust let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13), (1, 21), (2, 34), (4, 55)]; assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b), Ok(9)); assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b), Err(7)); assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13)); let r = s.binary_search_by_key(&1, |&(a, b)| b); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` -------------------------------- ### binary_search_by example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Example of using binary_search_by to search a slice with a comparator function. The example looks up four elements and asserts the results, including Ok and Err variants. ```rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; let seek = 13; assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9)); let seek = 4; assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7)); let seek = 100; assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13)); let seek = 1; let r = s.binary_search_by(|probe| probe.cmp(&seek)); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` -------------------------------- ### first example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Returns the first element of the slice, or None if empty. ```rust let v = [10, 40, 30]; assert_eq!(Some(&10), v.first()); let w: &[i32] = &[]; assert_eq!(None, w.first()); ``` -------------------------------- ### as_ptr example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Shows how to get a raw pointer to the slice's buffer and use it with get_unchecked. The pointer must not outlive the slice and the memory must not be written to. ```rust let x = &[1, 2, 4]; let x_ptr = x.as_ptr(); unsafe { for i in 0..x.len() { assert_eq!(x.get_unchecked(i), &*x_ptr.add(i)); } } ``` -------------------------------- ### align_to example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Example of using align_to to split a byte slice into prefix, aligned middle, and suffix slices. The example is wrapped in an unsafe block and includes commented-out placeholder calls. ```rust unsafe { let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7]; let (prefix, shorts, suffix) = bytes.align_to::(); // less_efficient_algorithm_for_bytes(prefix); // more_efficient_algorithm_for_aligned_shorts(shorts); // less_efficient_algorithm_for_bytes(suffix); } ``` -------------------------------- ### iter example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Shows how to iterate over a slice using the iter method, yielding references to each element. ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` -------------------------------- ### split_first example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Returns the first element and the rest of the slice. ```rust let x = &[0, 1, 2]; if let Some((first, elements)) = x.split_first() { assert_eq!(first, &0); assert_eq!(elements, &[1, 2]); } ``` -------------------------------- ### as_ptr_range example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Shows how to get a range of raw pointers spanning the slice and check if a pointer is within that range. ```rust let a = [1, 2, 3]; let x = &a[1] as *const _; let y = &5 as *const _; assert!(a.as_ptr_range().contains(&x)); assert!(!a.as_ptr_range().contains(&y)); ``` -------------------------------- ### len example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Returns the number of elements in the slice. ```rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### last example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Returns the last element of the slice, or None if empty. ```rust let v = [10, 40, 30]; assert_eq!(Some(&30), v.last()); let w: &[i32] = &[]; assert_eq!(None, w.last()); ``` -------------------------------- ### starts_with empty needle example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Demonstrates that `starts_with` always returns `true` when the needle is an empty slice. ```rust let v = &[10, 40, 30]; assert!(v.starts_with(&[])); let v: &[u8] = &[]; assert!(v.starts_with(&[])); ``` -------------------------------- ### trim_ascii_start example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Removes leading ASCII whitespace from a byte slice. ```rust assert_eq!(b" \t hello world\n".trim_ascii_start(), b"hello world\n"); assert_eq!(b" ".trim_ascii_start(), b""); assert_eq!(b"".trim_ascii_start(), b""); ``` -------------------------------- ### escape_ascii example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Shows how to escape ASCII bytes in a byte string, producing an escaped string. ```rust let s = b"0\t\r\n'\"\\\x9d"; let escaped = s.escape_ascii().to_string(); assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d"); ``` -------------------------------- ### first_chunk example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Returns an array reference to the first N items, or None if slice is too short. ```rust let u = [10, 40, 30]; assert_eq!(Some(&[10, 40]), u.first_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.first_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.first_chunk::<0>()); ``` -------------------------------- ### is_empty example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Checks if the slice is empty. ```rust let a = [1, 2, 3]; assert!(!a.is_empty()); let b: &[i32] = &[]; assert!(b.is_empty()); ``` -------------------------------- ### split_last example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Returns the last element and the rest of the slice. ```rust let x = &[0, 1, 2]; if let Some((last, elements)) = x.split_last() { assert_eq!(last, &2); assert_eq!(elements, &[0, 1]); } ``` -------------------------------- ### split_first_chunk example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Returns an array reference to the first N items and the remaining slice. ```rust let x = &[0, 1, 2]; if let Some((first, elements)) = x.split_first_chunk::<2>() { assert_eq!(first, &[0, 1]); assert_eq!(elements, &[2]); } assert_eq!(None, x.split_first_chunk::<4>()); ``` -------------------------------- ### split_at example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Divides a slice into two at a given index. Panics if mid > len. Shows splitting at 0, 2, and 3. ```rust let v = ['a', 'b', 'c']; { let (left, right) = v.split_at(0); assert_eq!(left, []); assert_eq!(right, ['a', 'b', 'c']); } { let (left, right) = v.split_at(2); assert_eq!(left, ['a', 'b']); assert_eq!(right, ['c']); } { let (left, right) = v.split_at(3); assert_eq!(left, ['a', 'b', 'c']); assert_eq!(right, []); } ``` -------------------------------- ### chunk_by example with sorted subslices Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Uses chunk_by with a <= predicate to extract sorted subslices from a slice. ```rust let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4]; let mut iter = slice.chunk_by(|a, b| a <= b); assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..])); assert_eq!(iter.next(), Some(&[2, 3][..])); assert_eq!(iter.next(), Some(&[2, 3, 4][..])); assert_eq!(iter.next(), None); ``` -------------------------------- ### repeat: Panic on overflow Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html This example demonstrates that repeat panics at runtime when the capacity would overflow. The code is marked with ⓘ to indicate it will panic. ```rust // this will panic at runtime b"0123456789abcdef".repeat(usize::MAX); ``` -------------------------------- ### chunk_by example with equality predicate Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Groups consecutive equal elements into non-overlapping runs using a predicate that compares adjacent elements. ```rust let slice = &[1, 1, 1, 3, 3, 2, 2, 2]; let mut iter = slice.chunk_by(|a, b| a == b); assert_eq!(iter.next(), Some(&[1, 1, 1][..])); assert_eq!(iter.next(), Some(&[3, 3][..])); assert_eq!(iter.next(), Some(&[2, 2, 2][..])); assert_eq!(iter.next(), None); ``` -------------------------------- ### contains example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Checks if the slice contains a given value. Uses `PartialEq` and runs in O(n). For sorted slices, `binary_search` may be faster. ```rust let v = [10, 40, 30]; assert!(v.contains(&30)); assert!(!v.contains(&50)); ``` -------------------------------- ### as_chunks Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Splits the slice into a slice of N-element arrays starting at the beginning, with a remainder slice of length less than N. Panics if N is zero. ```APIDOC ## as_chunks ### Description Splits the slice into a slice of N-element arrays, starting at the beginning of the slice, and a remainder slice with length strictly less than N. ### Method pub fn as_chunks(&self) -> (&[[T; N]], &[T]) ### Parameters - N (const generic) - Required - The number of elements per chunk. ### Panics Panics if N is zero. ### Examples ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let (chunks, remainder) = slice.as_chunks(); assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]); assert_eq!(remainder, &['m']); ``` If you expect the slice to be an exact multiple, you can combine let-else with an empty slice pattern: ```rust let slice = ['R', 'u', 's', 't']; let (chunks, []) = slice.as_chunks::<2>() else { panic!("slice didn't have even length") }; assert_eq!(chunks, &[['R', 'u'], ['s', 't']]); ``` ``` -------------------------------- ### rchunks_exact example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Iterates over chunks of exactly chunk_size elements from the end of the slice. Panics if chunk_size is zero. The remainder can be retrieved with the remainder() method. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks_exact(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert!(iter.next().is_none()); assert_eq!(iter.remainder(), &['l']); ``` -------------------------------- ### split_last_chunk example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Shows how to use split_last_chunk to get the last N elements as an array and the remaining slice. Returns None if the slice is shorter than N. ```rust let x = &[0, 1, 2]; if let Some((elements, last)) = x.split_last_chunk::<2>() { assert_eq!(elements, &[0]); assert_eq!(last, &[1, 2]); } assert_eq!(None, x.split_last_chunk::<4>()); ``` -------------------------------- ### Constructing HashType with TryFrom and TryInto Source: https://docs.rs/cashaddr/latest/cashaddr/struct.HashType.html Shows two ways to construct a HashType using TryFrom and TryInto, and demonstrates that out-of-range values return an error. ```rust use cashaddr::{HashType, DecodeError}; // Here are two different ways to construct a `HashType` using the `TryFrom` trait let hash_type = HashType::try_from(3)?; let hash_type: HashType = 9.try_into()?; // Attempting to create a HashType that is out-of-range returns and Err type assert_eq!(HashType::try_from(100), Err(DecodeError::InvalidVersion(100))); ``` -------------------------------- ### last_chunk example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Shows how to use last_chunk to get the last N elements as an array. Returns None if the slice is shorter than N, and Some(&[]) for N=0 on an empty slice. ```rust let u = [10, 40, 30]; assert_eq!(Some(&[40, 30]), u.last_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.last_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.last_chunk::<0>()); ``` -------------------------------- ### binary_search basic example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Binary searches a sorted slice. Returns Ok(index) if found, Err(insertion point) if not. For multiple matches, any index in the matching range may be returned. ```rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; assert_eq!(s.binary_search(&13), Ok(9)); assert_eq!(s.binary_search(&4), Err(7)); assert_eq!(s.binary_search(&100), Err(13)); let r = s.binary_search(&1); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` -------------------------------- ### Splitting a slice with as_simd Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Demonstrates using as_simd to split a slice into prefix, middle (SIMD-aligned), and suffix segments, including a basic SIMD summation example. ```rust #![feature(portable_simd)] use core::simd::prelude::*; let short = &[1, 2, 3]; let (prefix, middle, suffix) = short.as_simd::<4>(); assert_eq!(middle, []); // Not enough elements for anything in the middle // They might be split in any possible way between prefix and suffix let it = prefix.iter().chain(suffix).copied(); assert_eq!(it.collect::>(), vec![1, 2, 3]); fn basic_simd_sum(x: &[f32]) -> f32 { use std::ops::Add; let (prefix, middle, suffix) = x.as_simd(); let sums = f32x4::from_array([ prefix.iter().copied().sum(), 0.0, 0.0, suffix.iter().copied().sum(), ]); let sums = middle.iter().copied().fold(sums, f32x4::add); sums.reduce_sum() } let numbers: Vec = (1..101).map(|x| x as _).collect(); assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0); ``` -------------------------------- ### trim_ascii_end example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Removes trailing ASCII whitespace from a byte slice. ```rust assert_eq!(b"\r hello world\n ".trim_ascii_end(), b"\r hello world"); assert_eq!(b" ".trim_ascii_end(), b""); assert_eq!(b"".trim_ascii_end(), b""); ``` -------------------------------- ### convert.rs: Legacy to Cashaddr conversion module Source: https://docs.rs/cashaddr/latest/src/cashaddr/convert.rs.html This is the full source code of the convert.rs module. It defines the `from_legacy` and `to_legacy` functions, error types, and tests. The `from_legacy` function decodes a legacy Bitcoin address (P2PKH or P2SH) and re-encodes it as a cashaddr string. The `to_legacy` function decodes a cashaddr string and converts it back to a legacy address, supporting only P2PKH and P2SH hash types. ```rust //! Module for converting between Legacy Bitcoin addresses and Cashaddr addresses. use super::{CashEnc, HashType, Payload}; /// Errors arising in the convertion of a legacy Bitcoin address to cashaddr format #[derive(Debug, PartialEq, Eq)] pub enum L2CError { /// Decoding the Legacy the Bitcoin Address failed DecodeError(bs58::decode::Error), /// Encoding the cashaddr failed EncodeError(super::EncodeError), } impl From for L2CError { fn from(bs58_err: bs58::decode::Error) -> Self { Self::DecodeError(bs58_err) } } impl From for L2CError { fn from(encode_err: super::EncodeError) -> Self { Self::EncodeError(encode_err) } } /// Convert a legacy Bitcoin address to cashaddr format /// /// Decode string `legacy_addr` as a Legacy Bitcoin P2PKH or P2SH address and re-encode the /// resulting hash payload as a cashaddr string using the approriate `HashType` and `hrp` /// as the human-readable prefix. pub fn from_legacy(legacy_addr: &str, hrp: &str) -> Result { let bytes = bs58::decode(legacy_addr).with_check(None).into_vec()?; let payload = &bytes[1..]; Ok(match bytes[0] { 0x00 => payload.encode_p2pkh(hrp), 0x05 => payload.encode_p2sh(hrp), x => Err(super::EncodeError::InvalidHashType(x)), }?) } /// Errors arising in the conversion of a cashaddr to a legacy Bitcoin address #[derive(Debug, PartialEq, Eq)] pub enum C2LError { /// Error occurred during decoding cashaddr string DecodeError(super::DecodeError), /// Decoded cashaddr had a hash type not suitable for conversion to legacy Bitcoin format. Only /// `HashType::P2PKH` and `HashType::P2SH` are supported InvalidVersionByte(u8), } /// Convert a cashaddr string to a Legacy Bitcoin address /// /// cashaddr string `cashaddr` is decoded and its hash payload is interpreted as either a /// PubkeyHash or a ScriptHash depending on its hash type. This hash is then encoded as a Legacy /// Bitcoin P2PKH address or a P2SH address, using the appropriate standard version byte matching /// the cashaddr's hash type. `cashaddr` must have a hash type of either `HashType::P2PKH` or /// `HashType::P2SH` as these are the only two hash types supported by the legacy Bitcoin address /// formats. /// /// If decoding `cashaddr` fails, return a [`C2LError::DecodeError`]. If `cashaddr` decodes /// successfully but has an unsupported hash type, return a [`C2LError::InvalidVersionByte`]. /// Otherwise, the legacy address string is returned. pub fn to_legacy(cashaddr: &str) -> Result { let payload: Payload = cashaddr.parse()?; let vbyte = match payload.hash_type { HashType::P2PKH => 0x00, HashType::P2SH => 0x05, _ => { let n = payload.hash_type.numeric_value(); return Err(C2LError::InvalidVersionByte(n)); } }; let mut payload = payload.payload; payload.insert(0, vbyte); Ok(bs58::encode(payload).with_check().into_string()) } impl From for C2LError { fn from(decode_error: super::DecodeError) -> Self { C2LError::DecodeError(decode_error) } } #[cfg(test)] mod tests { #[rustfmt::skip] const TEST_VECTORS: [(&str, &str); 6]= [ ("1BpEi6DfDAUFd7GtittLSdBeYJvcoaVggu", "bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a"), ("1KXrWXciRDZUpQwQmuM1DbwsKDLYAYsVLR", "bitcoincash:qr95sy3j9xwd2ap32xkykttr4cvcu7as4y0qverfuy"), ("16w1D5WRVKJuZUsSRzdLp9w3YGcgoxDXb", "bitcoincash:qqq3728yw0y47sqn6l2na30mcw6zm78dzqre909m2r"), ("3CWFddi6m4ndiGyKqzYvsFYagqDLPVMTzC", "bitcoincash:ppm2qsznhks23z7629mms6s4cwef74vcwvn0h829pq"), ("3LDsS579y7sruadqu11beEJoTjdFiFCdX4", "bitcoincash:pr95sy3j9xwd2ap32xkykttr4cvcu7as4yc93ky28e"), ("31nwvkZwyPdgzjBJZXfDmSWsC4ZLKpYyUw", "bitcoincash:pqq3728yw0y47sqn6l2na30mcw6zm78dzq5ucqzc37"), ]; #[test] fn from_legacy() { for tc in TEST_VECTORS { assert_eq!(super::from_legacy(tc.0, "bitcoincash").as_deref(), Ok(tc.1)); } } #[test] fn to_legacy() { for tc in TEST_VECTORS { assert_eq!(super::to_legacy(tc.1).as_deref(), Ok(tc.0)); } } #[test] fn round_trip() { use super::{from_legacy, to_legacy}; for tc in TEST_VECTORS { let cashaddr = from_legacy(tc.0, "bitcoincash").unwrap(); assert_eq!(to_legacy(&cashaddr).as_deref(), Ok(tc.0)); let legacy = to_legacy(tc.1).unwrap(); assert_eq!(from_legacy(&legacy, "bitcoincash").as_deref(), Ok(tc.1)); } } } ``` -------------------------------- ### iter Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Returns an iterator over the slice, yielding all items from start to end. ```APIDOC ## iter ### Description Returns an iterator over the slice. The iterator yields all items from start to end. ### Method `pub fn iter(&self) -> Iter<'_, T>` ### Return Value - `Iter<'_, T>` - An iterator over the slice. ### Example ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` ``` -------------------------------- ### trim_ascii example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Removes leading and trailing ASCII whitespace from a byte slice. ```rust assert_eq!(b"\r hello world\n ".trim_ascii(), b"hello world"); assert_eq!(b" ".trim_ascii(), b""); assert_eq!(b"".trim_ascii(), b""); ``` -------------------------------- ### starts_with Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Returns true if the needle is a prefix of the slice or equal to the slice. ```APIDOC ## starts_with ### Description Returns `true` if `needle` is a prefix of the slice or equal to the slice. ### Method `pub fn starts_with(&self, needle: &[T]) -> bool` ### Parameters - `needle` (&[T]) - Required - The slice to check as a prefix. ### Return Value - `bool` - `true` if the slice starts with the needle, otherwise `false`. ### Example ```rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(v.starts_with(&v)); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); ``` Always returns `true` if `needle` is an empty slice: ```rust let v = &[10, 40, 30]; assert!(v.starts_with(&[])); let v: &[u8] = &[]; assert!(v.starts_with(&[])); ``` ``` -------------------------------- ### binary_search with partition_point for insertion Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Uses partition_point to find insertion index for maintaining sorted order, then inserts. Using <= allows insert to shift fewer elements. ```rust let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; let num = 42; let idx = s.partition_point(|&x| x <= num); // If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to // `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` will allow `insert` // to shift less elements. s.insert(idx, num); assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]); ``` -------------------------------- ### partition_point with all elements matching Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Demonstrates behavior when all elements match the predicate or the slice is empty. ```rust let a = [2, 4, 8]; assert_eq!(a.partition_point(|x| x < &100), a.len()); let a: [i32; 0] = []; assert_eq!(a.partition_point(|x| x < &100), 0); ``` -------------------------------- ### get Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Returns a reference to an element or subslice depending on the type of index. Returns None if out of bounds. ```APIDOC ## get ### Description Returns a reference to an element or subslice depending on the type of index. If given a position, returns a reference to the element at that position or `None` if out of bounds. If given a range, returns the subslice corresponding to that range, or `None` if out of bounds. ### Method `pub fn get(&self, index: I) -> Option<&>::Output> where I: SliceIndex<[T]>` ### Parameters - `index` (I) - Required - The index or range to access. ### Return Value - `Option<&>::Output>` - `Some` reference to the element or subslice, or `None` if out of bounds. ### Example ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` ``` -------------------------------- ### element_offset with unaligned element Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Demonstrates that element_offset returns None when the reference does not point to the start of an element. ```rust #![feature(substr_range)] let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### Handle short slices with windows() Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Demonstrates that the iterator returns no values when the slice length is less than the window size. ```rust let slice = ['f', 'o', 'o']; let mut iter = slice.windows(4); assert!(iter.next().is_none()); ``` -------------------------------- ### ends_with empty needle example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Demonstrates that `ends_with` always returns `true` when the needle is an empty slice. ```rust let v = &[10, 40, 30]; assert!(v.ends_with(&[])); let v: &[u8] = &[]; assert!(v.ends_with(&[])); ``` -------------------------------- ### trim_ascii_start Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Returns a byte slice with leading ASCII whitespace bytes removed. ```APIDOC ## trim_ascii_start ### Description Returns a byte slice with leading ASCII whitespace bytes removed. 'Whitespace' refers to the definition used by u8::is_ascii_whitespace. ### Method trim_ascii_start ### Signature pub fn trim_ascii_start(&self) -> &[u8] ### Parameters None ### Returns - **&[u8]** - The slice with leading ASCII whitespace removed. ### Examples ``` assert_eq!(b" \t hello world\n".trim_ascii_start(), b"hello world\n"); assert_eq!(b" ".trim_ascii_start(), b""); assert_eq!(b"".trim_ascii_start(), b""); ``` ``` -------------------------------- ### contains with iter().any example Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Shows how to search for a value when you don't have a `&T` but can compare with another type, e.g., `String` implements `PartialEq`. Uses `iter().any`. ```rust let v = [String::from("hello"), String::from("world")]; // slice of `String` assert!(v.iter().any(|e| e == "hello")); // search with `&str` assert!(!v.iter().any(|e| e == "hi")); ``` -------------------------------- ### rchunks Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Returns an iterator over chunk_size elements of the slice at a time, starting at the end. Panics if chunk_size is zero. ```APIDOC ## rchunks ### Description Returns an iterator over chunk_size elements of the slice at a time, starting at the end of the slice. The chunks are slices and do not overlap. If chunk_size does not divide the length of the slice, then the last chunk will not have length chunk_size. ### Method pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> ### Parameters - chunk_size (usize) - Required - The number of elements per chunk. ### Panics Panics if chunk_size is zero. ### Examples ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert_eq!(iter.next().unwrap(), &['l']); assert!(iter.next().is_none()); ``` ``` -------------------------------- ### Iterate over reverse chunks with rchunks Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Returns an iterator over chunks of a specified size starting from the end of the slice. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert_eq!(iter.next().unwrap(), &['l']); assert!(iter.next().is_none()); ``` -------------------------------- ### to_legacy Source: https://docs.rs/cashaddr/latest/cashaddr/convert/index.html Converts a cashaddr string to a Legacy Bitcoin address. ```APIDOC ## to_legacy ### Description Convert a cashaddr string to a Legacy Bitcoin address. ### Function Signature `to_legacy(...)` ### Parameters - **cashaddr** (string) - Required - The cashaddr address to convert. ### Returns - **legacy_address** (string) - The converted legacy Bitcoin address. ### Errors - **C2LError** - Errors arising in the conversion of a cashaddr to a legacy Bitcoin address. ``` -------------------------------- ### Split slice into reverse chunks with as_rchunks Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Splits a slice into N-element arrays starting from the end of the slice. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let (remainder, chunks) = slice.as_rchunks(); assert_eq!(remainder, &['l']); assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]); ``` -------------------------------- ### connect: Deprecated alias for join Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Deprecated since 1.3.0, renamed to join. The example shows the same usage as join. ```rust assert_eq!(["hello", "world"].connect(" "), "hello world"); assert_eq!([[1, 2], [3, 4]].connect(&0), [1, 2, 0, 3, 4]); ``` -------------------------------- ### as_array Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Gets a reference to the underlying array if the slice length exactly matches N. Returns None otherwise. ```APIDOC ## as_array ### Description Gets a reference to the underlying array. If `N` is not exactly equal to the length of `self`, then this method returns `None`. This is a nightly-only experimental API. ### Method `pub fn as_array(&self) -> Option<&[T; N]>` ### Parameters - `N` (const usize) - Required - The length of the array. ### Return Value - `Option<&[T; N]>` - `Some` reference to the array if the slice length equals `N`, otherwise `None`. ### Note This is a nightly-only experimental API (`slice_as_array`). ``` -------------------------------- ### as_simd Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Splits a slice into a prefix, a middle of aligned SIMD types, and a suffix. This is a safe wrapper around slice::align_to and inherits its guarantees. It is a nightly-only experimental API. ```APIDOC ## as_simd ### Description Splits a slice into a prefix, a middle of aligned SIMD types, and a suffix. This is a safe wrapper around `slice::align_to`, so inherits the same guarantees as that method. This is a nightly-only experimental API. ### Signature pub fn as_simd(&self) -> (&[T], &[Simd], &[T]) where Simd: AsRef<[T; LANES]>, T: SimdElement, LaneCount: SupportedLaneCount ### Parameters - `LANES` (const generic) - Required - The number of SIMD lanes. ### Panics This will panic if the size of the SIMD type is different from `LANES` times that of the scalar. At the time of writing, the trait restrictions on `Simd` keeps that from ever happening, as only power-of-two numbers of lanes are supported. It's possible that, in the future, those restrictions might be lifted in a way that would make it possible to see panics from this method for something like `LANES == 3`. ### Examples ```rust #![feature(portable_simd)] use core::simd::prelude::*; let short = &[1, 2, 3]; let (prefix, middle, suffix) = short.as_simd::<4>(); assert_eq!(middle, []); // Not enough elements for anything in the middle // They might be split in any possible way between prefix and suffix let it = prefix.iter().chain(suffix).copied(); assert_eq!(it.collect::>(), vec![1, 2, 3]); fn basic_simd_sum(x: &[f32]) -> f32 { use std::ops::Add; let (prefix, middle, suffix) = x.as_simd(); let sums = f32x4::from_array([ prefix.iter().copied().sum(), 0.0, 0.0, suffix.iter().copied().sum(), ]); let sums = middle.iter().copied().fold(sums, f32x4::add); sums.reduce_sum() } let numbers: Vec = (1..101).map(|x| x as _).collect(); assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0); ``` ### Availability 1.82.0 · Source ``` -------------------------------- ### rchunks_exact Source: https://docs.rs/cashaddr/latest/cashaddr/struct.Payload.html Returns an iterator over chunks of exactly chunk_size elements, starting from the end of the slice. Panics if chunk_size is zero. ```APIDOC ## rchunks_exact ### Description Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice. The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved from the `remainder` function of the iterator. ### Signature pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> ### Parameters - **chunk_size** (usize) - Required - The size of each chunk. ### Panics Panics if `chunk_size` is zero. ### Examples ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks_exact(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert!(iter.next().is_none()); assert_eq!(iter.remainder(), &['l']); ``` ```