### Buffer Initialization and Formatting Example (Rust) Source: https://docs.rs/const-hex/latest/const_hex/struct Demonstrates how to create a `Buffer` instance and use its `format` method to convert a byte array into its lower-case hexadecimal string representation. ```Rust let mut buffer = const_hex::Buffer::<4>::new(); let printed = buffer.format(b"1234"); assert_eq!(printed, "31323334"); ``` -------------------------------- ### Rust Example: Encoding String to Hex Source: https://docs.rs/const-hex/latest/const_hex/trait Demonstrates how to use the `ToHex` trait to encode a string into its hexadecimal representation. This example shows a common use case for the trait. ```Rust use hex::ToHex; println!("{}", "Hello world!".encode_hex::()); ``` -------------------------------- ### Buffer Initialization and Default in Rust Source: https://docs.rs/const-hex/latest/src/const_hex/buffer Provides the `new` and `default` methods for the Buffer struct. `new` creates a Buffer instance, initializing the prefix based on the `PREFIX` const generic and filling the byte array with zeros. `default` provides a convenient way to get a default Buffer. ```rust impl Default for Buffer { #[inline] fn default() -> Self { Self::new() } } impl Buffer { /// The length of the buffer in bytes. pub const LEN: usize = (N + PREFIX as usize) * 2; const ASSERT_SIZE: () = assert!(core::mem::size_of::() == 2 + N * 2, "invalid size"); const ASSERT_ALIGNMENT: () = assert!(core::mem::align_of::() == 1, "invalid alignment"); /// This is a cheap operation; you don't need to worry about reusing buffers /// for efficiency. #[inline] pub const fn new() -> Self { let () = Self::ASSERT_SIZE; let () = Self::ASSERT_ALIGNMENT; Self { prefix: if PREFIX { [b'0', b'x'] } else { [0, 0] }, bytes: [[0; 2]; N], } } } ``` -------------------------------- ### Rust Examples for ToHex Trait Usage Source: https://docs.rs/const-hex/latest/const_hex/traits/trait Demonstrates how to use the deprecated `ToHex` trait to encode a string into its hexadecimal representation, both in lowercase and uppercase. The examples show the expected output for the ASCII string 'Hello world!'. ```Rust #![allow(deprecated)] use const_hex::ToHex; assert_eq!("Hello world!".encode_hex::(), "48656c6c6f20776f726c6421"); assert_eq!("Hello world!".encode_hex_upper::(), "48656C6C6F20776F726C6421"); ``` -------------------------------- ### Serde Example: Struct with Hex Field Source: https://docs.rs/const-hex/latest/src/const_hex/serde Demonstrates how to use the `#[serde(with = "const_hex")]` attribute to automatically serialize and deserialize a `Vec` field as a hex string within a struct. ```rust # #[cfg(feature = "alloc")] { use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize)] struct Foo { #[serde(with = "const_hex")] bar: Vec, } # } ``` -------------------------------- ### Get Raw Pointer to Buffer (Rust) Source: https://docs.rs/const-hex/latest/src/const_hex/buffer Returns a const raw pointer to the buffer. The caller must ensure the buffer outlives the pointer. It calculates the pointer offset based on the `PREFIX` constant. ```Rust /// Returns a raw pointer to the buffer. /// /// The caller must ensure that the buffer outlives the pointer this /// function returns, or else it will end up pointing to garbage. #[inline] pub const fn as_ptr(&self) -> *const u8 { unsafe { (self as *const Self).cast::().add(!PREFIX as usize * 2) } } ``` -------------------------------- ### Get Mutable Raw Pointer to Buffer (Rust) Source: https://docs.rs/const-hex/latest/src/const_hex/buffer Returns a mutable raw pointer to the buffer's slice. The caller must ensure the slice outlives the pointer. It calculates the pointer offset based on the `PREFIX` constant. ```Rust /// Returns an unsafe mutable pointer to the slice's buffer. /// /// The caller must ensure that the slice outlives the pointer this /// function returns, or else it will end up pointing to garbage. #[inline] pub fn as_mut_ptr(&mut self) -> *mut u8 { unsafe { (self as *mut Self).cast::().add(!PREFIX as usize * 2) } } ``` -------------------------------- ### Get Buffer as Byte Slice (Rust) Source: https://docs.rs/const-hex/latest/src/const_hex/buffer Returns a const reference to the underlying bytes as a slice. This const method uses unsafe code to create the slice from a raw pointer, leveraging layout compatibility. ```Rust /// Returns a reference to the underlying bytes. #[inline] pub const fn as_bytes(&self) -> &[u8] { // SAFETY: [u16; N] is layout-compatible with [u8; N * 2]. unsafe { slice::from_raw_parts(self.as_ptr(), Self::LEN) } } ``` -------------------------------- ### Rust: Get Hex Character Lookup Table Source: https://docs.rs/const-hex/latest/src/const_hex/lib Returns a reference to a static array of 16 bytes representing hexadecimal characters ('0'-'9', 'a'-'f' or 'A'-'F'). The choice between lowercase and uppercase tables is determined by the `UPPER` const generic parameter. ```rust #[inline(always)] const fn get_chars_table() -> &'static [u8; 16] { if UPPER { HEX_CHARS_UPPER } else { HEX_CHARS_LOWER } } ``` -------------------------------- ### Get Buffer as Byte Array (Rust) Source: https://docs.rs/const-hex/latest/src/const_hex/buffer Returns a reference to the underlying stack-allocated byte array with a specified length. This const function includes a compile-time assertion to ensure the provided length matches the buffer's expected length. It uses unsafe code for casting the pointer, leveraging layout compatibility between [u16; N] and [u8; N * 2]. ```Rust /// Returns a reference to the underlying stack-allocated byte array. /// /// # Panics /// /// If `LEN` does not equal `Self::LEN`. /// /// This is panic is evaluated at compile-time if the `nightly` feature /// is enabled, as inline `const` blocks are currently unstable. /// /// See Rust tracking issue [#76001](https://github.com/rust-lang/rust/issues/76001). #[inline] pub const fn as_byte_array(&self) -> &[u8; LEN] { maybe_const_assert!(LEN == Self::LEN, "`LEN` must be equal to `Self::LEN`"); // SAFETY: [u16; N] is layout-compatible with [u8; N * 2]. unsafe { &*self.as_ptr().cast::<[u8; LEN]>() } } ``` -------------------------------- ### Implement PartialEq for FromHexError Source: https://docs.rs/const-hex/latest/const_hex/enum Shows the implementation of `PartialEq` for `FromHexError`, enabling comparison of error instances for equality and inequality. ```rust impl PartialEq for FromHexError Source #### fn eq(&self, other: &FromHexError) -> bool Tests for `self` and `other` values to be equal, and is used by `==`. 1.0.0 · Source #### fn ne(&self, other: &Rhs) -> bool Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. Source ``` -------------------------------- ### Buffer Constants and Methods (Rust) Source: https://docs.rs/const-hex/latest/const_hex/struct Details the `LEN` constant, `new` constructor, and various formatting methods (`const_format`, `const_format_upper`, `format`, `format_upper`, `format_slice`, `format_slice_upper`) for the `Buffer` struct. ```Rust pub const LEN: usize pub const fn new() -> Self pub const fn const_format(self, array: &[u8; N]) -> Self pub const fn const_format_upper(self, array: &[u8; N]) -> Self pub fn format(&mut self, array: &[u8; N]) -> &mut str pub fn format_upper(&mut self, array: &[u8; N]) -> &mut str pub fn format_slice>(&mut self, slice: T) -> &mut str pub fn format_slice_upper>(&mut self, slice: T) -> &mut str ``` -------------------------------- ### Get Mutable Buffer Excluding Prefix (Rust) Source: https://docs.rs/const-hex/latest/src/const_hex/buffer Returns a mutable reference to the underlying buffer, excluding the prefix bytes. This method is unsafe and requires the caller to ensure UTF-8 validity, similar to `as_mut_bytes`. ```Rust /// Returns a mutable reference to the underlying buffer, excluding the prefix. /// /// # Safety /// /// See [`as_mut_bytes`](Buffer::as_mut_bytes). #[inline] pub unsafe fn buffer(&mut self) -> &mut [u8] { unsafe { slice::from_raw_parts_mut(self.bytes.as_mut_ptr().cast(), N * 2) } } ``` -------------------------------- ### CloneToUninit Experimental Copy-Assignment Source: https://docs.rs/const-hex/latest/const_hex/struct Provides an experimental, nightly-only `clone_to_uninit` method for types implementing `Clone`. This method performs copy-assignment from `self` to a raw pointer `dest` in uninitialized memory. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Implement StructuralPartialEq for FromHexError Source: https://docs.rs/const-hex/latest/const_hex/enum Demonstrates the implementation of `StructuralPartialEq` for `FromHexError`, used for structural equality comparisons. ```rust impl StructuralPartialEq for FromHexError ``` -------------------------------- ### Implement Blanket Trait: CloneToUninit Source: https://docs.rs/const-hex/latest/const_hex/enum Shows the blanket implementation of the experimental `CloneToUninit` trait, facilitating copying data to uninitialized memory. ```rust impl CloneToUninit for T where T: Clone, Source #### unsafe fn clone_to_uninit(&self, dest: *mut u8) 🔬This is a nightly-only experimental API. (`clone_to_uninit`) Performs copy-assignment from `self` to `dest`. Read more Source ``` -------------------------------- ### Get Buffer as String Slice (Rust) Source: https://docs.rs/const-hex/latest/src/const_hex/buffer Returns a reference to the underlying bytes casted to a string slice. This method is inlined and uses an unsafe operation, assuming the buffer always contains valid UTF-8. ```Rust /// Returns a reference to the underlying bytes casted to a string slice. #[inline] pub const fn as_str(&self) -> &str { // SAFETY: The buffer always contains valid UTF-8. unsafe { str::from_utf8_unchecked(self.as_bytes()) } } ``` -------------------------------- ### Buffer Debug and AsRef Implementations in Rust Source: https://docs.rs/const-hex/latest/src/const_hex/buffer Implements `Debug` and `AsRef` for the Buffer struct. The `Debug` implementation formats the buffer as a tuple containing its string representation. The `AsRef` implementation provides a convenient way to access the hex-formatted string as a `&str`. ```rust impl fmt::Debug for Buffer { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_tuple("Buffer").field(&self.as_str()).finish() } } impl AsRef for Buffer { #[inline] fn as_ref(&self) -> &str { self.as_str() } } ``` -------------------------------- ### Buffer Trait Implementations (Rust) Source: https://docs.rs/const-hex/latest/const_hex/struct Shows implementations of standard Rust traits for the `Buffer` struct, including `AsRef`, `Clone`, and `Debug`, enabling common operations like string conversion and debugging. ```Rust impl AsRef for Buffer fn as_ref(&self) -> &str impl Clone for Buffer fn clone(&self) -> Buffer fn clone_from(&mut self, source: &Self) impl Debug for Buffer ``` -------------------------------- ### Get Mutable Buffer as Byte Slice (Rust) Source: https://docs.rs/const-hex/latest/src/const_hex/buffer Returns a mutable reference to the underlying bytes as a slice. This method requires `unsafe` due to direct memory manipulation and includes safety notes regarding UTF-8 validity. ```Rust /// Returns a mutable reference to the underlying bytes. /// /// # Safety /// /// The caller must ensure that the content of the slice is valid UTF-8 /// before the borrow ends and the underlying `str` is used. /// /// Use of a `str` whose contents are not valid UTF-8 is undefined behavior. #[inline] pub unsafe fn as_mut_bytes(&mut self) -> &mut [u8] { // SAFETY: [u16; N] is layout-compatible with [u8; N * 2]. unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), Self::LEN) } } ``` -------------------------------- ### Get Mutable Buffer as String Slice (Rust) Source: https://docs.rs/const-hex/latest/src/const_hex/buffer Returns a mutable reference to the underlying bytes casted to a string slice. This method is inlined and uses an unsafe operation, assuming the buffer always contains valid UTF-8. ```Rust /// Returns a mutable reference to the underlying bytes casted to a string /// slice. #[inline] pub fn as_mut_str(&mut self) -> &mut str { // SAFETY: The buffer always contains valid UTF-8. unsafe { str::from_utf8_unchecked_mut(self.as_mut_bytes()) } } ``` -------------------------------- ### Buffer Formatting Source: https://docs.rs/const-hex/latest/const_hex/struct Implements the `fmt` method for the `Buffer` type, allowing it to be formatted using a given `Formatter`. This is essential for displaying buffer contents in a human-readable format. ```rust fn fmt(&self, f: &mut Formatter<'_>) -> Result ``` -------------------------------- ### Get Mutable Buffer as Byte Array (Rust) Source: https://docs.rs/const-hex/latest/src/const_hex/buffer Returns a mutable reference to the underlying stack-allocated byte array with a specified length. This method includes a compile-time assertion for length matching and uses unsafe code for pointer casting, similar to `as_byte_array`. ```Rust /// Returns a mutable reference the underlying stack-allocated byte array. /// /// # Panics /// /// If `LEN` does not equal `Self::LEN`. /// /// See [`as_byte_array`](Buffer::as_byte_array) for more information. #[inline] pub fn as_mut_byte_array(&mut self) -> &mut [u8; LEN] { maybe_const_assert!(LEN == Self::LEN, "`LEN` must be equal to `Self::LEN`"); // SAFETY: [u16; N] is layout-compatible with [u8; N * 2]. unsafe { &mut *self.as_mut_ptr().cast::<[u8; LEN]>() } } ``` -------------------------------- ### Serde Integration with const_hex Source: https://docs.rs/const-hex/latest/const_hex/serde/index Demonstrates how to use the `const_hex` module with serde for serializing and deserializing byte vectors as hex strings. Requires the `serde` crate. ```rust use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize)] struct Foo { #[serde(with = "const_hex")] bar: Vec, } ``` -------------------------------- ### Implement Display for FromHexError Source: https://docs.rs/const-hex/latest/const_hex/enum Illustrates the implementation of the `Display` trait for `FromHexError`, providing a user-friendly string representation of the error. ```rust impl Display for FromHexError Source #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> Formats the value using the given formatter. Read more Source ``` -------------------------------- ### Rust: Strip 0x Prefix from Byte Slice Source: https://docs.rs/const-hex/latest/src/const_hex/lib A constant function that removes the "0x" prefix from a byte slice if it exists. If the slice starts with `b'0'` followed by `b'x'`, it returns a slice of the remaining bytes; otherwise, it returns the original slice. ```rust #[inline] const fn strip_prefix(bytes: &[u8]) -> &[u8] { match bytes { [b'0', b'x', rest @ ..] => rest, _ => bytes, } } ``` -------------------------------- ### Rust: Hex Encoding with `serde` (Serialization) Source: https://docs.rs/const-hex/latest/const_hex/index Handles hexadecimal encoding for types that are being serialized using the `serde` framework. This allows seamless integration with `serde`. ```Rust pub fn serialize(value: &T) -> impl serde::Serialize; ``` -------------------------------- ### FromHex Implementations Source: https://docs.rs/const-hex/latest/src/const_hex/traits Demonstrates how the `FromHex` trait is implemented for common types like `Vec`, `Box<[u8]>`, and fixed-size arrays `[u8; N]`. ```APIDOC ## Implementations of FromHex Trait ### Description This section details the implementations of the `FromHex` trait for various Rust types, including dynamically sized vectors and fixed-size arrays. ### `Vec` #### Method `from_hex>(hex: T) -> Result, crate::FromHexError>` #### Description Decodes a hexadecimal string into a `Vec`. #### Request Example ```rust use const_hex::FromHex; let bytes: Vec = >::from_hex("48656c6c6f")?; // bytes will be vec![72, 101, 108, 108, 111] ``` ### `Vec` #### Method `from_hex>(hex: T) -> Result, crate::FromHexError>` #### Description Decodes a hexadecimal string into a `Vec`. This involves a transmute operation after decoding to `Vec`. #### Request Example ```rust use const_hex::FromHex; let signed_bytes: Vec = >::from_hex("FF00")?; // signed_bytes will be vec![-1, 0] ``` ### `Box<[u8]>` #### Method `from_hex>(hex: T) -> Result, crate::FromHexError>` #### Description Decodes a hexadecimal string into a `Box<[u8]>`. #### Request Example ```rust use const_hex::FromHex; let boxed_bytes: Box<[u8]> = >::from_hex("0a0b0c")?; // boxed_bytes will be Box::new([10, 11, 12]) ``` ### `Box<[i8]>` #### Method `from_hex>(hex: T) -> Result, crate::FromHexError>` #### Description Decodes a hexadecimal string into a `Box<[i8]>`. #### Request Example ```rust use const_hex::FromHex; let boxed_signed_bytes: Box<[i8]> = >::from_hex("80")?; // boxed_signed_bytes will be Box::new([-128]) ``` ### `[u8; N]` (Generic Array) #### Method `from_hex>(hex: T) -> Result<[u8; N], crate::FromHexError>` #### Description Decodes a hexadecimal string into a fixed-size byte array `[u8; N]`. The length of the decoded hex string must match `N`. #### Request Example ```rust use const_hex::FromHex; let arr: [u8; 3] = <[u8; 3]>::from_hex("010203")?; // arr will be [1, 2, 3] ``` ### `[i8; N]` (Generic Signed Array) #### Method `from_hex>(hex: T) -> Result<[i8; N], crate::FromHexError>` #### Description Decodes a hexadecimal string into a fixed-size signed byte array `[i8; N]`. #### Request Example ```rust use const_hex::FromHex; let signed_arr: [i8; 2] = <[i8; 2]>::from_hex("8180")?; // signed_arr will be [129, -128] (Note: 129 in u8 is -127 in i8, but here it's raw byte interpretation) ``` ### `Box` where `T: FromHex` #### Method `from_hex>(hex: U) -> Result, Self::Error>` #### Description Decodes a hexadecimal string and returns it wrapped in a `Box`. ### `Cow<'_, T>` where `T: ToOwned + ?Sized` and `T::Owned: FromHex` #### Method `from_hex>(hex: U) -> Result, Self::Error>` #### Description Decodes a hexadecimal string into an owned `Cow`. ### `Rc` where `T: FromHex` #### Method `from_hex>(hex: U) -> Result, Self::Error>` #### Description Decodes a hexadecimal string and returns it wrapped in an `Rc`. ### `Arc` where `T: FromHex` #### Method `from_hex>(hex: U) -> Result, Self::Error>` #### Description Decodes a hexadecimal string and returns it wrapped in an `Arc`. ``` -------------------------------- ### Rust: Fuzzing Utilities for Hex Encoding/Decoding Source: https://docs.rs/const-hex/latest/src/const_hex/lib Provides fuzzing functions (`fuzz`, `encode`, `decode`) for testing hex encoding and decoding logic. These functions use `proptest` to generate test cases and assert correctness against expected outputs and round-trip conversions. They are conditionally compiled under the `__fuzzing` feature flag and exclude Miri testing. ```rust #[allow( missing_docs, unused, clippy::all, clippy::missing_inline_in_public_items )] #[cfg(all(feature = "__fuzzing", not(miri)))] #[doc(hidden)] pub mod fuzzing { use super::*; use proptest::test_runner::TestCaseResult; use proptest::{prop_assert, prop_assert_eq}; use std::fmt::Write; pub fn fuzz(data: &[u8]) -> TestCaseResult { self::encode(&data)?; self::decode(&data)?; Ok(()) } pub fn encode(input: &[u8]) -> TestCaseResult { test_buffer::<8, 16>(input)?; test_buffer::<20, 40>(input)?; test_buffer::<32, 64>(input)?; test_buffer::<64, 128>(input)?; test_buffer::<128, 256>(input)?; let encoded = crate::encode(input); let expected = mk_expected(input); prop_assert_eq!(&encoded, &expected); let decoded = crate::decode(&encoded).unwrap(); prop_assert_eq!(decoded, input); Ok(()) } pub fn decode(input: &[u8]) -> TestCaseResult { if let Ok(decoded) = crate::decode(input) { let input_len = strip_prefix(input).len() / 2; prop_assert_eq!(decoded.len(), input_len); } Ok(()) } fn mk_expected(bytes: &[u8]) -> String { let mut s = String::with_capacity(bytes.len() * 2); ``` -------------------------------- ### const-hex Buffer API Source: https://docs.rs/const-hex/latest/const_hex/struct This section details the Buffer struct and its associated methods for formatting byte slices into hexadecimal strings. ```APIDOC ## Struct Buffer ### Description A correctly sized stack allocation for the formatted bytes to be written into. `N` is the amount of bytes of the input, while `PREFIX` specifies whether the “0x” prefix is prepended to the output. Note that this buffer will contain only the prefix, if specified, and null (‘\0’) bytes before any formatting is done. ### Examples ```rust let mut buffer = const_hex::Buffer::<4>::new(); let printed = buffer.format(b"1234"); assert_eq!(printed, "31323334"); ``` ## Implementations ### impl Buffer #### `pub const LEN: usize` The length of the buffer in bytes. #### `pub const fn new() -> Self` This is a cheap operation; you don’t need to worry about reusing buffers for efficiency. #### `pub const fn const_format(self, array: &[u8; N]) -> Self` Print an array of bytes into this buffer. #### `pub const fn const_format_upper(self, array: &[u8; N]) -> Self` Print an array of bytes into this buffer. #### `pub fn format(&mut self, array: &[u8; N]) -> &mut str` Print an array of bytes into this buffer and return a reference to its _lower_ hex string representation within the buffer. #### `pub fn format_upper(&mut self, array: &[u8; N]) -> &mut str` Print an array of bytes into this buffer and return a reference to its _upper_ hex string representation within the buffer. #### `pub fn format_slice>(&mut self, slice: T) -> &mut str` Print a slice of bytes into this buffer and return a reference to its _lower_ hex string representation within the buffer. ##### Panics If the slice is not exactly `N` bytes long. #### `pub fn format_slice_upper>(&mut self, slice: T) -> &mut str` Print a slice of bytes into this buffer and return a reference to its _upper_ hex string representation within the buffer. ##### Panics If the slice is not exactly `N` bytes long. #### `pub fn to_string(&self) -> String` Available on **crate feature`alloc`** only. Copies `self` into a new owned `String`. #### `pub const fn as_str(&self) -> &str` Returns a reference to the underlying bytes casted to a string slice. #### `pub fn as_mut_str(&mut self) -> &mut str` Returns a mutable reference to the underlying bytes casted to a string slice. #### `pub fn to_vec(&self) -> Vec` Available on **crate feature`alloc`** only. Copies `self` into a new `Vec`. #### `pub const fn as_byte_array(&self) -> &[u8; LEN]` Returns a reference the underlying stack-allocated byte array. ##### Panics If `LEN` does not equal `Self::LEN`. This is panic is evaluated at compile-time if the `nightly` feature is enabled, as inline `const` blocks are currently unstable. See Rust tracking issue #76001. #### `pub fn as_mut_byte_array(&mut self) -> &mut [u8; LEN]` Returns a mutable reference the underlying stack-allocated byte array. ##### Panics If `LEN` does not equal `Self::LEN`. See `as_byte_array` for more information. #### `pub const fn as_bytes(&self) -> &[u8]` Returns a reference to the underlying bytes. #### `pub unsafe fn as_mut_bytes(&mut self) -> &mut [u8]` Returns a mutable reference to the underlying bytes. ##### Safety The caller must ensure that the content of the slice is valid UTF-8 before the borrow ends and the underlying `str` is used. Use of a `str` whose contents are not valid UTF-8 is undefined behavior. #### `pub unsafe fn buffer(&mut self) -> &mut [u8]` Returns a mutable reference to the underlying buffer, excluding the prefix. ##### Safety See `as_mut_bytes`. #### `pub const fn as_ptr(&self) -> *const u8` Returns a raw pointer to the buffer. The caller must ensure that the buffer outlives the pointer this function returns, or else it will end up pointing to garbage. #### `pub fn as_mut_ptr(&mut self) -> *mut u8` Returns an unsafe mutable pointer to the slice’s buffer. The caller must ensure that the slice outlives the pointer this function returns, or else it will end up pointing to garbage. ### Trait Implementations #### `impl AsRef for Buffer` ##### `fn as_ref(&self) -> &str` Converts this type into a shared reference of the (usually inferred) input type. #### `impl Clone for Buffer` ##### `fn clone(&self) -> Buffer` Returns a duplicate of the value. Read more 1.0.0 · Source ##### `fn clone_from(&mut self, source: &Self)` Performs copy-assignment from `source`. Read more #### `impl Debug for Buffer` ``` -------------------------------- ### Implement Debug for FromHexError Source: https://docs.rs/const-hex/latest/const_hex/enum Shows the implementation of the `Debug` trait for `FromHexError`, enabling formatted output for debugging purposes. ```rust impl Debug for FromHexError Source #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> Formats the value using the given formatter. Read more Source ``` -------------------------------- ### Rust: Create uninitialized array Source: https://docs.rs/const-hex/latest/src/const_hex/impl_core Provides a const function `uninit_array` to create an array of `MaybeUninit` of a specified size `N`. It leverages `MaybeUninit::uninit().assume_init()` for safety. ```rust /// `MaybeUninit::uninit_array` #[inline] pub(crate) const fn uninit_array() -> [MaybeUninit; N] { // SAFETY: An uninitialized `[MaybeUninit<_>; N]` is valid. unsafe { MaybeUninit::<[MaybeUninit; N]>::uninit().assume_init() } ``` -------------------------------- ### Rust: Serde Integration for Hexadecimal Data Source: https://docs.rs/const-hex/latest/const_hex/all Provides Serde serialization and deserialization capabilities for hexadecimal data. This allows seamless integration with data formats that use hexadecimal representations for binary data, simplifying data interchange. ```Rust mod serde { fn deserialize<'de, T>(deserializer: D) -> Result::Error>; fn serialize(value: &T, serializer: S) -> Result; fn serialize_upper(value: &T, serializer: S) -> Result; } ``` -------------------------------- ### Rust: Hex Encoding with `serde` (Uppercase Serialization) Source: https://docs.rs/const-hex/latest/const_hex/index Handles uppercase hexadecimal encoding for types being serialized with `serde`. This provides an alternative output format for `serde` integration. ```Rust pub fn serialize_upper(value: &T) -> impl serde::Serialize; ``` -------------------------------- ### Buffer Conversion and Access Methods (Rust) Source: https://docs.rs/const-hex/latest/const_hex/struct Provides methods for converting the buffer's content to a `String` (`to_string`), accessing it as a string slice (`as_str`, `as_mut_str`), and retrieving the underlying byte arrays (`as_byte_array`, `as_mut_byte_array`). ```Rust pub fn to_string(&self) -> String pub const fn as_str(&self) -> &str pub fn as_mut_str(&mut self) -> &mut str pub fn to_vec(&self) -> Vec pub const fn as_byte_array(&self) -> &[u8; LEN] pub fn as_mut_byte_array(&mut self) -> &mut [u8; LEN] ``` -------------------------------- ### Test Hex Buffer Formatting in Rust Source: https://docs.rs/const-hex/latest/src/const_hex/lib Tests the `Buffer` struct's ability to format byte slices into hexadecimal strings, both with and without a '0x' prefix. It verifies string lengths, content, and equivalence with expected outputs, also testing decoding functions. ```Rust fn test_buffer(bytes: &[u8]) -> TestCaseResult { if let Ok(bytes) = <&[u8; N]>::try_from(bytes) { let mut buffer = Buffer::::new(); let string = buffer.format(bytes).to_string(); prop_assert_eq!(string.len(), bytes.len() * 2); prop_assert_eq!(string.as_bytes(), buffer.as_byte_array::()); prop_assert_eq!(string.as_str(), buffer.as_str()); prop_assert_eq!(string.as_str(), mk_expected(bytes)); let mut buffer = Buffer::::new(); let prefixed = buffer.format(bytes).to_string(); prop_assert_eq!(prefixed.len(), 2 + bytes.len() * 2); prop_assert_eq!(prefixed.as_str(), buffer.as_str()); prop_assert_eq!(prefixed.as_str(), format!("0x{string}")); prop_assert_eq!(decode_to_array(&string), Ok(*bytes)); prop_assert_eq!(decode_to_array(&prefixed), Ok(*bytes)); prop_assert_eq!(const_decode_to_array(string.as_bytes()), Ok(*bytes)); prop_assert_eq!(const_decode_to_array(prefixed.as_bytes()), Ok(*bytes)); } Ok(()) } ``` -------------------------------- ### Implement Blanket Trait: VZip Source: https://docs.rs/const-hex/latest/const_hex/enum Details the blanket implementation of the `VZip` trait, used for zipping multiple lanes of data together. ```rust impl VZip for T where V: MultiLane, Source #### fn vzip(self) -> V ``` -------------------------------- ### Buffer Pointer and Slice Access (Rust) Source: https://docs.rs/const-hex/latest/const_hex/struct Includes methods for obtaining raw pointers (`as_ptr`, `as_mut_ptr`) and direct mutable access to the underlying byte buffer (`buffer`) for advanced manipulation. ```Rust pub const fn as_ptr(&self) -> *const u8 pub fn as_mut_ptr(&mut self) -> *mut u8 pub unsafe fn buffer(&mut self) -> &mut [u8] ``` -------------------------------- ### Implement Clone for FromHexError Source: https://docs.rs/const-hex/latest/const_hex/enum Demonstrates the implementation of the `Clone` trait for the `FromHexError` enum. This allows `FromHexError` instances to be duplicated. ```rust impl Clone for FromHexError Source #### fn clone(&self) -> FromHexError Returns a duplicate of the value. Read more 1.0.0 · Source #### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more Source ``` -------------------------------- ### Implement Blanket Trait: TryFrom Source: https://docs.rs/const-hex/latest/const_hex/enum Illustrates the blanket implementation of the `TryFrom` trait, enabling fallible conversions from type `U` to `T`. ```rust impl TryFrom for T where U: Into, Source #### type Error = Infallible The type returned in the event of a conversion error. Source #### fn try_from(value: U) -> Result>::Error> Performs the conversion. Source ``` -------------------------------- ### Rust: Hex Decoding with `serde` (Deserialization) Source: https://docs.rs/const-hex/latest/const_hex/index Handles hexadecimal decoding for types being deserialized using the `serde` framework. This enables `serde` to parse hex strings into target types. ```Rust pub fn deserialize<'de, T: FromHex + Deserialize<'de>>(deserializer: &'de D) -> Result; ``` -------------------------------- ### TryFrom Type Conversion Source: https://docs.rs/const-hex/latest/const_hex/struct Implements `TryFrom` for types `T` from `U`, where `U` implements `Into`. The `try_from` method attempts the conversion, returning a `Result` which is `Ok(T)` on success or an `Err` containing an `Infallible` error type on failure. ```rust type Error = Infallible ``` ```rust fn try_from(value: U) -> Result>::Error> ``` -------------------------------- ### Rust: Hex Encoding with `fmt` Traits Source: https://docs.rs/const-hex/latest/const_hex/index Provides a value that can be formatted using the standard Rust `fmt` traits, likely for displaying hex representations. ```Rust pub fn display<'a, T: ToHex + ?Sized>(value: &'a T) -> impl fmt::Display + 'a; ``` -------------------------------- ### TryInto Type Conversion Source: https://docs.rs/const-hex/latest/const_hex/struct Implements `TryInto` for types `T` to `U`, where `U` implements `TryFrom`. The `try_into` method attempts the conversion, returning a `Result` with the conversion error type defined by `U`'s `TryFrom` implementation. ```rust type Error = >::Error ``` ```rust fn try_into(self) -> Result>::Error> ``` -------------------------------- ### Implement Error for FromHexError Source: https://docs.rs/const-hex/latest/const_hex/enum Details the implementation of the standard `Error` trait for `FromHexError`, providing methods like `source` and deprecated methods like `description` and `cause`. ```rust impl Error for FromHexError 1.30.0 · Source #### fn source(&self) -> Option<&(dyn Error + 'static)> Returns the lower-level source of this error, if any. Read more 1.0.0 · Source #### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to_string() Read more 1.0.0 · Source #### fn cause(&self) -> Option<&dyn Error> 👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting Source #### fn provide<'a>(&'a self, request: &mut Request<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access`) Provides type-based access to context intended for error reports. Read more Source ``` -------------------------------- ### Rust Trait and Implementations for Output Buffering Source: https://docs.rs/const-hex/latest/src/const_hex/output Defines an internal `Output` trait in Rust for abstracting over different output buffer types. It includes methods for writing bytes and checking remaining capacity. Implementations are provided for mutable byte slices (`&mut [u8]`) and mutable formatters (`&mut fmt::Formatter<'_>`). The byte slice implementation directly copies data and updates the slice, while the formatter implementation handles writing strings and individual characters, with debug assertions for UTF-8 validity. ```Rust use core::fmt::{self, Write}; /// Internal trait for abstracting over output buffer types. pub(crate) trait Output { fn write(&mut self, bytes: &[u8]); #[inline] fn write_byte(&mut self, byte: u8) { self.write(&[byte]) } #[inline] fn remaining(&self) -> Option { None } } impl Output for &mut [u8] { #[inline] fn write(&mut self, bytes: &[u8]) { let src = bytes.as_ptr(); let dst = self.as_mut_ptr(); let count = bytes.len(); debug_assert!(self.len() >= count); unsafe { dst.copy_from_nonoverlapping(src, count); *self = core::slice::from_raw_parts_mut(dst.add(count), self.len() - count); } } #[inline] fn remaining(&self) -> Option { Some(self.len()) } } impl Output for &mut fmt::Formatter<'_> { #[inline] fn write(&mut self, bytes: &[u8]) { if cfg!(debug_assertions) { core::str::from_utf8(bytes).unwrap(); } let _ = self.write_str(unsafe { core::str::from_utf8_unchecked(bytes) }); } #[inline] fn write_byte(&mut self, byte: u8) { let _ = self.write_char(byte as char); } } ``` -------------------------------- ### Implement Blanket Trait: ToString Source: https://docs.rs/const-hex/latest/const_hex/enum Details the blanket implementation of the `ToString` trait, allowing conversion of types that implement `Display` into `String` objects. ```rust impl ToString for T where T: Display + ?Sized, Source #### fn to_string(&self) -> String Converts the given value to a `String`. Read more Source ``` -------------------------------- ### Hex Serialization and Deserialization Functions Source: https://docs.rs/const-hex/latest/const_hex/serde/index Provides functions for serializing raw bytes into hex strings (both lowercase and uppercase) and deserializing hex strings back into raw bytes using the `const-hex` crate. ```rust # Deserializes a hex string into raw bytes. fn deserialize(hex_string: &str) -> Result, Error> { ... } # Serializes `data` as hex string using lowercase characters. fn serialize(data: &[u8]) -> String { ... } # Serializes `data` as hex string using uppercase characters. fn serialize_upper(data: &[u8]) -> String { ... } ``` -------------------------------- ### Serde Serialization with const-hex (Lowercase) Source: https://docs.rs/const-hex/latest/src/const_hex/serde Serializes a byte slice into a lowercase hex string using Serde. The output string is prefixed and its length is twice the input data's length. ```rust /// Serializes `data` as hex string using lowercase characters. /// /// Lowercase characters are used (e.g. `f9b4ca`). The resulting string's length /// is always even, each byte in data is always encoded using two hex digits. /// Thus, the resulting string contains exactly twice as many bytes as the input /// data. #[inline] pub fn serialize(data: T, serializer: S) -> Result where S: Serializer, T: AsRef<[u8]>, { serializer.serialize_str(&crate::encode_prefixed(data.as_ref())) } ``` -------------------------------- ### Implement Blanket Trait: Any Source: https://docs.rs/const-hex/latest/const_hex/enum Shows the blanket implementation of the `Any` trait for any type `T`, allowing runtime type identification. ```rust impl Any for T where T: 'static + ?Sized, Source #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more Source ``` -------------------------------- ### Implement Blanket Trait: From Source: https://docs.rs/const-hex/latest/const_hex/enum Demonstrates the blanket implementation of the `From` trait, allowing conversion from a type `T` to itself. ```rust impl From for T Source #### fn from(t: T) -> T Returns the argument unchanged. Source ``` -------------------------------- ### Rust: Initialize array from MaybeUninit array Source: https://docs.rs/const-hex/latest/src/const_hex/impl_core Provides an unsafe function `array_assume_init` to convert an array of `MaybeUninit` into an array of `T`. It relies on the caller ensuring all elements are initialized and uses `transpose` for safe conversion. ```rust /// `MaybeUninit::array_assume_init` #[inline] pub(crate) unsafe fn array_assume_init(array: [MaybeUninit; N]) -> [T; N] { // SAFETY: // * The caller guarantees that all elements of the array are initialized // * `MaybeUninit` and T are guaranteed to have the same layout // * `MaybeUninit` does not drop, so there are no double-frees // And thus the conversion is safe unsafe { transpose(array).assume_init() } ``` -------------------------------- ### Rust: FromHex and ToHex Traits Source: https://docs.rs/const-hex/latest/const_hex/all Introduces traits for converting between byte slices and hexadecimal string representations. The `FromHex` trait facilitates decoding, while the `ToHex` trait handles encoding. These traits are fundamental for integrating with other parts of the library. ```Rust trait FromHex { type Error; fn from_hex(hex: &str) -> Result; } trait ToHex { fn to_hex(&self) -> String; fn to_hex_bytes(&self) -> Vec; } ```