### peek Method Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/buffered_queue.md Example of using the peek method. ```rust if let Some(item) = buffered.peek(&mut buf) { println!("Next item: {:?}", item); } ``` -------------------------------- ### enqueue Method Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/buffered_queue.md Example of using the enqueue method. ```rust buffered.enqueue(b"Hello").ok(); buffered.enqueue(b"World").ok(); ``` -------------------------------- ### Map Module - Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/module_structure.md Example demonstrating storing, fetching, and iterating items in MapStorage. ```rust use sequential_storage::map::{MapStorage, MapConfig}; let storage = MapStorage::::new( flash, const { MapConfig::new(0x1000..0x3000) }, NoCache::new() ); // Store a value storage.store_item(&mut buf, &key, &value).await?; // Fetch it back let result: Option = storage.fetch_item(&mut buf, &key).await?; // Iterate all let mut iter = storage.fetch_all_items(&mut buf).await?; while let Some((key, value)) = iter.next::(&mut buf).await? { // Process item } ``` -------------------------------- ### BufferedQueue Constructor Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/buffered_queue.md Example of creating a new BufferedQueue instance. ```rust use sequential_storage::queue::buffered::{BufferedQueue, OverflowPolicy}; let queue = QueueStorage::new(flash, config, cache); let buffered = BufferedQueue::<512, _, _>::new(queue, OverflowPolicy::ReturnError); ``` -------------------------------- ### drain_all Method Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/buffered_queue.md Example of using the drain_all method. ```rust buffered.drain_all().await?; // Wait until ring is empty ``` -------------------------------- ### Example: Initializing QueueStorage Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/queue_storage.md An example demonstrating how to initialize a QueueStorage instance with a flash interface, configuration, and a NoCache implementation. ```rust use sequential_storage::cache::NoCache; use sequential_storage::queue::{QueueConfig, QueueStorage}; let mut flash = /* initialize flash */; let mut storage = QueueStorage::new( flash, const { QueueConfig::new(0x1000..0x3000) }, NoCache::new() ); ``` -------------------------------- ### Cache Module - Example Usage Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/module_structure.md Example of how to use NoCache and PagePointerCache. ```rust use sequential_storage::cache::{NoCache, PagePointerCache}; let no_cache = NoCache::new(); let cached = PagePointerCache::<8>::new(); ``` -------------------------------- ### len Method Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/buffered_queue.md Example of using the len method. ```rust println!("Buffered items: {}", buffered.len()); ``` -------------------------------- ### OverflowPolicy Selection Examples Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/buffered_queue.md Examples demonstrating how to select OverflowPolicy variants. ```rust // Strict: fail on overflow let buffered = BufferedQueue::<512, _, _>::new(queue, OverflowPolicy::ReturnError); // Lossy: keep newest data let buffered = BufferedQueue::<512, _, _>::new(queue, OverflowPolicy::EvictOldest); ``` -------------------------------- ### pop Method Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/buffered_queue.md Example of using the asynchronous pop method. ```rust match buffered.pop(&mut buf).await { Ok(Some(item)) => println!("Popped: {:?}", item), Ok(None) => println!("Queue empty"), Err(e) => eprintln!("Error: {:?}", e), } ``` -------------------------------- ### Reusing Caches Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/cache_types.md Example demonstrating how to reuse a cache across storage instances. ```rust let (flash, cache) = storage.destroy(); // Cache is valid if flash wasn't modified externally let new_storage = MapStorage::new(flash, config, cache); ``` -------------------------------- ### Reusing Configuration Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/configuration.md Shows how to reuse a configuration across multiple storage instances. ```rust const MAP_CONFIG: MapConfig = unsafe { MapConfig::new(0x1000..0x5000) }; // Multiple storages with same config (if flash ranges don't overlap) let storage1 = MapStorage::new(flash1, MAP_CONFIG, cache1); let storage2 = MapStorage::new(flash2, MAP_CONFIG, cache2); ``` -------------------------------- ### Example: Pushing Data to QueueStorage Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/queue_storage.md An example showing how to push data to the queue, with the option to overwrite older data if the queue is full. ```rust let data = b"Hello, world!"; storage.push(data, true).await?; // Overwrite old data if needed ``` -------------------------------- ### Multiple Storages Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/cache_types.md Example illustrating the correct usage of separate caches for different storage instances. ```rust let cache1 = PagePointerCache::new(); let cache2 = PagePointerCache::new(); let storage1 = MapStorage::new(flash1, config1, cache1); let storage2 = MapStorage::new(flash2, config2, cache2); // ✓ OK // Invalid - reusing cache1 with different storage: // let storage3 = MapStorage::new(flash3, config3, cache1); // ✗ Wrong ``` -------------------------------- ### SharedRamRing Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/buffered_queue.md Example demonstrating the usage of SharedRamRing in interrupt handlers and main tasks. ```rust #[cfg(feature = "shared-ram-ring")] { use sequential_storage::queue::buffered::SharedRamRing; // In interrupt handler let shared_ring: &'static SharedRamRing<512, MyFlash, MyCache> = /* global */; shared_ring.with(|buffered| { buffered.enqueue(interrupt_data).ok(); }); // In main task shared_ring.with(|buffered| { buffered.drain_one().await.ok(); }); } ``` -------------------------------- ### Runtime Validation Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/README.md Shows how to use `try_new()` for fallible runtime validation of configurations. ```rust if let Some(config) = MapConfig::try_new(0x1000..0x5000) { // Valid } ``` -------------------------------- ### HeapPageStateCache Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/cache_types.md Example usage of HeapPageStateCache with MapStorage. ```rust #[cfg(feature = "alloc")] { let cache = HeapPageStateCache::new(8); // Runtime page count let storage = MapStorage::new(flash, config, cache); } ``` -------------------------------- ### Alignment Requirements Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/configuration.md Demonstrates valid and invalid flash range alignments based on flash page size. ```rust // If flash page size is 2KB (0x800): const VALID_START: u32 = 0x08000000; // Aligned to 0x800 const INVALID_START: u32 = 0x08000100; // NOT aligned // Try to create config - will fail const _: Option> = MapConfig::try_new(INVALID_START..INVALID_START + 0x2000); ``` -------------------------------- ### Producer-Consumer Pattern Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/buffered_queue.md Example illustrating the producer-consumer pattern using a shared buffered queue. ```rust // Shared buffered queue static BUFFERED: Mutex> = Mutex::new(/* ... */); // Producer task (fast, synchronous) async fn producer() { for i in 0..1000 { BUFFERED.lock(|q| { q.enqueue(&format!("data-{}", i).as_bytes()).ok(); }); } } // Consumer task (handles flash latency) async fn consumer() { loop { BUFFERED.lock(|q| { q.drain_one().await.ok(); }); Timer::after(Duration::from_millis(10)).await; } } ``` -------------------------------- ### drain_one Method Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/buffered_queue.md Example of using drain_one in a background loop. ```rust // Drain in a background loop async fn drain_loop(buffered: &mut BufferedQueue<512, _, _>) { loop { buffered.drain_one().await.ok(); embassy_time::Timer::after(Duration::from_millis(100)).await; } } ``` -------------------------------- ### MapStorage Constructor Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/map_storage.md An example demonstrating how to create a new MapStorage instance with a specific key type, flash interface, configuration, and cache implementation. ```rust use sequential_storage::cache::NoCache; use sequential_storage::map::{MapConfig, MapStorage}; let mut flash = /* initialize flash */; let mut storage = MapStorage::::new( flash, const { MapConfig::new(0x1000..0x3000) }, NoCache::new() ); ``` -------------------------------- ### Example Usage of PartialEq Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/types.md Demonstrates how to use the `PartialEq` implementation to check for specific error conditions. ```rust if result == Err(Error::FullStorage) { // Handle full storage } ``` -------------------------------- ### MapConfig Example: Runtime Usage with try_new Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/configuration.md Shows how to use MapConfig created with try_new in a runtime context. ```rust if let Some(config) = MapConfig::try_new(0x1000..0x5000) { let storage = MapStorage::new(flash, config, cache); } else { eprintln!("Invalid map configuration"); } ``` -------------------------------- ### STM32H7 Internal Flash Configuration Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/configuration.md Example of configuring MapConfig and QueueConfig for STM32H7 internal flash. ```rust // STM32H7 has 256-byte words, pages are 2KB const FLASH_START: u32 = 0x08000000; const FLASH_SIZE: u32 = 2 * 1024 * 1024; // 2MB const PAGE_SIZE: usize = 2 * 1024; // 2KB // Reserve 64KB (32 pages) for map starting at 0x100000 const MAP_CONFIG: MapConfig = unsafe { MapConfig::new(0x08100000..0x08110000) // 64KB }; // Reserve 128KB for queue const QUEUE_CONFIG: QueueConfig = unsafe { QueueConfig::new(0x08110000..0x08130000) // 128KB }; ``` -------------------------------- ### Example: Peeking at Data in QueueStorage Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/queue_storage.md An example showing how to peek at the oldest item in the queue without removing it, using a data buffer. ```rust let mut data_buffer = [0; 256]; if let Some(item) = storage.peek(&mut data_buffer).await? { println!("Next item (not removed): {:?}", item); } ``` -------------------------------- ### NoCache Constructor Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/cache_types.md Example of creating a new instance of NoCache and using it with MapStorage. ```rust let cache = NoCache::new(); let storage = MapStorage::new(flash, config, cache); ``` -------------------------------- ### FullStorage Error Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/errors.md Example of handling the FullStorage error variant, which occurs when there is no space available to store an item. ```rust match storage.push(data, false).await { Err(Error::FullStorage) => { println!("Queue full, retrying with overwrite"); storage.push(data, true).await?; } _ => {} } ``` -------------------------------- ### QueueConfig Example: Compile-time Validation Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/configuration.md Illustrates compile-time validation for QueueConfig using a const block. ```rust const QUEUE_CONFIG: QueueConfig = unsafe { QueueConfig::new(0x5000..0x9000) }; ``` -------------------------------- ### fetch_item Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/map_storage.md An example demonstrating how to use the 'fetch_item' function to retrieve a u32 value stored under a specific key and handle the result. ```rust let mut data_buffer = [0; 128]; // Fetch a u32 value stored under key 42 match storage.fetch_item::(&mut data_buffer, &42).await { Ok(Some(value)) => println!("Found: {}", value), Ok(None) => println!("Key not found"), Err(e) => println!("Error: {:?}", e), } ``` -------------------------------- ### Compile-Time Validation Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/README.md Demonstrates how to use `const` for compile-time validation of configurations. ```rust const MAP_CONFIG: MapConfig = unsafe { MapConfig::new(0x1000..0x5000) // Validation at compile time }; ``` -------------------------------- ### MapConfig Example: Compile-time and Runtime Validation Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/configuration.md Demonstrates how to create MapConfig using compile-time const blocks or runtime try_new. ```rust // Compile-time validation with const block const MAP_CONFIG: MapConfig = unsafe { MapConfig::new(0x1000..0x5000) // Must be valid at compile time }; // Or runtime validation with try_new let config = MapConfig::try_new(0x1000..0x5000)?; ``` -------------------------------- ### Example: Popping Data from QueueStorage Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/queue_storage.md An example demonstrating how to pop the oldest item from the queue using a data buffer and handling the result. ```rust let mut data_buffer = [0; 256]; match storage.pop(&mut data_buffer).await? { Some(item) => println!("Popped: {:?}", item), None => println!("Queue is empty"), } ``` -------------------------------- ### PageStateCache Constructor Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/cache_types.md Example of creating a PageStateCache for a specific flash size and page count, and using it with MapStorage. ```rust const FLASH_SIZE: u32 = 32 * 1024; const PAGE_SIZE: usize = 4 * 1024; const PAGE_COUNT: usize = (FLASH_SIZE / PAGE_SIZE as u32) as usize; // = 8 let cache = PageStateCache::::new(); let storage = MapStorage::new(flash, config, cache); ``` -------------------------------- ### Storage Error Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/errors.md Example of handling the Storage error variant, which occurs when an underlying flash operation fails. ```rust match storage.fetch_item(&mut buf, &key).await { Err(Error::Storage { value }) => { eprintln!("Flash error: {:?}", value); // Retry or abort } _ => {} } ``` -------------------------------- ### store_item Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/map_storage.md A concise example showing how to store a u32 value under a u8 key using the 'store_item' function. ```rust storage.store_item(&mut data_buffer, &42u8, &1024u32).await?; ``` -------------------------------- ### BufferedQueue Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/module_structure.md Demonstrates the usage of BufferedQueue for RAM-buffered queue operations, including synchronous enqueue and asynchronous draining. ```rust use sequential_storage::queue::buffered::{BufferedQueue, OverflowPolicy}; let queue = QueueStorage::new(flash, config, cache); let mut buffered = BufferedQueue::<512, _, _>::new(queue, OverflowPolicy::ReturnError); // Fast synchronous enqueue buffered.enqueue(b"data").ok(); // Async drain to flash buffered.drain_all().await?; // Pop from queue (flash first, then RAM) if let Some(item) = buffered.pop(&mut buf).await? { println!("Item: {:?}", item); } ``` -------------------------------- ### remove_item Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/map_storage.md An example demonstrating the usage of the 'remove_item' function to remove a value associated with a u8 key. ```rust storage.remove_item(&mut data_buffer, &42u8).await?; ``` -------------------------------- ### LogicBug Error Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/errors.md Example of handling the LogicBug error variant, which signifies an internal library logic error. ```rust match storage.fetch_item(&mut buf, &key).await { Err(Error::LogicBug) => { eprintln!("INTERNAL LIBRARY BUG! Please report."); storage.erase_all().await?; } _ => {} } ``` -------------------------------- ### Cache Invalidation Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/cache_types.md Example showing automatic cache invalidation upon operation interruption. ```rust // If an operation returns an error, cache may be marked "dirty" // Next operation automatically invalidates and rebuilds cache state match storage.store_item(&mut buf, &key, &value).await { Err(Error::Corrupted) => { // Cache is invalidated, safe to retry } _ => {} } ``` -------------------------------- ### SerializationError Display Implementation Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/types.md Provides an example of how to implement the Display trait for SerializationError to provide human-readable error messages. ```rust match error { SerializationError::BufferTooSmall => "Buffer too small", SerializationError::InvalidData => "Invalid data", SerializationError::InvalidFormat => "Invalid format", SerializationError::Custom(code) => format!("Custom error: {code}"), } ``` -------------------------------- ### BufferTooSmall Recovery Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/errors.md Demonstrates how to recover from a BufferTooSmall error by allocating a larger buffer and retrying the fetch operation. ```rust match storage.fetch_item(&mut buf, &key).await { Err(Error::BufferTooSmall(needed)) => { let mut larger_buf = vec![0; needed]; storage.fetch_item(&mut larger_buf, &key).await? } _ => {} } ``` -------------------------------- ### MapStorage (Key-Value) Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/README.md Example usage of MapStorage for key-value operations. ```rust use sequential_storage::map::{MapStorage, MapConfig}; use sequential_storage::cache::NoCache; let mut storage = MapStorage::::new( flash, const { MapConfig::new(0x1000..0x5000) }, NoCache::new() ); // Store storage.store_item(&mut buffer, &key, &value).await?; // Fetch let result: Option = storage.fetch_item(&mut buffer, &key).await?; // Iterate let mut iter = storage.fetch_all_items(&mut buffer).await?; while let Some((key, value)) = iter.next::(&mut buffer).await? { // Process } ``` -------------------------------- ### QueueStorage (FIFO) Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/README.md Example usage of QueueStorage for FIFO queue operations. ```rust use sequential_storage::queue::{QueueStorage, QueueConfig}; let mut storage = QueueStorage::new( flash, const { QueueConfig::new(0x5000..0x9000) }, NoCache::new() ); // Push storage.push(data, false).await?; // Pop if let Some(item) = storage.pop(&mut buffer).await? { // Process } // Iterate let mut iter = storage.iter().await?; while let Some(entry) = iter.next(&mut buffer).await? { // Peek or pop entry.pop().await?; } ``` -------------------------------- ### Error Handling with ? Operator Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/errors.md Example demonstrating how to use the ? operator for error propagation and logging when fetching an item from sequential storage. ```rust storage.fetch_item(&mut buf, &key).await .map_err(|e| format!("Failed to fetch: {}", e))? ``` -------------------------------- ### Key Trait Example Implementation Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/types.md Demonstrates how to implement the Key trait for a custom struct with a u32 ID and a fixed-size byte array name. ```rust // Using a primitive key storage.store_item(&mut buffer, &42u8, &value).await?; // Custom key implementation struct MyKey { id: u32, name: [u8; 32], } impl Key for MyKey { fn serialize_into(&self, buffer: &mut [u8]) -> Result { if buffer.len() < 36 { return Err(SerializationError::BufferTooSmall); } buffer[..4].copy_from_slice(&self.id.to_le_bytes()); buffer[4..36].copy_from_slice(&self.name); Ok(36) } fn deserialize_from(buffer: &[u8]) -> Result<(Self, usize), SerializationError> { if buffer.len() < 36 { return Err(SerializationError::BufferTooSmall); } let id = u32::from_le_bytes(buffer[..4].try_into().unwrap()); let mut name = [0u8; 32]; name.copy_from_slice(&buffer[4..36]); Ok((MyKey { id, name }, 36)) } } ``` -------------------------------- ### External SPI Flash Configuration Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/configuration.md Example of configuring generic SPI flash with specific page and word sizes for map and queue configurations. ```rust // Generic SPI flash: 4KB pages, 1-byte words const FLASH_START: u32 = 0x00000000; // 32KB for map (8 pages of 4KB each) const MAP_CONFIG: MapConfig = unsafe { MapConfig::new(0x00000000..0x00008000) }; // 64KB for queue (16 pages) const QUEUE_CONFIG: QueueConfig = unsafe { QueueConfig::new(0x00008000..0x00018000) }; ``` -------------------------------- ### ItemTooBig Recovery Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/errors.md Illustrates recovery from an ItemTooBig error, suggesting solutions like splitting the value or increasing the page size. ```rust match storage.store_item(&mut buf, &key, &large_value).await { Err(Error::ItemTooBig) => { println!("Value too large for flash page size"); // Split value into multiple items or increase page size } _ => {} } ``` -------------------------------- ### SerializationError Recovery Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/errors.md Shows how to handle different SerializationError variants, such as InvalidFormat and BufferTooSmall, providing specific recovery messages. ```rust match storage.fetch_item::(&mut buf, &key).await { Err(Error::SerializationError(SerializationError::InvalidFormat)) => { println!("Data corrupted or format mismatch"); // May need to use different Value type or check data } Err(Error::SerializationError(SerializationError::BufferTooSmall)) => { println!("Need larger buffer"); } _ => {} } ``` -------------------------------- ### Periodic drain in background Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/buffered_queue.md Example of how to periodically drain the buffered queue in a background task. ```rust // Periodic drain in background async fn drain_periodically(buffered: &mut BufferedQueue<512, _, _>) { loop { Timer::after(Duration::from_secs(5)).await; buffered.drain_all().await.ok(); } } ``` -------------------------------- ### BufferedQueue (RAM-Buffered) Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/README.md Example usage of BufferedQueue for RAM-buffered queue operations. ```rust use sequential_storage::queue::buffered::{BufferedQueue, OverflowPolicy}; let queue = QueueStorage::new(flash, config, cache); let mut buffered = BufferedQueue::<512, _, _>::new(queue, OverflowPolicy::ReturnError); // Fast synchronous enqueue buffered.enqueue(data)?; // Async drain to flash buffered.drain_all().await?; // Pop from queue if let Some(item) = buffered.pop(&mut buffer).await? { // Process } ``` -------------------------------- ### Drain on demand Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/buffered_queue.md Example of draining the buffered queue on demand at critical checkpoints. ```rust // Or on demand critical_action().await?; buffered.drain_all().await?; // Ensure flush to flash ``` -------------------------------- ### Corrupted Error Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/errors.md Example of handling the Corrupted error variant, which indicates flash memory corruption. It shows the automatic repair process and recovery options. ```rust match storage.fetch_item(&mut buf, &key).await { Err(Error::Corrupted) => { println!("Corruption detected but auto-repaired"); // If returned again after auto-repair, flash is unrecoverable storage.erase_all().await?; } _ => {} } ``` -------------------------------- ### Error Logging with Context Pattern Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/errors.md An example of logging errors with context, showing how to print specific error messages for different error types like Storage, FullStorage, or other unexpected errors. ```rust match storage.store_item(&mut buf, &key, &value).await { Ok(()) => {}, Err(Error::Storage { value }) => { eprintln!("Flash error: {:?}", value); } Err(Error::FullStorage) => { eprintln!("Storage full, cleanup needed"); } Err(e) => { eprintln!("Unexpected error: {:?}", e); } } ``` -------------------------------- ### Get item overhead size Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/queue_storage.md Returns the minimum header overhead per item in bytes. ```rust pub const fn item_overhead_size() -> u32 ``` ```rust let overhead = QueueStorage::::item_overhead_size(); ``` -------------------------------- ### Try-Recover Error Handling Pattern Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/errors.md An example of the Try-Recover pattern for handling errors like Corrupted or FullStorage, allowing for automatic repair or specific actions. ```rust match operation().await { Err(Error::Corrupted) => { // Automatically repaired, safe to retry operation().await? } Err(Error::FullStorage) => { // For queue, allow overwrite queue.push(data, true).await? } result => result? } ``` -------------------------------- ### Value Trait Zero-Copy Example Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/types.md Illustrates implementing the Value trait for zero-copy deserialization using a struct that borrows from the input buffer. ```rust // Store and fetch a slice without copying struct MyData<'a> { items: &'a [u8], } impl<'a> Value<'a> for MyData<'a> { fn serialize_into(&self, buffer: &mut [u8]) -> Result { // Serialize length then data let len = (self.items.len() as u16).to_le_bytes(); let total = 2 + self.items.len(); if buffer.len() < total { return Err(SerializationError::BufferTooSmall); } buffer[..2].copy_from_slice(&len); buffer[2..total].copy_from_slice(self.items); Ok(total) } fn deserialize_from(buffer: &'a [u8]) -> Result<(Self, usize), SerializationError> { if buffer.len() < 2 { return Err(SerializationError::BufferTooSmall); } let len = u16::from_le_bytes([buffer[0], buffer[1]]) as usize; if buffer.len() < 2 + len { return Err(SerializationError::BufferTooSmall); } Ok((MyData { items: &buffer[2..2+len] }, 2 + len)) } } ``` -------------------------------- ### Get mutable access to flash Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/queue_storage.md Provides mutable access to the underlying flash. Direct flash manipulation is at your own risk. ```rust pub const fn flash(&mut self) -> &mut S ``` -------------------------------- ### Mock Flash for Testing Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/README.md Shows how to enable and use mock flash for unit tests. ```rust #[cfg(any(test, feature = "_test"))] pub mod mock_flash; ``` -------------------------------- ### Mock Flash for Testing Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/configuration.md Configuration for a mock flash type used in testing, with specified word and page sizes. ```rust // Test flash: 4-byte words, 64-byte pages type TestFlash = MockFlashBase<4, 4, 64>; const TEST_MAP_CONFIG: MapConfig = unsafe { MapConfig::new(0x000..0x400) // 1KB, 16 pages }; const TEST_QUEUE_CONFIG: QueueConfig = unsafe { QueueConfig::new(0x400..0x800) // 1KB }; ``` -------------------------------- ### Get flash address range Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/queue_storage.md Returns the flash address range in use. ```rust pub const fn flash_range(&self) -> Range ``` -------------------------------- ### MapConfig Constructor: new (panic on invalid config) Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/configuration.md Creates a map configuration with compile-time validation. Panics if the configuration is invalid. ```rust pub const fn new(flash_range: Range) -> Self ``` -------------------------------- ### Full Featured Set (for documentation) Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/module_structure.md TOML configuration for a comprehensive feature set of the sequential-storage crate, often used for documentation purposes. ```toml sequential-storage = { version = "7.2", features = ["std", "alloc", "postcard", "heapless", "heapless-09", "arrayvec"] } ``` -------------------------------- ### With Heap Allocation Feature Set Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/module_structure.md TOML configuration for enabling heap allocation in the sequential-storage crate. ```toml sequential-storage = { version = "7.2", features = ["alloc"] } ``` -------------------------------- ### Buffer Size Negotiation Pattern Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/errors.md Demonstrates a pattern for negotiating buffer sizes, where a smaller buffer is automatically resized if an operation reports it's too small. ```rust let mut buf = [0; 256]; loop { match storage.fetch_item::(&mut buf, &key).await { Ok(val) => break Ok(val), Err(Error::BufferTooSmall(needed)) if needed <= 2048 => { buf = vec![0; needed].leak(); // Allocate larger buffer continue; } Err(e) => break Err(e), } } ``` -------------------------------- ### Get mutable data buffer from entry Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/queue_storage.md Consumes the entry and returns a mutable reference to its data buffer. ```rust pub fn into_buf(self) -> &'d mut [u8] ``` ```rust let item = entry.into_buf(); println!("Item data: {:?}", item); ``` -------------------------------- ### MapConfig Constructor: try_new (fallible) Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/configuration.md Creates a map configuration with compile-time validation. Returns None if invalid. ```rust pub const fn try_new(flash_range: Range) -> Option ``` -------------------------------- ### QueueStorage Constructor: new Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/queue_storage.md The constructor for QueueStorage, which takes flash storage, configuration, and a cache implementation. ```rust pub const fn new(storage: S, config: QueueConfig, cache: C) -> Self ``` -------------------------------- ### Remove item from flash and get data Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/queue_storage.md Removes this item from flash and returns its data. This operation requires `MultiwriteNorFlash`. ```rust pub async fn pop(self) -> Result<&'d mut [u8], Error> where S: MultiwriteNorFlash ``` ```rust while let Some(entry) = iterator.next(&mut data_buffer).await? { let item = entry.pop().await?; // Remove and get data process(item); } ``` -------------------------------- ### Minimal Feature Set (no_std, no_alloc) Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/module_structure.md TOML configuration for the minimal feature set of the sequential-storage crate, suitable for no_std and no_alloc environments. ```toml sequential-storage = "7.2" ``` -------------------------------- ### Top-Level Re-exports Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/module_structure.md The crate root re-exports main types for convenience, allowing direct access. ```rust pub use map::SerializationError; pub use cache::CacheImpl; pub enum Error { /* ... */ } ``` ```rust use sequential_storage::Error; use sequential_storage::map::MapStorage; ``` -------------------------------- ### peek Method Signature Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/buffered_queue.md Signature for the synchronous peek method, which peeks at the oldest item (flash first, then RAM). ```rust pub fn peek(&mut self, buf: &mut [u8]) -> Option<&[u8]> ``` -------------------------------- ### BufferedQueue Constructor Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/buffered_queue.md Creates a new buffered queue wrapping a QueueStorage. ```rust pub fn new( storage: QueueStorage, overflow_policy: OverflowPolicy, ) -> Self ``` -------------------------------- ### SharedRamRing Constructor Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/buffered_queue.md Constructor for the SharedRamRing. ```rust pub fn new( buffered: BufferedQueue, ) -> Self ``` -------------------------------- ### QueueConfig Type Signature Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/configuration.md Defines the structure for queue configuration, generic over the NOR flash type. ```rust pub struct QueueConfig ``` -------------------------------- ### QueueIteratorEntry Deref Implementations Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/queue_storage.md Demonstrates how QueueIteratorEntry implements Deref and DerefMut for slice access. ```rust while let Some(entry) = iterator.next(&mut data_buffer).await? { // Access as &[u8] let slice: &[u8] = &entry; // Access as &mut [u8] let mut_slice: &mut [u8] = &mut entry; } ``` -------------------------------- ### is_empty Method Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/buffered_queue.md Checks if the RAM ring is empty. ```rust pub fn is_empty(&self) -> bool ``` ```rust if buffered.is_empty() { println!("RAM ring is empty (flash may still have items)"); } ``` -------------------------------- ### fetch_all_items Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/map_storage.md Creates an iterator over all stored items in flash from oldest to newest. ```rust pub async fn fetch_all_items( &mut self, data_buffer: &mut [u8], ) -> Result, Error> ``` ```rust let mut iterator = storage.fetch_all_items(&mut data_buffer).await?; while let Some((key, value)) = iterator.next::(&mut data_buffer).await? { println!("Key: {:?}, Value: {}", key, value); } ``` -------------------------------- ### HeapKeyPointerCache Constructor Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/cache_types.md Constructor for HeapKeyPointerCache. ```rust pub fn new(page_count: usize, key_capacity: usize) -> Self ``` -------------------------------- ### MapConfig Type Signature Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/configuration.md Defines the structure for map configuration, generic over the NOR flash type. ```rust pub struct MapConfig where S: embedded_storage_async::nor_flash::NorFlash, ``` -------------------------------- ### Consume storage Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/queue_storage.md Consumes the storage and returns the underlying flash and cache. ```rust pub fn destroy(self) -> (S, C) ``` ```rust let (flash, cache) = storage.destroy(); ``` -------------------------------- ### HeapPageStateCache Constructor Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/cache_types.md Constructor for HeapPageStateCache. ```rust pub fn new(page_count: usize) -> Self ``` -------------------------------- ### MapStorage Constructor: new Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/map_storage.md The signature for the 'new' constructor function of MapStorage, detailing the parameters for storage, configuration, and cache. ```rust pub const fn new(storage: S, config: MapConfig, cache: C) -> Self ``` -------------------------------- ### Calculate available space Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/queue_storage.md Calculates the approximate available space in the queue in bytes. ```rust pub async fn space_left(&mut self) -> Result> ``` ```rust let available = storage.space_left().await?; println!("Available space: {} bytes", available); ``` -------------------------------- ### Effective WORD_SIZE Calculation Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/configuration.md The library determines the effective WORD_SIZE based on WRITE_SIZE and READ_SIZE. ```rust const WORD_SIZE: usize = max(WRITE_SIZE, READ_SIZE); ``` -------------------------------- ### Page State Machine Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/README.md Illustrates the state transitions for a page within the storage system. ```text Open → PartialOpen → Closed → (next cycle) ``` -------------------------------- ### item_overhead_size Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/map_storage.md Returns the minimum header overhead per stored item. ```rust pub const fn item_overhead_size() -> u32 ``` ```rust let overhead = MapStorage::::item_overhead_size(); println!("Per-item overhead: {} bytes", overhead); ``` -------------------------------- ### drain_all Method Signature Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/buffered_queue.md Signature for the asynchronous drain_all method, which drains all items from the RAM ring to flash. ```rust pub async fn drain_all(&mut self) -> Result<(), Error> ``` -------------------------------- ### MapItemIter::next Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/map_storage.md Fetches the next (key, value) pair from the iterator. ```rust pub async fn next<'a, V: Value<'a>>( &mut self, data_buffer: &'a mut [u8], ) -> Result, Error> ``` ```rust let mut iterator = storage.fetch_all_items(&mut data_buffer).await?; while let Some((key, value)) = iterator.next::(&mut data_buffer).await? { // Process key and value } ``` -------------------------------- ### Iterate over queue items Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/queue_storage.md Creates an iterator to traverse all items in the queue from oldest to newest. Iteration is non-destructive. ```rust pub async fn iter(&mut self) -> Result, Error> ``` ```rust let mut iterator = storage.iter().await?; while let Some(entry) = iterator.next(&mut data_buffer).await? { println!("Item: {:?}", &entry[..]); // Optionally pop the item: entry.pop().await?; } ``` -------------------------------- ### len Method Signature Source: https://github.com/tweedegolf/sequential-storage/blob/master/_autodocs/buffered_queue.md Signature for the synchronous len method, which returns the number of items currently in the RAM ring. ```rust pub fn len(&self) -> usize ```