### Merkle Tree Examples Source: https://docs.rs/merkletree/0.23.0/merkletree/index This section provides practical examples of how to use the merkletree crate. It demonstrates common use cases such as building a Merkle tree, generating proofs, and verifying them. ```Rust Examples ``` -------------------------------- ### Merkle Tree Examples Source: https://docs.rs/merkletree/0.23.0/index This section provides practical examples of how to use the merkletree crate. It demonstrates common use cases such as creating a tree, generating a proof for a specific data element, and verifying that proof. ```rust Examples ```rust use merkletree::{MerkleTree, MerkleProof}; let data = vec![ b"hello".to_vec(), b"world".to_vec(), b"rust".to_vec(), b"merkle".to_vec(), ]; let tree = MerkleTree::new(&data); let root = tree.root(); println!("Merkle Root: {:?}", hex::encode(root)); let proof = tree.generate_proof(b"rust").expect("Proof should exist"); let is_valid = tree.verify_proof(&proof).expect("Verification should succeed"); assert!(is_valid); println!("Proof is valid!"); ``` This example shows the basic usage of creating a Merkle tree, getting its root, generating a proof for the data `b"rust"`, and then verifying that proof. ``` -------------------------------- ### Merkle Tree Examples Source: https://docs.rs/merkletree/0.23.0/merkletree This section provides practical examples of how to use the merkletree crate. It demonstrates common use cases such as creating a tree, generating a proof for a specific data element, and verifying that proof. ```rust Examples ```rust use merkletree::{MerkleTree, MerkleProof}; let data = vec![ b"hello".to_vec(), b"world".to_vec(), b"rust".to_vec(), b"merkle".to_vec(), ]; let tree = MerkleTree::new(&data); let root = tree.root(); println!("Merkle Root: {:?}", hex::encode(root)); let proof = tree.generate_proof(b"rust").expect("Proof should exist"); let is_valid = tree.verify_proof(&proof).expect("Verification should succeed"); assert!(is_valid); println!("Proof is valid!"); ``` This example shows the basic usage of creating a Merkle tree, getting its root, generating a proof for the data `b"rust"`, and then verifying that proof. ``` -------------------------------- ### Rust Slice as_rchunks Example Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.MmapStore Demonstrates splitting a slice into chunks from the end using `as_rchunks`. It shows how the remainder is handled at the beginning 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']]) ``` -------------------------------- ### Rust Slice as_chunks Example Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.MmapStore Demonstrates splitting a slice into chunks of a specified size using `as_chunks_unchecked`. It shows how to handle slices that are exact multiples of the chunk size and highlights unsound usage. ```rust let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!']; let chunks: &[[char; 1]] = // SAFETY: 1-element chunks never have remainder unsafe { slice.as_chunks_unchecked() }; assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]); let chunks: &[[char; 3]] = // SAFETY: The slice length (6) is a multiple of 3 unsafe { slice.as_chunks_unchecked() }; assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]); // These would be unsound: // let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5 // let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed ``` -------------------------------- ### Rust element_offset Example Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.MmapStore Illustrates the `element_offset` method, which returns the index of an element reference within a slice. It returns `None` if the element reference is not aligned with the start of an element. This is a nightly-only experimental API. ```rust #![feature(substr_range)] let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` -------------------------------- ### MerkleTree Crate Overview Source: https://docs.rs/merkletree/0.23.0/src/merkletree/store/disk.rs Provides an overview of the merkletree crate, including its version, license, source code links, and dependencies. It also lists supported platforms and documentation coverage. ```Rust Project: /context7/rs-merkletree-0.23.0 License: BSD-3-Clause Dependencies: - anyhow ^1.0.23 - arrayref ^0.3.5 - log ^0.4.7 - memmap2 ^0.5.7 - positioned-io ^0.3 - rayon ^1.0.0 - serde ^1.0 - tempfile ^3.3 - typenum ^1.11.2 Supported Platforms: - i686-pc-windows-msvc - i686-unknown-linux-gnu - x86_64-apple-darwin - x86_64-pc-windows-msvc - x86_64-unknown-linux-gnu Documentation Coverage: 52.05% ``` -------------------------------- ### Rust Slice Get Unchecked Method Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.MmapStore Unsafely retrieves a reference to an element or subslice without bounds checking. Use with caution as out-of-bounds access is undefined behavior. For a safe alternative, use `get`. ```rust pub unsafe fn get_unchecked(&self, index: I) -> &>::Output where I: SliceIndex<[T]>, ``` -------------------------------- ### Initialize Disk Store from Disk Source: https://docs.rs/merkletree/0.23.0/src/merkletree/store/disk.rs Creates a new Disk Store by loading data from a specified path on disk, using the provided configuration. It delegates the actual loading to `new_from_disk_with_path`. ```rust fn new_from_disk(size: usize, _branches: usize, config: &StoreConfig) -> Result { let data_path = StoreConfig::data_path(&config.path, &config.id); Self::new_from_disk_with_path(size, &data_path) } ``` -------------------------------- ### MerkleTree Store Initialization Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.DiskStore Provides methods for creating new Merkletree stores. Supports initialization from slices with or without configuration, and from disk. ```APIDOC fn new(size: usize) -> Result Initializes a new store with a specified size. fn new_from_slice_with_config(size: usize, branches: usize, data: &[[u8]], config: StoreConfig) -> Result Initializes a new store from a slice of data with a given configuration. fn new_from_slice(size: usize, data: &[[u8]]) -> Result Initializes a new store from a slice of data. fn new_from_disk(size: usize, _branches: usize, config: &[StoreConfig]) -> Result Initializes a store from existing disk files. This constructor is used for instantiating stores ONLY from existing (potentially read-only) files. ``` -------------------------------- ### Rust Slice repeat Example Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.MmapStore Shows the `repeat` method, which creates a new vector by copying the elements of a slice a specified number of times. It also includes an example of a panic scenario when the capacity would overflow. ```rust assert_eq!([1, 2].repeat(3), vec![1, 2, 1, 2, 1, 2]); ``` ```rust // this will panic at runtime b"0123456789abcdef".repeat(usize::MAX); ``` -------------------------------- ### MerkleTree Crate Overview Source: https://docs.rs/merkletree/0.23.0/src/merkletree/store/vec.rs Provides an overview of the merkletree crate, including its version, license, source code links, and dependencies. It also lists supported platforms for building and testing. ```Rust Project: /context7/rs-merkletree-0.23.0 Dependencies: * [ anyhow ^1.0.23 _normal_ ] * [ arrayref ^0.3.5 _normal_ ] * [ log ^0.4.7 _normal_ ] * [ memmap2 ^0.5.7 _normal_ ] * [ positioned-io ^0.3 _normal_ ] * [ rayon ^1.0.0 _normal_ ] * [ serde ^1.0 _normal_ ] * [ tempfile ^3.3 _normal_ ] * [ typenum ^1.11.2 _normal_ ] Platforms: * i686-pc-windows-msvc * i686-unknown-linux-gnu * x86_64-apple-darwin * x86_64-pc-windows-msvc * x86_64-unknown-linux-gnu License: BSD-3-Clause ``` -------------------------------- ### Hashable Trait Implementation Example Source: https://docs.rs/merkletree/0.23.0/src/merkletree/hash.rs Demonstrates how to implement the `Hashable` trait for a custom struct `Person`. It shows how to feed struct fields into a `Hasher` and provides an example of hashing a `Person` instance and asserting the resulting hash value. ```rust struct Person { id: i32, name: String, phone: i32, } impl Hashable for Person { fn hash(&self, state: &mut DefaultHasher) { self.id.hash(state); self.name.hash(state); self.phone.hash(state); } } let foo = Person{ id: 1, name: String::from("blah"), phone: 2, }; let mut hr = DefaultHasher::new(); foo.hash(&mut hr); assert_eq!(hr.finish(), 7101638158313343130) ``` -------------------------------- ### Rust element_offset with Unaligned Element Example Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.MmapStore Demonstrates how `element_offset` returns `None` when the element reference is not properly aligned within the slice. This example uses a flattened slice to create an unaligned reference. This is a nightly-only experimental API. ```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 ``` -------------------------------- ### DiskStore Creation from Slice with Configuration Source: https://docs.rs/merkletree/0.23.0/src/merkletree/store/disk.rs Initializes a DiskStore from a slice of elements with a given configuration. This method is used when pre-existing data needs to be loaded into the store. ```rust fn new_from_slice_with_config( size: usize, ``` -------------------------------- ### Get Slice as Array Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.MmapStore Attempts to get a reference to the underlying array if the slice's length exactly matches the specified size `N`. This is a nightly-only experimental API. Returns `None` if `N` does not match the slice length. ```rust // This is an experimental API and requires a nightly Rust compiler. // let data: [i32; 3] = [1, 2, 3]; // let slice = &data[..]; // let array_ref: Option<&[[i32; 3]]> = slice.as_array(); ``` -------------------------------- ### DiskStore Initialization - APIDOC Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.DiskStore Provides methods for initializing and managing a DiskStore for merkletree. This includes creating a new store with specific size, branch factor, and configuration, as well as other store-related operations. ```APIDOC impl Store for DiskStore new_with_config(size: usize, branches: usize, config: StoreConfig) -> Result Creates a new store which can store up to `size` elements. Parameters: size: The maximum number of elements the store can hold. branches: The branching factor for the Merkle tree. config: The configuration for the store. Returns: A Result containing the new DiskStore or an error if creation fails. new(size: usize, branches: usize) -> Result Creates a new store with default configuration. Parameters: size: The maximum number of elements the store can hold. branches: The branching factor for the Merkle tree. Returns: A Result containing the new DiskStore or an error if creation fails. ``` -------------------------------- ### Rust: Get Element or Subslice by Index Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.VecStore The `get` method allows accessing elements or subslices of a slice using various index types (e.g., usize for elements, ranges for subslices). It returns an Option containing a reference to the element/subslice or None if the index is out of bounds. ```rust pub fn get(&self, index: I) -> Option<&>::Output> where I: SliceIndex<[T]> // Example: 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)); ``` -------------------------------- ### DiskStore Creation with Configuration Source: https://docs.rs/merkletree/0.23.0/src/merkletree/store/disk.rs Creates a new DiskStore with specified size, branches, and configuration. It checks if the data file exists and loads it, otherwise it creates a new file and initializes it. ```rust impl Store for DiskStore { fn new_with_config(size: usize, branches: usize, config: StoreConfig) -> Result { let data_path = StoreConfig::data_path(&config.path, &config.id); // If the specified file exists, load it from disk. if Path::new(&data_path).exists() { return Self::new_from_disk(size, branches, &config); } // Otherwise, create the file and allow it to be the on-disk store. let file = OpenOptions::new() .write(true) .read(true) .create_new(true) .open(data_path)?; let store_size = E::byte_len() * size; file.set_len(store_size as u64)?; Ok(DiskStore { len: 0, elem_len: E::byte_len(), _e: Default::default(), file, loaded_from_disk: false, store_size, }) } ``` -------------------------------- ### strip_prefix - Remove a prefix from a slice Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.VecStore The `strip_prefix` method removes a given prefix from the beginning of a slice. If the slice starts with the specified prefix, it returns a new slice containing the remainder, wrapped in `Some`. If the prefix is empty, the original slice is returned. If the slice does not start with the prefix, `None` is returned. The prefix type `P` must implement `SlicePattern`. ```rust pub fn strip_prefix

(&self, prefix: &[P]) -> Option<&[T]> where P: SlicePattern + ?Sized, T: PartialEq, { // ... implementation details ... } // Examples: let v = &[10, 40, 30]; assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..])); assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..])); assert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..])); assert_eq!(v.strip_prefix(&[50]), None); assert_eq!(v.strip_prefix(&[10, 50]), None); let prefix : &str = "he"; assert_eq!(b"hello".strip_prefix(prefix.as_bytes()), Some(b"llo".as_ref())); ``` -------------------------------- ### MerkleTree Core Module Files Source: https://docs.rs/merkletree/0.23.0/src/merkletree/store/disk.rs Lists the core files for the merkletree crate, including hashing, Merkle tree logic, and proof generation. ```Rust hash.rs hash_impl.rs lib.rs merkle.rs proof.rs ``` -------------------------------- ### MerkleTree Core Files Source: https://docs.rs/merkletree/0.23.0/src/merkletree/proof.rs Lists the core Rust files for the merkletree crate, including hashing, Merkle tree logic, and proof generation. ```rust Core files: - hash.rs - hash_impl.rs - lib.rs - merkle.rs - proof.rs ``` -------------------------------- ### Get DiskStore Size Source: https://docs.rs/merkletree/0.23.0/src/merkletree/store/disk.rs Returns the current size of the data stored in the DiskStore in bytes. ```rust pub fn store_size(&self) -> usize { self.store_size } ``` -------------------------------- ### DiskStore Methods Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.DiskStore Provides methods for interacting with the DiskStore, including checking consistency, creating from disk, and managing stored data. ```APIDOC DiskStore::is_consistent() Checks if the disk store is consistent. DiskStore::new_from_disk_with_path(path: &str) Creates a new DiskStore instance from a given disk path. Parameters: path: The path to the directory containing the store. Returns: A Result containing the DiskStore or an error. DiskStore::store_copy_from_slice(data: &[u8]) Copies data from a slice into the store. Parameters: data: A slice of bytes to store. DiskStore::store_read_into(buffer: &mut [u8]) Reads data from the store into a provided buffer. Parameters: buffer: A mutable slice to read data into. DiskStore::store_read_range(start: u64, end: u64) Reads a range of data from the store. Parameters: start: The starting index of the range. end: The ending index of the range. Returns: A Result containing the data or an error. DiskStore::store_size() Returns the total size of the data stored. ``` -------------------------------- ### Get Slice Length Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.VecStore Returns the number of elements in a slice. This is a fundamental operation for understanding the size of a data collection. ```rust pub fn len(&self) -> usize // Returns the number of elements in the slice. // Example: let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Get Sub Layer Node Count Source: https://docs.rs/merkletree/0.23.0/src/merkletree/proof.rs Returns the number of nodes in the sub-layers of the Merkle tree relevant to this proof. ```rust pub fn sub_layer_nodes(&self) -> usize { self.sub_tree_layer_nodes } ``` -------------------------------- ### LevelCacheStore Initialization Source: https://docs.rs/merkletree/0.23.0/src/merkletree/store/level_cache.rs Demonstrates the creation of a LevelCacheStore instance with specific configuration parameters. It initializes the store with a given size, number of branches, and file handle, setting up internal fields like element length, data width, and cache start index. It also handles the initial loading state from disk. ```rust Ok(LevelCacheStore { len: 0, elem_len: E::byte_len(), file, data_width: size, cache_index_start: 0, store_size, loaded_from_disk: false, reader: None, _e: Default::default(), }) ``` -------------------------------- ### Get Slice Length (Rust) Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.MmapStore Returns the number of elements in a slice. This is a fundamental operation for understanding the size of a collection. ```rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### MerkleTree Core Modules Source: https://docs.rs/merkletree/0.23.0/src/merkletree/store/vec.rs Lists the core modules of the merkletree crate, including hash.rs, hash_impl.rs, lib.rs, merkle.rs, and proof.rs. These files likely contain the main logic for Merkle tree construction, hashing, and proof generation. ```Rust Files: [hash.rs](https://docs.rs/merkletree/0.23.0/src/merkletree/hash.rs.html) [hash_impl.rs](https://docs.rs/merkletree/0.23.0/src/merkletree/hash_impl.rs.html) [lib.rs](https://docs.rs/merkletree/0.23.0/src/merkletree/lib.rs.html) [merkle.rs](https://docs.rs/merkletree/0.23.0/src/merkletree/merkle.rs.html) [proof.rs](https://docs.rs/merkletree/0.23.0/src/merkletree/proof.rs.html) ``` -------------------------------- ### DiskStore Constructor from Disk Source: https://docs.rs/merkletree/0.23.0/src/merkletree/store/disk.rs Initializes a DiskStore from an existing file path. It opens the file for reading and writing, checks for permission errors, and validates the file size against the expected size based on the element byte length. If the file does not exist or has an incorrect size, it returns an error. ```rust impl DiskStore { pub fn new_from_disk_with_path>(size: usize, data_path: P) -> Result { ensure!(data_path.as_ref().exists(), "[DiskStore] new_from_disk constructor can be used only for instantiating already existing storages"); let file = match OpenOptions::new().write(true).read(true).open(&data_path) { Ok(file) => file, Err(e) => { if e.kind() == std::io::ErrorKind::PermissionDenied { warn!( "[DiskStore] Permission denied occurred. Try to open storage as read-only" ); } OpenOptions::new() .write(false) .read(true) .open(&data_path)? } }; let metadata = file.metadata()?; let store_size = metadata.len() as usize; // Sanity check. ensure!( store_size == size * E::byte_len(), "Invalid formatted file provided. Expected {} bytes, found {} bytes", size * E::byte_len(), store_size ); Ok(DiskStore { len: size, elem_len: E::byte_len(), _e: Default::default(), file, loaded_from_disk: true, store_size, }) } } ``` -------------------------------- ### Get Top Layer Node Count Source: https://docs.rs/merkletree/0.23.0/src/merkletree/proof.rs Returns the number of nodes in the top layer of the Merkle tree relevant to this proof. ```rust pub fn top_layer_nodes(&self) -> usize { self.top_layer_nodes } ``` -------------------------------- ### MerkleTree Crate Overview Source: https://docs.rs/merkletree/0.23.0/merkletree/hash/index Provides an overview of the merkletree Rust crate, including its version, license, source code repository, and dependencies. It also lists supported platforms and feature flags. ```Rust Crate: merkletree Version: 0.23.0 License: BSD-3-Clause Repository: https://github.com/filecoin-project/merkle_light Dependencies: - anyhow ^1.0.23 - arrayref ^0.3.5 - log ^0.4.7 - memmap2 ^0.5.7 - positioned-io ^0.3 - rayon ^1.0.0 - serde ^1.0 - tempfile ^3.3 - typenum ^1.11.2 Supported Platforms: - i686-pc-windows-msvc - i686-unknown-linux-gnu - x86_64-apple-darwin - x86_64-pc-windows-msvc - x86_64-unknown-linux-gnu Features: - Browse available feature flags of merkletree-0.23.0 ``` -------------------------------- ### Get Merkle Root Source: https://docs.rs/merkletree/0.23.0/src/merkletree/merkle.rs Retrieves the Merkle root of the tree. This is a simple getter method that returns a clone of the stored root. ```rust /// Returns merkle root #[inline] pub fn root(&self) -> E { self.root.clone() } ``` -------------------------------- ### MerkleTree Store Constructors Source: https://docs.rs/merkletree/0.23.0/merkletree/store/trait.Store Provides methods for creating and initializing a Merkle tree store. These methods handle different initialization scenarios, including creating new stores, initializing from existing data slices, and loading from disk. ```APIDOC Store Trait Methods: new_with_config(size: usize, branches: usize, config: StoreConfig) -> Result - Creates a new store capable of holding up to `size` elements with a specified number of `branches` and `config`. - Returns a Result containing the new store instance or an error. new(size: usize) -> Result - Creates a new store for up to `size` elements without a specific configuration. - Returns a Result containing the new store instance or an error. new_from_slice_with_config(size: usize, branches: usize, data: &[u8], config: StoreConfig) -> Result - Initializes a store from a byte slice `data`, with `size` elements and `branches`, using the provided `config`. - Returns a Result containing the initialized store instance or an error. new_from_slice(size: usize, data: &[u8]) -> Result - Initializes a store from a byte slice `data` for `size` elements without a specific configuration. - Returns a Result containing the initialized store instance or an error. new_from_disk(size: usize, branches: usize, config: &[StoreConfig]) -> Result - Instantiates a store from existing files on disk, suitable for read-only operations. Requires `size` elements and `branches`, with configuration provided in `config`. - Returns a Result containing the store instance loaded from disk or an error. ``` -------------------------------- ### Iterate Over Slice Elements Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.MmapStore Returns an iterator that yields all elements of the slice from start to end. This is a standard way to traverse the contents of a slice. ```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); ``` -------------------------------- ### Rustdoc Keyboard Shortcuts Source: https://docs.rs/merkletree/0.23.0/help Provides a list of keyboard shortcuts for interacting with the Rustdoc documentation interface. These shortcuts allow for efficient navigation and searching within the documentation. ```Rust `?` Show this help dialog `S` / `/` Focus the search field `↑` Move up in search results `↓` Move down in search results `←` / `→` Switch result tab (when results focused) `⏎` Go to active search result `+` Expand all sections `-` Collapse all sections ``` -------------------------------- ### Get Cache Length Source: https://docs.rs/merkletree/0.23.0/src/merkletree/store/level_cache.rs Returns the number of elements currently stored in the cache. This is a simple getter method that returns the `len` field of the struct. ```rust fn len(&self) -> usize { self.len } ``` -------------------------------- ### MerkleTree Crate Overview Source: https://docs.rs/merkletree/0.23.0/src/merkletree/proof.rs Provides an overview of the merkletree crate, including its purpose, license, source code links, and dependencies. It highlights the crate's focus on a lightweight Merkle tree implementation with SPV support. ```rust Project: /context7/rs-merkletree-0.23.0 License: BSD-3-Clause Dependencies: - anyhow ^1.0.23 - arrayref ^0.3.5 - log ^0.4.7 - memmap2 ^0.5.7 - positioned-io ^0.3 - rayon ^1.0.0 - serde ^1.0 - tempfile ^3.3 - typenum ^1.11.2 Source Code: https://github.com/filecoin-project/merkle_light Crates.io: https://crates.io/crates/merkletree ``` -------------------------------- ### DiskStore: Get Last Element Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.DiskStore Retrieves the last element stored in the DiskStore. This method is useful for resuming operations or checking the state of the tree. ```rust fn last(&self) -> Result ``` -------------------------------- ### MerkleTree Crate Overview Source: https://docs.rs/merkletree/0.23.0/merkletree/merkle/index This section provides a high-level overview of the merkletree crate, including its version, license, source code repository, and dependencies. It also lists the supported build targets and feature flags. ```Rust Crate: merkletree Version: 0.23.0 License: BSD-3-Clause Repository: https://github.com/filecoin-project/merkle_light Dependencies: - anyhow ^1.0.23 - arrayref ^0.3.5 - log ^0.4.7 - memmap2 ^0.5.7 - positioned-io ^0.3 - rayon ^1.0.0 - serde ^1.0 - tempfile ^3.3 - typenum ^1.11.2 Supported Platforms: - i686-pc-windows-msvc - i686-unknown-linux-gnu - x86_64-apple-darwin - x86_64-pc-windows-msvc - x86_64-unknown-linux-gnu ``` -------------------------------- ### Rust Slice Get Method Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.MmapStore Retrieves a reference to an element or subslice from the MmapStore. Supports indexing by position or range. Returns `None` if the index is out of bounds. ```rust pub fn get(&self, index: I) -> Option<&>::Output> where I: SliceIndex<[T]>, ``` -------------------------------- ### MerkleTree Crate Overview Source: https://docs.rs/merkletree/0.23.0/src/merkletree/store/level_cache.rs Provides an overview of the merkletree crate, including its purpose, version, license, source code links, and dependencies. It also lists supported platforms and feature flags. ```Rust Project: /context7/rs-merkletree-0.23.0 Dependencies: * anyhow ^1.0.23 * arrayref ^0.3.5 * log ^0.4.7 * memmap2 ^0.5.7 * positioned-io ^0.3 * rayon ^1.0.0 * serde ^1.0 * tempfile ^3.3 * typenum ^1.11.2 Dev Dependencies: * byteorder ^1.3.1 * criterion ^0.3 * env_logger ^0.7.1 * rand ^0.7.3 * sha2 ^0.10.2 * tempfile ^3.3 * walkdir ^2.3.2 License: BSD-3-Clause Platforms: i686-pc-windows-msvc, i686-unknown-linux-gnu, x86_64-apple-darwin, x86_64-pc-windows-msvc, x86_64-unknown-linux-gnu Documentation Coverage: 52.05% ``` -------------------------------- ### MerkleTree Crate Overview Source: https://docs.rs/merkletree/0.23.0/src/merkletree/lib.rs Provides an overview of the merkletree crate, its purpose as a light Merkle tree implementation with SPV support, and its dependency-agnostic nature. It also lists supported platforms and feature flags. ```Rust /// merkletree 0.23.0 /// Light merkle tree implementation with SPV support and dependency agnostic. /// /// Supported Platforms: /// - i686-pc-windows-msvc /// - i686-unknown-linux-gnu /// - x86_64-apple-darwin /// - x86_64-pc-windows-msvc /// - x86_64-unknown-linux-gnu /// /// Feature flags can be browsed at: https://docs.rs/crate/merkletree/0.23.0/features ``` -------------------------------- ### Get Last Element of a Slice Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.MmapStore Retrieves the last element of a slice. Returns `None` if the slice is empty. This is a common operation for accessing the tail of a sequence. ```rust pub fn last(&self) -> Option<&T> Returns the last element of the slice, or `None` if it is empty. # Examples ``` let v = [10, 40, 30]; assert_eq!(Some(&30), v.last()); let w: &[i32] = &[]; assert_eq!(None, w.last()); ``` ``` -------------------------------- ### MerkleTree Store Initialization Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.LevelCacheStore Provides methods to create new MerkleTree stores with various configurations. Includes options for initializing with a specific size, branch factor, and configuration, as well as creating from slices or disk. ```APIDOC fn new_with_config(size: usize, branches: usize, config: StoreConfig) -> Result Creates a new store which can store up to `size` elements. Parameters: size: The maximum number of elements the store can hold. branches: The branching factor of the Merkle tree. config: The store configuration. Returns: A Result containing the new store instance or an error. fn new(size: usize) -> Result Creates a new store with default configuration. Parameters: size: The maximum number of elements the store can hold. Returns: A Result containing the new store instance or an error. fn new_from_slice_with_config(size: usize, branches: usize, data: &[u8], config: StoreConfig) -> Result Creates a new store and populates it with data from a slice, using a specified configuration. Parameters: size: The maximum number of elements the store can hold. branches: The branching factor of the Merkle tree. data: A slice containing the data to populate the store. config: The store configuration. Returns: A Result containing the new store instance or an error. fn new_from_slice(size: usize, data: &[u8]) -> Result Creates a new store and populates it with data from a slice using default configuration. Parameters: size: The maximum number of elements the store can hold. data: A slice containing the data to populate the store. Returns: A Result containing the new store instance or an error. fn new_from_disk(store_range: usize, branches: usize, config: &[StoreConfig]) -> Result This constructor is used for instantiating stores ONLY from existing (potentially read-only) files. Parameters: store_range: The range of the store to load from disk. branches: The branching factor of the Merkle tree. config: A slice of store configurations. Returns: A Result containing the new store instance or an error. ``` -------------------------------- ### Rust array_windows Example Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.VecStore Demonstrates the usage of the `array_windows` iterator, which provides overlapping windows of a specified size over a slice. This is useful for processing consecutive elements in groups. ```rust #![feature(array_windows)] let slice = [0, 1, 2, 3]; let mut iter = slice.array_windows(); assert_eq!(iter.next().unwrap(), &[0, 1]); assert_eq!(iter.next().unwrap(), &[1, 2]); assert_eq!(iter.next().unwrap(), &[2, 3]); assert!(iter.next().is_none()); ``` -------------------------------- ### MerkleTree Construction and Management Source: https://docs.rs/merkletree/0.23.0/merkletree/merkle/struct.MerkleTree Methods for creating, initializing, and managing MerkleTree instances, including handling sub-trees and deleting backing stores. ```APIDOC MerkleTree::from_sub_tree_store_configs pub fn from_sub_tree_store_configs(leafs: usize, configs: &[[StoreConfig]], ) -> Result> - Instantiates a compound Merkle tree from a set of StoreConfig references. - The order of configs is significant for leaf indexing. MerkleTree::compact pub fn compact(&mut self, config: StoreConfig, store_version: u32) -> Result - Truncates data for later access via LevelCacheStore interface. MerkleTree::reinit pub fn reinit(&mut self) -> Result<()> - Reinitializes the Merkle tree. MerkleTree::delete pub fn delete(&self, config: StoreConfig) -> Result<()> - Removes the backing store for this Merkle tree. ``` -------------------------------- ### Get First Element of Slice Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.VecStore Returns the first element of the slice as an `Option<&T>`. Returns `None` if the slice is empty. This method is safe for accessing the initial element. ```rust pub fn first(&self) -> Option<&T> // Returns the first element of the slice, or `None` if it is empty. // Example: let v = [10, 40, 30]; assert_eq!(Some(&10), v.first()); let w: &[i32] = &[]; assert_eq!(None, w.first()); ``` -------------------------------- ### CloneToUninit Trait Methods Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.VecStore Documentation for the `clone_to_uninit` method, which performs copy-assignment from self to a destination. This is a nightly-only experimental API. ```APIDOC unsafe fn clone_to_uninit(&self, dest: [*mut u8]) - Performs copy-assignment from `self` to `dest`. - This is a nightly-only experimental API. ``` -------------------------------- ### VecStoreProducer Struct and Methods Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.VecStoreProducer The VecStoreProducer struct is an implementation for producing elements from a VecStore. It provides methods to create a producer, get its length, and check if it's empty. ```rust pub struct VecStoreProducer<'data, E: Element> { /* private fields */ } impl<'data, E: 'data + Element> VecStoreProducer<'data, E> { /// Creates a new VecStoreProducer. /// /// # Arguments /// /// * `current` - The starting index for the producer. /// * `end` - The ending index for the producer. /// * `store` - A reference to the VecStore containing the elements. /// /// # Returns /// /// A new instance of VecStoreProducer. pub fn new(current: usize, end: usize, store: &'data VecStore) -> Self; /// Returns the number of elements the producer can yield. pub fn len(&self) -> usize; /// Checks if the producer is empty. pub fn is_empty(&self) -> bool; } ``` -------------------------------- ### Iterate Over Slice Elements Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.VecStore The `iter()` method returns an iterator that yields references to each element in the slice from start to end. This is useful for simple traversal of slice contents. ```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); ``` -------------------------------- ### DiskStore API Documentation Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.DiskStore Provides API documentation for the DiskStore struct, including methods for creating a new store from disk, checking consistency, and retrieving the store size. It outlines parameters, return types, and potential errors. ```APIDOC DiskStore new_from_disk_with_path>(size: usize, data_path: P) -> Result Creates a new DiskStore instance from a specified path. Parameters: size: The desired size of the store. data_path: The path to the directory where the store data will be managed. Returns: A Result containing the new DiskStore instance or an error. is_consistent(store_range: usize, _branches: usize, config: &[StoreConfig]) -> Result Checks if the store is consistent based on the provided range and configuration. Parameters: store_range: The range of the store to check. _branches: The number of branches (unused in this context). config: A slice of StoreConfig to use for consistency check. Returns: A Result containing a boolean indicating consistency or an error. store_size(&self) -> usize Returns the current size of the store. Returns: The size of the store in bytes. ``` -------------------------------- ### MmapStore Initialization and Disk Loading Source: https://docs.rs/merkletree/0.23.0/src/merkletree/store/mmap.rs Handles the creation of a new MmapStore. If the data file already exists, it loads the store from disk; otherwise, it creates a new file for the on-disk store. This function is part of the Store trait implementation for MmapStore. ```rust impl Store for MmapStore { #[allow(unsafe_code)] fn new_with_config(size: usize, branches: usize, config: StoreConfig) -> Result { let data_path = StoreConfig::data_path(&config.path, &config.id); // If the specified file exists, load it from disk. if Path::new(&data_path).exists() { return Self::new_from_disk(size, branches, &config); } // Otherwise, create the file and allow it to be the on-disk store. let file = OpenOptions::new() .write(true) .read(true) .create_new(true) .open(&data_path)?; // ... rest of the implementation for creating a new file ... unimplemented!() } } ``` -------------------------------- ### Rust Iterator enumerate Source: https://docs.rs/merkletree/0.23.0/merkletree/store/struct.DiskIter Creates an iterator that yields pairs of the current iteration count (starting from 0) and the element from the original iterator. This is useful for tracking indices. ```rust fn enumerate(self) -> Enumerate where Self: Sized, ``` -------------------------------- ### Merkle Tree Crate Overview Source: https://docs.rs/merkletree/0.23.0/merkletree/all This section provides a high-level overview of the merkletree crate, including its purpose, license, source code links, and dependencies. It also indicates the percentage of the crate that is documented. ```rust /// merkletree 0.23.0 /// /// A light merkle tree implementation with SPV support and dependency agnostic. /// /// License: BSD-3-Clause /// /// Source: https://github.com/filecoin-project/merkle_light /// Crates.io: https://crates.io/crates/merkletree /// /// Dependencies: /// - anyhow ^1.0.23 /// - arrayref ^0.3.5 /// - log ^0.4.7 /// - memmap2 ^0.5.7 /// - positioned-io ^0.3 /// - rayon ^1.0.0 /// - serde ^1.0 /// - tempfile ^3.3 /// - typenum ^1.11.2 /// /// Development Dependencies: /// - byteorder ^1.3.1 /// - criterion ^0.3 /// - env_logger ^0.7.1 /// - rand ^0.7.3 /// - sha2 ^0.10.2 /// - tempfile ^3.3 /// - walkdir ^2.3.2 /// /// Documentation Coverage: 52.05% ```