### Example Searches Source: https://docs.rs/rkyv/latest/src/rkyv/impls/alloc/collections/btree_map.rs.html?search= These are example search queries for common Rust patterns and types. They can be used as starting points for exploring the codebase or documentation. ```text Example searches: * std::vec * u32 -> bool * Option, (T -> U) -> Option ``` ```text Example searches: * std::vec * u32 -> bool * Option, (T -> U) -> Option ``` ```text Example searches: * std::vec * u32 -> bool * Option, (T -> U) -> Option ``` -------------------------------- ### String Length Example Source: https://docs.rs/rkyv/latest/rkyv/string/struct.ArchivedString.html?search= Demonstrates how to get the byte length of a string, including examples with multi-byte characters. ```rust let len = "foo".len(); assert_eq!(3, len); assert_eq!("ƒoo".len(), 4); // fancy f! assert_eq!("ƒoo".chars().count(), 3); ``` -------------------------------- ### NicheInto Example: Space Saving with Option Source: https://docs.rs/rkyv/latest/rkyv/with/struct.NicheInto.html?search= Demonstrates how NicheInto can save space by niching Option types. It compares the size of a basic example with a niched example, showing that the niched version is smaller. ```rust use core::mem::size_of; use rkyv::{ niche::niching::{NaN, Null}, with::NicheInto, Archive, Archived, }; #[derive(Archive)] struct BasicExample { maybe_box: Option>, maybe_non_nan: Option, } #[derive(Archive)] struct NichedExample { #[rkyv(with = NicheInto)] maybe_box: Option>, #[rkyv(with = NicheInto)] maybe_non_nan: Option, } assert!( size_of::>() > size_of::>() ); ``` -------------------------------- ### Example Search: Option mapping Source: https://docs.rs/rkyv/latest/rkyv/string/repr/union.ArchivedStringRepr.html?search= An example search query for mapping a function over an `Option`. ```text Option, (T -> U) -> Option ``` -------------------------------- ### Example Search: u32 to bool Source: https://docs.rs/rkyv/latest/rkyv/string/repr/union.ArchivedStringRepr.html?search= An example search query demonstrating a type conversion from `u32` to `bool`. ```text u32 -> bool ``` -------------------------------- ### Example: Using access_pos_mut for Mutable Access Source: https://docs.rs/rkyv/latest/rkyv/api/low/fn.access_pos_mut.html?search=std%3A%3Avec Demonstrates how to use `access_pos_mut` to obtain mutable access to archived data within a byte slice, allowing in-place modifications. This example requires several imports and setup for serialization and archiving. ```rust use core::mem::MaybeUninit; use rkyv:: api::{root_position, low::{to_bytes_in_with_alloc, access_pos_mut}}, rancor::Failure, ser::{allocator::SubAllocator, writer::Buffer}, util::Align, with::InlineAsBox, Archive, Serialize, munge::munge; let mut output = Align([MaybeUninit::::uninit(); 256]); let mut alloc = [MaybeUninit::::uninit(); 256]; #[derive(Archive, Serialize)] struct Example { inner: i32, } let value = Example { inner: 42 }; let mut bytes = to_bytes_in_with_alloc::<_, _, Failure>( &value, Buffer::from(&mut *output), SubAllocator::new(&mut alloc), ) .unwrap(); let root_pos = root_position::(bytes.len()); let mut archived = access_pos_mut::( &mut *bytes, root_pos, ).unwrap(); // Because the access is mutable, we can mutate the archived data munge!(let ArchivedExample { mut inner, .. } = archived); assert_eq!(*inner, 42); *inner = 12345.into(); assert_eq!(*inner, 12345); ``` -------------------------------- ### Example Usage of access_pos Source: https://docs.rs/rkyv/latest/rkyv/api/low/fn.access_pos.html?search=u32+-%3E+bool Demonstrates how to use access_pos to safely access archived data from a byte slice. This example requires the 'bytecheck' feature and involves serialization and deserialization setup. ```rust use core::mem::MaybeUninit; use rkyv:: api:: low::{access_pos, to_bytes_in_with_alloc}, root_position, }, rancor::Failure, ser:: allocator::SubAllocator, writer::Buffer, }, util::Align, with::InlineAsBox, Archive, Serialize, }; let mut output = Align([MaybeUninit::::uninit(); 256]); let mut alloc = [MaybeUninit::::uninit(); 256]; #[derive(Archive, Serialize)] struct Example<'a> { #[rkyv(with = InlineAsBox)] inner: &'a i32, } let forty_two = 42; let value = Example { inner: &forty_two }; let bytes = to_bytes_in_with_alloc::<_, _, Failure>( &value, Buffer::from(&mut *output), SubAllocator::new(&mut alloc), ) .unwrap(); let archived = access_pos::, Failure>( &*bytes, root_position::>(bytes.len()), ) .unwrap(); assert_eq!(*archived.inner, 42); ``` -------------------------------- ### Example: Deserializing with from_bytes Source: https://docs.rs/rkyv/latest/rkyv/api/low/fn.from_bytes.html?search= Demonstrates how to use `from_bytes` for safe deserialization. This example serializes a struct `Example` into bytes using `to_bytes_in_with_alloc` and then deserializes it back using `from_bytes`, asserting equality. ```rust use core::mem::MaybeUninit; use rkyv:: api::low::{from_bytes, to_bytes_in_with_alloc}, rancor::Failure, ser::{allocator::SubAllocator, writer::Buffer}, util::Align, Archive, Deserialize, Serialize, ; let mut output = Align([MaybeUninit::::uninit(); 256]); let mut alloc = [MaybeUninit::::uninit(); 256]; #[derive(Archive, Serialize, Deserialize, PartialEq, Debug)] struct Example { inner: i32, } let value = Example { inner: 42 }; let bytes = to_bytes_in_with_alloc::<_, _, Failure>( &value, Buffer::from(&mut *output), SubAllocator::new(&mut alloc), ) .unwrap(); let deserialized = from_bytes::(&*bytes).unwrap(); assert_eq!(value, deserialized); ``` -------------------------------- ### Example Searches Source: https://docs.rs/rkyv/latest/src/rkyv/traits.rs.html?search= Provides example search queries for exploring the rs_rkyv project's functionality. ```APIDOC ### Example Searches - `std::vec` - `u32 -> bool` - `Option, (T -> U) -> Option` ``` -------------------------------- ### Example Search: std::vec Source: https://docs.rs/rkyv/latest/rkyv/string/repr/union.ArchivedStringRepr.html?search= An example search query for the `std::vec` module. ```text std::vec ``` -------------------------------- ### Manual ArchiveUnsized Implementation Example Source: https://docs.rs/rkyv/latest/src/rkyv/traits.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example demonstrating how to manually implement `ArchiveUnsized` for a custom unsized type `Block`. ```APIDOC ## ArchivePointee for Block ### Description Defines the metadata for `Block` when used as an unsized type. This is necessary because pointers to unsized types need to store extra information. ### Associated Types - `ArchivedMetadata`: The metadata type for the archived version of `Block`, typically derived from the trailing slice's metadata. ### Methods - `pointer_metadata(metadata: &Self::ArchivedMetadata) -> ::Metadata`: Converts the archived metadata into the native pointer metadata. ## ArchiveUnsized for Block ### Description Manual implementation of `ArchiveUnsized` for `Block`, allowing it to be archived as an unsized type. ### Associated Types - `Archived`: The archived representation of `Block`, which is `Block, [Archived]>`. ### Methods - `archived_metadata(&self) -> ArchivedMetadata`: Returns the archived metadata for the `Block`, which is derived from the tail's metadata. ``` -------------------------------- ### Example: Deserializing with from_bytes_unchecked Source: https://docs.rs/rkyv/latest/rkyv/api/low/fn.from_bytes_unchecked.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates deserializing an `Example` struct from bytes using `from_bytes_unchecked`. This example requires setting up an output buffer, an allocator, and serializing the struct first using `to_bytes_in_with_alloc`. Ensure the byte slice is valid before using this function. ```rust use core::mem::MaybeUninit; use rkyv:: access_unchecked, api::low::{from_bytes_unchecked, to_bytes_in_with_alloc}, rancor::Failure, ser::{allocator::SubAllocator, writer::Buffer}, util::Align, with::InlineAsBox, Archive, Deserialize, Serialize, ; let mut output = Align([MaybeUninit::::uninit(); 256]); let mut alloc = [MaybeUninit::::uninit(); 256]; #[derive(Archive, Serialize, Deserialize, Debug, PartialEq)] struct Example { inner: i32, } let value = Example { inner: 42 }; let bytes = to_bytes_in_with_alloc::<_, _, Failure>( &value, Buffer::from(&mut *output), SubAllocator::new(&mut alloc), ) .unwrap(); let deserialized = unsafe { from_bytes_unchecked::(&*bytes).unwrap() }; assert_eq!(value, deserialized); ``` -------------------------------- ### MapNiche Example Source: https://docs.rs/rkyv/latest/rkyv/with/struct.MapNiche.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example demonstrating the usage of MapNiche with Option and AsBox. ```APIDOC ## §Example ```rust use rkyv::{ with::{AsBox, MapNiche}, Archive, Serialize, }; #[derive(Archive, Serialize)] struct BasicExample { option: Option, } #[derive(Archive, Serialize)] struct NichedExample { #[rkyv(with = MapNiche)] option: Option, } #[derive(Archive, Serialize)] struct HugeType([u8; 1024]); let basic_value = BasicExample { option: None }; let basic_bytes = rkyv::to_bytes(&basic_value)?; assert_eq!(basic_bytes.len(), 1 + 1024); let niched_value = NichedExample { option: None }; let niched_bytes = rkyv::to_bytes(&niched_value)?; assert_eq!(niched_bytes.len(), 4); // size_of::>() ``` ``` -------------------------------- ### Is empty example Source: https://docs.rs/rkyv/latest/rkyv/ffi/struct.ArchivedCString.html?search=u32+-%3E+bool Examples demonstrating the usage of `is_empty` for both non-empty and empty C strings. ```rust assert!(!c"foo".is_empty()); assert!(c"".is_empty()); ``` -------------------------------- ### MapNiche Struct and Example Source: https://docs.rs/rkyv/latest/rkyv/with/struct.MapNiche.html Demonstrates the structure of MapNiche and provides a practical example of its usage with Option types and custom wrappers like AsBox. ```APIDOC ## Struct MapNiche ### Description A wrapper that first applies another wrapper `W` to the value inside an `Option` and then niches the result based on the `Niching` `N`. ### Example ```rust use rkyv::{ with::{AsBox, MapNiche}, Archive, Serialize, }; #[derive(Archive, Serialize)] struct BasicExample { option: Option, } #[derive(Archive, Serialize)] struct NichedExample { #[rkyv(with = MapNiche)] option: Option, } #[derive(Archive, Serialize)] struct HugeType([u8; 1024]); let basic_value = BasicExample { option: None }; let basic_bytes = rkyv::to_bytes(&basic_value)?; assert_eq!(basic_bytes.len(), 1 + 1024); let niched_value = NichedExample { option: None }; let niched_bytes = rkyv::to_bytes(&niched_value)?; assert_eq!(niched_bytes.len(), 4); // size_of::>() ``` ``` -------------------------------- ### Start Sharing for Strategy Source: https://docs.rs/rkyv/latest/rkyv/api/high/type.HighValidator.html?search=u32+-%3E+bool Starts sharing the value associated with the given address. This is part of the Sharing implementation for Strategy. ```rust fn start_sharing(&mut self, address: usize) -> SharingState ``` -------------------------------- ### Example Usage Source: https://docs.rs/rkyv/latest/rkyv/with/struct.Map.html?search=std%3A%3Avec Demonstrates how to use the Map wrapper with the `#[rkyv(with = ...)]` attribute for options and vectors. ```APIDOC ## Example ```rust use rkyv({ with::{InlineAsBox, Map}, Archive, }); #[derive(Archive)] struct Example<'a> { // This will apply `InlineAsBox` to the `&i32` contained in this option #[rkyv(with = Map)] option: Option<&'a i32>, // This will apply `InlineAsBox` to each `&i32` contained in this vector #[rkyv(with = Map)] vec: Vec<&'a i32>, } ``` ``` -------------------------------- ### String Get Subslice Example Source: https://docs.rs/rkyv/latest/rkyv/string/struct.ArchivedString.html?search= Illustrates safely getting a subslice of a string using the `get` method, handling invalid indices. ```rust let v = String::from("🗻∈🌏"); assert_eq!(Some("🗻"), v.get(0..4)); // indices not on UTF-8 sequence boundaries assert!(v.get(1..).is_none()); assert!(v.get(..8).is_none()); // out of bounds assert!(v.get(..42).is_none()); ``` -------------------------------- ### Example of creating ArchivedOption Source: https://docs.rs/rkyv/latest/rkyv/option/enum.ArchivedOption.html?search= Demonstrates creating an ArchivedOption::Some with a value. ```rust let o: ArchivedOption = ArchivedOption::from(67); assert!(matches!(o, ArchivedOption::Some(67))); ``` -------------------------------- ### Get Start Bound of ArchivedRangeFrom Source: https://docs.rs/rkyv/latest/rkyv/ops/struct.ArchivedRangeFrom.html?search=std%3A%3Avec Returns the start bound of the range as a reference to T. This is part of the RangeBounds trait implementation. ```rust fn start_bound(&self) -> Bound<&T> ``` -------------------------------- ### start_sharing Method Source: https://docs.rs/rkyv/latest/rkyv/ser/sharing/trait.Sharing.html Starts the sharing process for a value associated with a given address. Returns the current sharing state. ```rust fn start_sharing(&mut self, address: usize) -> SharingState; ``` -------------------------------- ### Example Usage of AsUnixTime Source: https://docs.rs/rkyv/latest/rkyv/with/struct.AsUnixTime.html Demonstrates how to use the AsUnixTime wrapper with the `rkyv` derive macro to archive a SystemTime field. Ensure the `std` feature is enabled for this functionality. ```rust use rkyv::{Archive, with::AsUnixTime}; use std::time::SystemTime; #[derive(Archive)] struct Example { #[rkyv(with = AsUnixTime)] time: SystemTime, } ``` -------------------------------- ### Example of using access_unchecked_mut Source: https://docs.rs/rkyv/latest/rkyv/fn.access_unchecked_mut.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This example shows how to use `access_unchecked_mut` to get a mutable reference to archived data and then modify it. Ensure the data is valid before using this function. ```rust use rkyv::{ to_bytes, access_unchecked_mut, util::Align, munge::munge, Archive, Serialize, Deserialize, rancor::Error, }; #[derive(Archive, Serialize, Deserialize)] struct Example { name: String, value: i32, } let value = Example { name: "pi".to_string(), value: 31415926, }; let mut bytes = to_bytes::(&value).unwrap(); let mut archived = unsafe { access_unchecked_mut::(&mut *bytes) }; assert_eq!(archived.name, "pi"); assert_eq!(archived.value, 31415926); // Because the access is mutable, we can mutate the archived data munge!(let ArchivedExample { mut value, .. } = archived); assert_eq!(*value, 31415926); *value = 12345.into(); assert_eq!(*value, 12345); ``` -------------------------------- ### Manual Unsizing and Serialization Example Source: https://docs.rs/rkyv/latest/rkyv/trait.ArchiveUnsized.html?search= This example demonstrates manually un-sizing a `Box>` to `Box>`, serializing it, and then deserializing it to verify its contents. ```rust let value = Box::new(Block { head: "Numbers 1-4".to_string(), tail: [1, 2, 3, 4], }); // We have a Box> but we want to it to be a // Box>, so we need manually "unsize" the pointer. let ptr = Box::into_raw(value); let unsized_ptr = ptr_meta::from_raw_parts_mut::>( ptr.cast::<()>(), 4, ); let unsized_value = unsafe { Box::from_raw(unsized_ptr) }; let bytes = to_bytes::(&unsized_value).unwrap(); let archived = unsafe { access_unchecked::>>>(&bytes) }; assert_eq!(archived.head, "Numbers 1-4"); assert_eq!(archived.tail.len(), 4); assert_eq!(archived.tail, [1, 2, 3, 4]); ``` -------------------------------- ### Get Base Pointer of RawRelPtr Source: https://docs.rs/rkyv/latest/src/rkyv/rel_ptr.rs.html?search=u32+-%3E+bool Returns the base pointer for a RawRelPtr. This is the starting address of the relative pointer itself. ```rust pub fn base_raw(this: *mut Self) -> *mut u8 { this.cast() } ``` -------------------------------- ### Get Base Pointer Source: https://docs.rs/rkyv/latest/rkyv/rel_ptr/type.RawRelPtrI16.html Retrieves the base pointer for the relative pointer. This is the starting point from which the offset is calculated. ```rust pub fn base(&self) -> *const u8 ``` -------------------------------- ### Get Base Raw Pointer Source: https://docs.rs/rkyv/latest/rkyv/rel_ptr/type.RawRelPtrI16.html Retrieves the base pointer for a RawRelPtr. This is the starting point from which the offset is calculated. ```rust pub fn base_raw(this: *mut Self) -> *mut u8 ``` -------------------------------- ### Conversion and Formatting Source: https://docs.rs/rkyv/latest/rkyv/primitive/type.ArchivedU64.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Documentation for Sum, TryFrom, and formatting traits for u64_le. ```APIDOC ## Summation ### Description Takes an iterator and generates u64_le by summing up the items. ### Method - sum(iter: I) -> u64_le where I: Iterator ## TryFrom ### Description Performs a fallible conversion from usize to u64_le. ### Method - try_from(value: usize) -> Result ``` -------------------------------- ### RelPtr base_raw Method Source: https://docs.rs/rkyv/latest/src/rkyv/rel_ptr.rs.html?search=std%3A%3Avec Gets the base pointer for the pointed-to relative pointer. This is the starting address from which the offset is calculated. ```rust pub fn base_raw(this: *mut Self) -> *mut u8 { RawRelPtr::::base_raw(this.cast()) } ``` -------------------------------- ### MapKV Example Usage Source: https://docs.rs/rkyv/latest/rkyv/with/struct.MapKV.html?search=u32+-%3E+bool Demonstrates how to use the MapKV wrapper with the `#[rkyv(with = ...)]` attribute to customize archiving for HashMap entries. ```APIDOC ## Example ```rust use std::collections::HashMap; use rkyv::{ with::{Inline, InlineAsBox, MapKV}, Archive, }; #[derive(Archive)] struct Example<'a> { // This will apply `InlineAsBox` to the `&str` key, and `Inline` to the // `&str` value. #[rkyv(with = MapKV)] hash_map: HashMap<&'a str, &'a str>, } ``` ``` -------------------------------- ### Get match indices with match_indices Source: https://docs.rs/rkyv/latest/rkyv/string/struct.ArchivedString.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns an iterator over disjoint matches and their starting indices. Overlapping matches are not returned. ```rust let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect(); assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]); let v: Vec<_> = "1abcabc2".match_indices("abc").collect(); assert_eq!(v, [(1, "abc"), (4, "abc")]); let v: Vec<_> = "ababa".match_indices("aba").collect(); assert_eq!(v, [(0, "aba")]); // only the first `aba` ``` -------------------------------- ### Conversion and Formatting Source: https://docs.rs/rkyv/latest/rkyv/primitive/type.ArchivedI16.html?search=u32+-%3E+bool Documentation for TryFrom conversions and formatting traits for i16_le. ```APIDOC ## Conversion and Formatting ### Description Provides conversion from isize and formatting capabilities for i16_le. ### Methods - try_from(value: isize) -> Result - fmt(&self, f: &mut Formatter) -> Result<(), Error> (UpperExp, UpperHex) ``` -------------------------------- ### Get Immutable Base Pointer Source: https://docs.rs/rkyv/latest/src/rkyv/rel_ptr.rs.html?search=u32+-%3E+bool Returns the immutable base pointer for the relative pointer. This is the starting address of the relative pointer itself. ```rust pub fn base(&self) -> *const u8 { Self::base_raw((self as *const Self).cast_mut()).cast_const() } ``` -------------------------------- ### Example of NicheInto for Space Optimization Source: https://docs.rs/rkyv/latest/rkyv/with/struct.NicheInto.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how NicheInto can be used with Null and NaN niching to reduce the size of archived data structures compared to standard Option types. ```rust use core::mem::size_of; use rkyv::{ niche::niching::{NaN, Null}, with::NicheInto, Archive, }; #[derive(Archive)] struct BasicExample { maybe_box: Option>, maybe_non_nan: Option, } #[derive(Archive)] struct NichedExample { #[rkyv(with = NicheInto)] maybe_box: Option>, #[rkyv(with = NicheInto)] maybe_non_nan: Option, } assert!( size_of::>() > size_of::>() ); ``` -------------------------------- ### EntryAdapter::new Source: https://docs.rs/rkyv/latest/rkyv/collections/util/struct.EntryAdapter.html?search= Creates a new instance of EntryAdapter for the given key and value. ```APIDOC ## fn new(key: BK, value: BV) -> Self ### Description Returns a new `EntryAdapter` for the given key and value. ### Parameters - **key** (BK) - Required - The key to serialize and resolve. - **value** (BV) - Required - The value to serialize and resolve. ### Response - **Self** (EntryAdapter) - A new instance of EntryAdapter. ``` -------------------------------- ### Example: Mutably Accessing Archived Data with access_pos_mut Source: https://docs.rs/rkyv/latest/rkyv/api/low/fn.access_pos_mut.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to use `access_pos_mut` to get mutable access to archived data. This example serializes a struct, finds its root position, accesses it mutably, and then modifies a field within the archived data. ```rust use core::mem::MaybeUninit; use rkyv:: api::{ root_position, low::{ to_bytes_in_with_alloc, access_pos_mut } }, rancor::Failure, ser::{ allocator::SubAllocator, writer::Buffer }, util::Align, with::InlineAsBox, Archive, Serialize, munge::munge, ; let mut output = Align([MaybeUninit::::uninit(); 256]); let mut alloc = [MaybeUninit::::uninit(); 256]; #[derive(Archive, Serialize)] struct Example { inner: i32, } let value = Example { inner: 42 }; let mut bytes = to_bytes_in_with_alloc::<_, _, Failure>( &value, Buffer::from(&mut *output), SubAllocator::new(&mut alloc), ) .unwrap(); let root_pos = root_position::(bytes.len()); let mut archived = access_pos_mut::( &mut *bytes, root_pos, ).unwrap(); // Because the access is mutable, we can mutate the archived data munge!(let ArchivedExample { mut inner, .. } = archived); assert_eq!(*inner, 42); *inner = 12345.into(); assert_eq!(*inner, 12345); ``` -------------------------------- ### RelPtr base_raw Method Source: https://docs.rs/rkyv/latest/src/rkyv/rel_ptr.rs.html?search=u32+-%3E+bool Gets the base pointer for the pointed-to relative pointer. This is a raw pointer to the start of the `RawRelPtr` within the `RelPtr`. ```rust pub fn base_raw(this: *mut Self) -> *mut u8 { RawRelPtr::::base_raw(this.cast()) } ``` -------------------------------- ### Example Usage of to_bytes_in Source: https://docs.rs/rkyv/latest/rkyv/api/high/fn.to_bytes_in.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates serializing a custom struct `Example` to bytes using `to_bytes_in` and then deserializing it back using `from_bytes`. Ensure the `alloc` feature is enabled. ```rust use rkyv:: api::high::to_bytes_in, from_bytes, rancor::Error, util::AlignedVec, Archive, Deserialize, Serialize, ; #[derive(Archive, Serialize, Deserialize, Debug, PartialEq)] struct Example { name: String, value: i32, } let value = Example { name: "pi".to_string(), value: 31415926, }; let bytes = to_bytes_in::<_, Error>(&value, AlignedVec::<8>::new()).unwrap(); let deserialized = from_bytes::(&bytes).unwrap(); assert_eq!(deserialized, value); ``` -------------------------------- ### Example Usage of Niche Source: https://docs.rs/rkyv/latest/rkyv/with/struct.Niche.html?search=u32+-%3E+bool Demonstrates how to use the Niche wrapper to reduce the archived size of Option>. ```APIDOC ## Example ```rust use core::mem::size_of; use rkyv::{with::Niche, Archive, Archived}; #[derive(Archive)] struct BasicExample { value: Option>, } #[derive(Archive)] struct NichedExample { #[rkyv(with = Niche)] value: Option>, } assert!( size_of::>() > size_of::>() ); ``` ``` -------------------------------- ### match_indices Examples Source: https://docs.rs/rkyv/latest/rkyv/string/struct.ArchivedString.html?search= Returns an iterator over the starting indices and string slices of all disjoint matches of a pattern. Overlapping matches are handled by returning only the first. ```rust let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect(); assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]); ``` ```rust let v: Vec<_> = "1abcabc2".match_indices("abc").collect(); assert_eq!(v, [(1, "abc"), (4, "abc")]); ``` ```rust let v: Vec<_> = "ababa".match_indices("aba").collect(); assert_eq!(v, [(0, "aba")]); // only the first `aba` ``` -------------------------------- ### Example: Using access_unchecked_mut Source: https://docs.rs/rkyv/latest/rkyv/api/fn.access_unchecked_mut.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to use `access_unchecked_mut` to get mutable access to archived data and then mutate it. Ensure the byte slice is valid before using this function. ```rust use rkyv::{ to_bytes, access_unchecked_mut, util::Align, Archive, munge::munge, Serialize, Deserialize, rancor::Error, }; #[derive(Archive, Serialize, Deserialize)] struct Example { name: String, value: i32, } let value = Example { name: "pi".to_string(), value: 31415926, }; let mut bytes = to_bytes::(&value).unwrap(); let mut archived = unsafe { access_unchecked_mut::(&mut *bytes) }; assert_eq!(archived.name, "pi"); assert_eq!(archived.value, 31415926); // Because the access is mutable, we can mutate the archived data munge!(let ArchivedExample { mut value, .. } = archived); assert_eq!(*value, 31415926); *value = 12345.into(); assert_eq!(*value, 12345); ``` -------------------------------- ### C String Byte Slice Examples Source: https://docs.rs/rkyv/latest/rkyv/ffi/struct.ArchivedCString.html Provides examples for `count_bytes`, `is_empty`, and `to_bytes` methods on C strings, demonstrating their usage with both non-empty and empty strings. ```rust assert_eq!(c"foo".count_bytes(), 3); assert_eq!(c"".count_bytes(), 0); ``` ```rust assert!(!c"foo".is_empty()); assert!(c"".is_empty()); ``` ```rust assert_eq!(c"foo".to_bytes(), b"foo"); ``` -------------------------------- ### Split String and Get Substring Ranges Source: https://docs.rs/rkyv/latest/rkyv/string/struct.ArchivedString.html?search= This example demonstrates splitting a string by a delimiter and obtaining the byte range of each substring within the original string. Requires the `substr_range` feature. ```rust #![feature(substr_range)] let data = "a, b, b, a"; let mut iter = data.split(", ").map(|s| data.substr_range(s).unwrap()); assert_eq!(iter.next(), Some(0..1)); assert_eq!(iter.next(), Some(3..4)); assert_eq!(iter.next(), Some(6..7)); assert_eq!(iter.next(), Some(9..10)); ``` -------------------------------- ### Strategy::wrap Implementation Example Source: https://docs.rs/rkyv/latest/rkyv/api/high/type.HighSerializer.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates wrapping a type with Strategy without changing its memory layout. ```rust use core::ops::Deref; use rancor::{Failure, Strategy}; fn test() { struct Inner { value: u64, } let mut inner = Inner { value: 10 }; let inner_value_ptr = &inner.value as *const u64; let strategy: &mut Strategy = Strategy::wrap(&mut inner); let strategy_value_ptr = (&strategy.deref().value) as *const u64; assert_eq!(inner_value_ptr, strategy_value_ptr); // Strategy wraps a type but does not change its memory layout. } test(); ``` -------------------------------- ### Example: Unsafely Access Archived Data by Position Source: https://docs.rs/rkyv/latest/src/rkyv/api/mod.rs.html Demonstrates using `access_pos_unchecked` to read archived data at a specific position. The `root_position` is used to find the starting point of the archived data. ```rust use rkyv::{ to_bytes, api::{root_position, access_pos_unchecked}, Archive, Serialize, Deserialize, rancor::Error, }; #[derive(Archive, Serialize, Deserialize)] struct Example { name: String, value: i32, } let value = Example { name: "pi".to_string(), value: 31415926, }; let bytes = to_bytes::(&value).unwrap(); let archived = unsafe { access_pos_unchecked::( &*bytes, root_position::(bytes.len()), ) }; assert_eq!(archived.name, "pi"); assert_eq!(archived.value, 31415926); ``` -------------------------------- ### Example: Unsafely Mutably Access Archived Data by Position Source: https://docs.rs/rkyv/latest/src/rkyv/api/mod.rs.html Demonstrates using `access_pos_unchecked_mut` to get a mutable reference to archived data. The `munge!` macro is used to destructure and modify the archived data. ```rust use rkyv::{ to_bytes, api::{root_position, access_pos_unchecked_mut}, Archive, Serialize, Deserialize, munge::munge, rancor::Error, }; #[derive(Archive, Serialize, Deserialize)] struct Example { name: String, value: i32, } let value = Example { name: "pi".to_string(), value: 31415926, }; let mut bytes = to_bytes::(&value).unwrap(); let root_pos = root_position::(bytes.len()); let mut archived = unsafe { access_pos_unchecked_mut::(&mut *bytes, root_pos) }; assert_eq!(archived.name, "pi"); assert_eq!(archived.value, 31415926); // Because the access is mutable, we can mutate the archived data munge!(let ArchivedExample { mut value, .. } = archived); assert_eq!(*value, 31415926); *value = 12345.into(); assert_eq!(*value, 12345); ``` -------------------------------- ### Mutably iterate over slice chunks from the end Source: https://docs.rs/rkyv/latest/rkyv/ser/writer/struct.Buffer.html Use `rchunks_mut` to get an iterator over mutable slices of a specified size, starting from the end. This allows in-place modification of slice elements within each chunk. ```rust let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; for chunk in v.rchunks_mut(2) { for elem in chunk.iter_mut() { *elem += count; } count += 1; } assert_eq!(v, &[3, 2, 2, 1, 1]); ``` -------------------------------- ### MapKV and Inline Wrapper Example Source: https://docs.rs/rkyv/latest/src/rkyv/with.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to use the MapKV wrapper with Inline for selectively applying a wrapper to keys or values in a HashMap. ```APIDOC ## MapKV with Inline Wrapper ### Description This example shows how to use `MapKV` in conjunction with `Inline` to apply a wrapper to either the keys or values of a `HashMap`. This is particularly useful when you need to serialize or deserialize keys and values differently. ### Method N/A (Code Example) ### Endpoint N/A (Code Example) ### Parameters N/A (Code Example) ### Request Example N/A (Code Example) ### Response N/A (Code Example) ### Code Example ```rust use std::collections::HashMap; use rkyv::{ with::{Identity, Inline, MapKV}, Archive, }; #[derive(Archive)] struct Example<'a> { #[rkyv(with = MapKV)] a: HashMap, } ``` ``` -------------------------------- ### MapKV Wrapper Example Source: https://docs.rs/rkyv/latest/src/rkyv/with.rs.html?search= Demonstrates how to use the MapKV wrapper to apply transformations to keys or values within a collection, such as a HashMap. ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of a new user in the system. It accepts user details in the request body and returns the created user's information. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address of the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier for the created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": "user-12345", "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Iterate over slice chunks from the end Source: https://docs.rs/rkyv/latest/rkyv/ser/writer/struct.Buffer.html Use `rchunks` to get an iterator over mutable slices of a specified size, starting from the end. The last chunk may be smaller if the slice length is not divisible by `chunk_size`. ```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()); ``` -------------------------------- ### Get Element Index via Pointer Arithmetic Source: https://docs.rs/rkyv/latest/rkyv/ser/writer/struct.Buffer.html Determines the index of an element reference within a slice using pointer arithmetic. Returns `None` if the element reference does not point to the start of an element. Panics if `T` is zero-sized. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust 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 ``` -------------------------------- ### Accessing Archived Data Unsafely Source: https://docs.rs/rkyv/latest/rkyv/fn.access_unchecked.html This example demonstrates how to use `access_unchecked` to get a reference to an archived type from a byte slice. It requires the byte slice to be valid and does not perform any checks. Ensure the data is valid before calling this function. ```rust use rkyv::{ access_unchecked, rancor::Error, to_bytes, Archive, Deserialize, Serialize, }; #[derive(Archive, Serialize, Deserialize)] struct Example { name: String, value: i32, } let value = Example { name: "pi".to_string(), value: 31415926, }; let bytes = to_bytes::(&value).unwrap(); let archived = unsafe { access_unchecked::(&*bytes) }; assert_eq!(archived.name, "pi"); assert_eq!(archived.value, 31415926); ``` -------------------------------- ### Buffer Example Usage Source: https://docs.rs/rkyv/latest/src/rkyv/ser/writer/core.rs.html Demonstrates how to use the Buffer for serialization in a no_std environment. ```APIDOC ## Buffer Serialization Example ### Description This example shows how to serialize an `Event` enum into a fixed-size byte buffer using `rkyv`'s `to_bytes_in` function and a `Buffer`. ### Code ```rust use core::mem::MaybeUninit; use rkyv::{ access_unchecked, api::high::to_bytes_in, rancor::{Error, Strategy}, ser::{writer::Buffer, Writer}, util::Align, Archive, Archived, Serialize, }; #[derive(Archive, Serialize)] enum Event { Spawn, Speak(String), Die, } fn main() { let event = Event::Speak("Help me!".to_string()); let mut bytes = Align([MaybeUninit::uninit(); 256]); let buffer = to_bytes_in::<_, Error>(&event, Buffer::from(&mut *bytes)) .expect("failed to serialize event"); let archived = unsafe { access_unchecked::>(&buffer) }; if let Archived::::Speak(message) = archived { assert_eq!(message.as_str(), "Help me!"); } else { panic!("archived event was of the wrong type"); } } ``` ``` -------------------------------- ### Mutably Access Archived Data Unchecked Source: https://docs.rs/rkyv/latest/rkyv/api/fn.access_unchecked_mut.html Use `access_unchecked_mut` to get mutable access to archived data within a byte slice. This is unsafe and requires the caller to guarantee the validity of the byte slice. The example demonstrates accessing and modifying a struct's fields. ```rust use rkyv::{ to_bytes, access_unchecked_mut, util::Align, Archive, munge::munge, Serialize, Deserialize, rancor::Error, }; #[derive(Archive, Serialize, Deserialize)] struct Example { name: String, value: i32, } let value = Example { name: "pi".to_string(), value: 31415926, }; let mut bytes = to_bytes::(&value).unwrap(); let mut archived = unsafe { access_unchecked_mut::(&mut *bytes) }; assert_eq!(archived.name, "pi"); assert_eq!(archived.value, 31415926); // Because the access is mutable, we can mutate the archived data munge!(let ArchivedExample { mut value, .. } = archived); assert_eq!(*value, 31415926); *value = 12345.into(); assert_eq!(*value, 12345); ``` -------------------------------- ### Get Index Of Source: https://docs.rs/rkyv/latest/src/rkyv/collections/swiss_table/index_map.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the index of a key if it exists in the map. ```APIDOC ## GET /api/indexmap/index_of ### Description Gets the index of a key if it exists in the map. ### Method GET ### Endpoint `/api/indexmap/index_of` ### Parameters #### Query Parameters - **key** (Q) - Required - The key to find the index of. ### Response #### Success Response (200) - **usize** - The index of the key if found, otherwise None. #### Response Example ```json { "index": 0 } ``` ``` -------------------------------- ### IoWriter Example Usage Source: https://docs.rs/rkyv/latest/src/rkyv/ser/writer/std.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to use IoWriter for serialization, including wrapping it with a Strategy and writing data. ```APIDOC ## IoWriter Example Usage ### Description This example shows how to initialize an `IoWriter`, wrap it with a `Strategy`, write data to it, and retrieve the underlying buffer. ### Code Example ```rust # use rkyv::ser::{Writer, Positional, writer::IoWriter}; use rkyv::rancor::{Error, Strategy}; let mut io_writer = IoWriter::new(Vec::new()); // In most cases, calling a method like `serialize` will wrap the writer in // a Strategy for us. let mut writer = Strategy::<_, Error>::wrap(&mut io_writer); assert_eq!(writer.pos(), 0); writer.write(&[0u8, 1u8, 2u8, 3u8]); assert_eq!(writer.pos(), 4); let buf = io_writer.into_inner(); assert_eq!(buf.len(), 4); assert_eq!(buf, vec![0u8, 1u8, 2u8, 3u8]); ``` ``` -------------------------------- ### Get Offset Source: https://docs.rs/rkyv/latest/rkyv/rel_ptr/struct.RawRelPtr.html?search= Gets the offset of the relative pointer from its base. ```rust pub fn offset(&self) -> isize ``` -------------------------------- ### Basic Serialization and Deserialization with Derive Source: https://docs.rs/rkyv/latest/rkyv/trait.Archive.html?search=std%3A%3Avec Demonstrates how to use the `#[derive(Archive)]` macro for automatic implementation of serialization and deserialization. Shows basic usage of `rkyv::to_bytes` and `rkyv::access` for both safe and unsafe deserialization. ```rust use rkyv::{deserialize, rancor::Error, Archive, Deserialize, Serialize}; #[derive(Archive, Deserialize, Serialize, Debug, PartialEq)] #[rkyv( // This will generate a PartialEq impl between our unarchived // and archived types compare(PartialEq), // Derives can be passed through to the generated type: derive(Debug), )] struct Test { int: u8, string: String, option: Option>, } fn main() { let value = Test { int: 42, string: "hello world".to_string(), option: Some(vec![1, 2, 3, 4]), }; // Serializing is as easy as a single function call let _bytes = rkyv::to_bytes::(&value).unwrap(); // Or you can customize your serialization for better performance or control // over resource usage use rkyv::{api::high::to_bytes_with_alloc, ser::allocator::Arena}; let mut arena = Arena::new(); let bytes = to_bytes_with_alloc::<_, Error>(&value, arena.acquire()).unwrap(); // You can use the safe API for fast zero-copy deserialization let archived = rkyv::access::(&bytes[..]).unwrap(); assert_eq!(archived, &value); // Or you can use the unsafe API for maximum performance let archived = unsafe { rkyv::access_unchecked::(&bytes[..]) }; assert_eq!(archived, &value); // And you can always deserialize back to the original type let deserialized = deserialize::(archived).unwrap(); assert_eq!(deserialized, value); } ``` -------------------------------- ### SerVec Initialization Source: https://docs.rs/rkyv/latest/src/rkyv/util/ser_vec.rs.html?search= Utility for converting a vector of MaybeUninit elements to a standard SerVec. ```rust pub fn assume_init(self) -> SerVec { SerVec { ptr: self.ptr.cast(), cap: self.cap, len: self.len, } } ``` -------------------------------- ### GET as_array Source: https://docs.rs/rkyv/latest/rkyv/util/struct.AlignedVec.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets a reference to the underlying array if the length matches. ```APIDOC ## GET as_array ### Description Gets a reference to the underlying array. If N is not exactly equal to the length of the slice, returns None. ### Parameters #### Path Parameters - **N** (usize) - Required - The expected length of the array ### Response #### Success Response (200) - **array** (Option<&[T; N]>) - The array reference if lengths match, otherwise None. ``` -------------------------------- ### Get Base Pointer Source: https://docs.rs/rkyv/latest/rkyv/rel_ptr/struct.RawRelPtr.html?search= Gets the base pointer for the relative pointer. ```rust pub fn base(&self) -> *const u8 ``` -------------------------------- ### String As Bytes Example Source: https://docs.rs/rkyv/latest/rkyv/string/struct.ArchivedString.html?search= Shows how to convert a string slice into a byte slice. ```rust let bytes = "bors".as_bytes(); assert_eq!(b"bors", bytes); ``` -------------------------------- ### Archive Trait Documentation Example Source: https://docs.rs/rkyv/latest/src/rkyv/traits.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This example demonstrates how to use the `#[derive(Archive)]` macro and provides notes on implementing `Archive` for custom types when the derive macro is insufficient. ```rust /// # Examples /// /// Most of the time, `#[derive(Archive)]` will create an acceptable /// implementation. You can use the `#[rkyv(...)]` attribute to control how the /// implementation is generated. See the [`Archive`](macro@crate::Archive) /// derive macro for more details. #[doc = concat!("```\n", include_str!("../examples/readme.rs"), "```\n")] /// _Note: the safe API requires the `bytecheck` feature._ /// /// Many of the core and standard library types already have `Archive` /// implementations available, but you may need to implement `Archive` for your /// own types in some cases the derive macro cannot handle. /// /// In this example, we add our own wrapper that serializes a `&'static str` as /// if it's owned. Normally you can lean on the archived version of `String` to /// do most of the work, or use the [`Inline`](crate::with::Inline) to do /// exactly this. This example does everything to demonstrate how to implement ```