### Example usage of as_view Source: https://docs.rs/heapless/0.9.3/heapless/mpmc/type.Queue.html Demonstrates obtaining a QueueView reference from a Queue. Type coercion is also shown as an alternative. ```rust let queue: Queue = Queue::new(); let view: &QueueView = queue.as_view(); ``` ```rust let queue: Queue = Queue::new(); let view: &QueueView = &queue; ``` -------------------------------- ### Consumer is_empty Example Source: https://docs.rs/heapless/0.9.3/heapless/spsc/struct.Consumer.html Demonstrates how to check if the consumer queue is empty. This is useful before attempting to dequeue items. ```rust use heapless::spsc::Queue; let mut queue: Queue = Queue::new(); let (mut producer, mut consumer) = queue.split(); assert!(consumer.is_empty()); ``` -------------------------------- ### FnvIndexMap::first Source: https://docs.rs/heapless/0.9.3/heapless/index_map/type.FnvIndexMap.html Get the first key-value pair. Computes in O(1) time. ```APIDOC ## FnvIndexMap::first ### Description Get the first key-value pair. Computes in _O_(1) time. ### Method `first()` ### Returns An `Option` containing a reference to the first key-value pair, or `None` if the map is empty. ``` -------------------------------- ### Iterate Over Slice Elements Source: https://docs.rs/heapless/0.9.3/heapless/history_buf/struct.HistoryBufInner.html Use `iter` to get an iterator that yields all items from the start to the end of the 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); ``` -------------------------------- ### Example: Initializing and Checking Producer State Source: https://docs.rs/heapless/0.9.3/heapless/spsc/struct.Producer.html Demonstrates how to create a new queue, split it into producer and consumer, and check if the producer initially reports the queue as empty. ```rust use heapless::spsc::Queue; let mut queue: Queue = Queue::new(); let (mut producer, mut consumer) = queue.split(); assert!(producer.is_empty()); ``` -------------------------------- ### Queue Creation and Basic Operations Source: https://docs.rs/heapless/0.9.3/heapless/mpmc/type.Queue.html Demonstrates how to create a new queue, check its capacity, and perform enqueue and dequeue operations. Note that the `new` method is deprecated. ```APIDOC ## Queue Operations ### Method: `new()` **Description**: Creates an empty queue. This method is deprecated due to potential deadlocks in certain concurrent scenarios. Use with caution or consider alternatives. ### Method: `capacity()` **Description**: Returns the maximum number of elements the queue can hold. **Usage**: `queue.capacity()` ### Method: `enqueue(item: T)` **Description**: Adds an `item` to the end of the queue. Returns `Ok(())` if successful, or `Err(item)` if the queue is full. **Usage**: `queue.enqueue(item)` ### Method: `dequeue()` **Description**: Returns the item at the front of the queue, or `None` if the queue is empty. **Usage**: `queue.dequeue()` ### Method: `as_view()` **Description**: Get a reference to the `Queue`, erasing the `N` const-generic. **Usage**: `queue.as_view()` ### Method: `as_mut_view()` **Description**: Get a mutable reference to the `Queue`, erasing the `N` const-generic. **Usage**: `queue.as_mut_view()` ### Example Usage: ```rust use heapless::mpmc::Queue; // Note: `new()` is deprecated. Use `#[expect(deprecated)]` if necessary. #[allow(deprecated)] let mut queue: Queue = Queue::new(); assert_eq!(queue.capacity(), 2); // Enqueue an item match queue.enqueue(1) { Ok(_) => println!("Enqueued 1"), Err(item) => println!("Queue full, failed to enqueue {}", item), } // Dequeue an item match queue.dequeue() { Some(item) => println!("Dequeued {}", item), None => println!("Queue empty"), } // Get a view let view = queue.as_view(); let mut_view = queue.as_mut_view(); ``` ``` -------------------------------- ### Iterate Over Exact Chunks From the End of a Slice Source: https://docs.rs/heapless/0.9.3/heapless/history_buf/struct.HistoryBufInner.html Use `rchunks_exact` to get an iterator over non-overlapping chunks of a specified size, starting from the end of the slice. Elements that do not form a full chunk are available via `remainder()`. Panics if `chunk_size` is zero. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks_exact(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert!(iter.next().is_none()); assert_eq!(iter.remainder(), &['l']); ``` -------------------------------- ### Example: Checking if a SortedLinkedList is empty Source: https://docs.rs/heapless/0.9.3/heapless/sorted_linked_list/type.SortedLinkedListView.html Demonstrates the `is_empty` method by checking the status of a new `SortedLinkedList` and after pushing an element. ```rust use heapless::sorted_linked_list::{Max, SortedLinkedList}; let mut ll: SortedLinkedList<_, Max, 3, u8> = SortedLinkedList::new_u8(); assert_eq!(ll.is_empty(), true); ll.push(1).unwrap(); assert_eq!(ll.is_empty(), false); ``` -------------------------------- ### Initialize and Use HistoryBufView Source: https://docs.rs/heapless/0.9.3/heapless/history_buf/type.HistoryBufView.html Demonstrates initializing a HistoryBuf, obtaining a mutable view, writing elements, and calculating the average of the buffer's contents. ```rust use heapless::history_buf::{HistoryBuf, HistoryBufView}; // Initialize a new buffer with 8 elements. let mut owned_buf = HistoryBuf::<_, 8>::new(); let buf: &mut HistoryBufView<_> = &mut owned_buf; // Starts with no data assert_eq!(buf.recent(), None); buf.write(3); buf.write(5); buf.extend(&[4, 4]); // The most recent written element is a four. assert_eq!(buf.recent(), Some(&4)); // To access all elements in an unspecified order, use `as_slice()`. for el in buf.as_slice() { println!("{:?}", el); } // Now we can prepare an average of all values, which comes out to 4. let avg = buf.as_slice().iter().sum::() / buf.len(); assert_eq!(avg, 4); ``` -------------------------------- ### Iterate Over Chunks From the End of a Slice Source: https://docs.rs/heapless/0.9.3/heapless/history_buf/struct.HistoryBufInner.html Use `rchunks` to get an iterator over non-overlapping chunks of a specified size, starting from the end of the slice. The last chunk may be smaller if the slice length is not divisible by `chunk_size`. Panics if `chunk_size` is zero. ```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()); ``` -------------------------------- ### Remove prefix from Vec slice Source: https://docs.rs/heapless/0.9.3/heapless/vec/struct.VecInner.html Use `strip_prefix` to get a subslice with a specified prefix removed. Returns `None` if the slice does not start with the prefix. An empty prefix results in the original slice. If the prefix matches the entire slice, an empty slice is returned. ```rust 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); ``` ```rust let prefix : &str = "he"; assert_eq!(b"hello".strip_prefix(prefix.as_bytes()), Some(b"llo".as_ref())); ``` -------------------------------- ### BinaryHeap Usage Example Source: https://docs.rs/heapless/0.9.3/heapless/binary_heap/type.BinaryHeap.html Demonstrates the basic usage of BinaryHeap for a max-heap, including pushing, peeking, popping, and checking length and emptiness. ```APIDOC ## BinaryHeap Usage Example ### Description This example shows how to create and use a `BinaryHeap` as a max-heap. It covers common operations like `new`, `push`, `peek`, `len`, `pop`, `clear`, and `is_empty`. ### Code ```rust use heapless::binary_heap::{BinaryHeap, Max}; let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new(); // We can use peek to look at the next item in the heap. In this case, // there's no items in there yet so we get None. assert_eq!(heap.peek(), None); // Let's add some scores... heap.push(1).unwrap(); heap.push(5).unwrap(); heap.push(2).unwrap(); // Now peek shows the most important item in the heap. assert_eq!(heap.peek(), Some(&5)); // We can check the length of a heap. assert_eq!(heap.len(), 3); // We can iterate over the items in the heap, although they are returned in // a random order. for x in &heap { println!("{}", x); } // If we instead pop these scores, they should come back in order. assert_eq!(heap.pop(), Some(5)); assert_eq!(heap.pop(), Some(2)); assert_eq!(heap.pop(), Some(1)); assert_eq!(heap.pop(), None); // We can clear the heap of any remaining items. heap.clear(); // The heap should now be empty. assert!(heap.is_empty()) ``` ``` -------------------------------- ### Example: Checking if a SortedLinkedList is full Source: https://docs.rs/heapless/0.9.3/heapless/sorted_linked_list/type.SortedLinkedList.html Shows how to use the `is_full` method to check if a `SortedLinkedList` has reached its capacity. Demonstrates the state before, during, and after filling. ```rust use heapless::sorted_linked_list::{Max, SortedLinkedList}; let mut ll: SortedLinkedList<_, Max, 3, u8> = SortedLinkedList::new_u8(); assert_eq!(ll.is_full(), false); ll.push(1).unwrap(); assert_eq!(ll.is_full(), false); ll.push(2).unwrap(); assert_eq!(ll.is_full(), false); ll.push(3).unwrap(); assert_eq!(ll.is_full(), true); ``` -------------------------------- ### get Source: https://docs.rs/heapless/0.9.3/heapless/history_buf/struct.HistoryBufInner.html Safely gets an element or subslice from the HistoryBuf by index or range. ```APIDOC ## get ### Description Returns a reference to an element or subslice depending on the type of index. * If given a position, returns a reference to the element at that position or `None` if out of bounds. * If given a range, returns the subslice corresponding to that range, or `None` if out of bounds. ### Method `get(&self, index: I) -> Option<&>::Output>` where I: SliceIndex<[T]> ### Examples ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` ``` -------------------------------- ### Safe String Slicing with `get` Source: https://docs.rs/heapless/0.9.3/heapless/string/struct.StringInner.html Use `get` for non-panicking string slicing. It returns `None` if the indices are out of bounds or not on UTF-8 sequence boundaries. ```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()); ``` -------------------------------- ### BinaryHeap::new Source: https://docs.rs/heapless/0.9.3/heapless/binary_heap/type.BinaryHeap.html Creates an empty `BinaryHeap` as a $K-heap. ```APIDOC ## BinaryHeap::new ### Description Creates a new, empty `BinaryHeap`. The type of heap (min-heap or max-heap) is determined by the `K` type parameter. ### Method `pub const fn new() -> Self` ### Example ```rust use heapless::binary_heap::{BinaryHeap, Max}; // allocate the binary heap on the stack let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new(); heap.push(4).unwrap(); // allocate the binary heap in a static variable static mut HEAP: BinaryHeap = BinaryHeap::new(); ``` ``` -------------------------------- ### Example Usage of Object Pool Source: https://docs.rs/heapless/0.9.3/heapless/pool/object/index.html Demonstrates how to create, manage, and request objects from an object pool. Objects are returned to the pool upon dropping. ```rust use core::ptr::addr_of_mut; use heapless::{object_pool, pool::object::{Object, ObjectBlock}}; object_pool!(MyObjectPool: [u8; 128]); // cannot request objects without first giving object blocks to the pool assert!(MyObjectPool.request().is_none()); // (some `no_std` runtimes have safe APIs to create `&'static mut` references) let block: &'static mut ObjectBlock<[u8; 128]> = unsafe { // unlike the memory pool APIs, an initial value must be specified here static mut BLOCK: ObjectBlock<[u8; 128]>= ObjectBlock::new([0; 128]); addr_of_mut!(BLOCK).as_mut().unwrap() }; // give object block to the pool MyObjectPool.manage(block); // it's now possible to request objects // unlike the memory pool APIs, no initial value is required here let mut object = MyObjectPool.request().unwrap(); // mutation is possible object.iter_mut().for_each(|byte| *byte = byte.wrapping_add(1)); // the number of live objects is limited to the number of blocks managed by the pool let res = MyObjectPool.request(); assert!(res.is_none()); // `object`'s destructor returns the object to the pool drop(object); // it's possible to request an `Object` again let res = MyObjectPool.request(); assert!(res.is_some()); ``` -------------------------------- ### Get QueueView Reference via Type Coercion Source: https://docs.rs/heapless/0.9.3/heapless/mpmc/type.QueueView.html Leverage type coercion to get a reference to the QueueView. This is often preferred over using `as_view`. ```rust let queue: Queue = Queue::new(); let view: &QueueView = &queue; ``` -------------------------------- ### Getting the Number of Elements in an IndexSet Source: https://docs.rs/heapless/0.9.3/heapless/index_set/struct.IndexSet.html Illustrates how to get the current number of elements stored in an IndexSet. This is useful for tracking the set's size. ```rust use heapless::index_set::FnvIndexSet; let mut v: FnvIndexSet<_, 16> = FnvIndexSet::new(); assert_eq!(v.len(), 0); v.insert(1).unwrap(); assert_eq!(v.len(), 1); ``` -------------------------------- ### BinaryHeapView Overview Source: https://docs.rs/heapless/0.9.3/heapless/binary_heap/type.BinaryHeapView.html Demonstrates basic usage of BinaryHeapView, including peeking, pushing, checking length, iterating, popping, and clearing. ```APIDOC ## BinaryHeapView Usage Example This example shows how to use `BinaryHeapView` to manage a priority queue. ```rust use heapless::binary_heap::{BinaryHeap, BinaryHeapView, Max}; let mut heap_buffer: BinaryHeap<_, Max, 8> = BinaryHeap::new(); let heap: &mut BinaryHeapView<_, Max> = &mut heap_buffer; // Peek at the next item (None if empty) assert_eq!(heap.peek(), None); // Add items to the heap heap.push(1).unwrap(); heap.push(5).unwrap(); heap.push(2).unwrap(); // Peek shows the highest priority item assert_eq!(heap.peek(), Some(&5)); // Check the number of items assert_eq!(heap.len(), 3); // Iterate over items (order is not guaranteed) for x in &*heap { println!("{}", x); } // Pop items in priority order assert_eq!(heap.pop(), Some(5)); assert_eq!(heap.pop(), Some(2)); assert_eq!(heap.pop(), Some(1)); assert_eq!(heap.pop(), None); // Clear the heap heap.clear(); assert!(heap.is_empty()); ``` ``` -------------------------------- ### Getting VecView from VecInner (immutable) Source: https://docs.rs/heapless/0.9.3/heapless/vec/struct.VecInner.html Use as_view to get an immutable reference to a VecView, erasing the N const-generic. Type coercion to &VecView is often preferred. ```rust let vec: Vec = Vec::from_slice(&[1, 2, 3, 4]).unwrap(); let view: &VecView = vec.as_view(); ``` ```rust let vec: Vec = Vec::from_slice(&[1, 2, 3, 4]).unwrap(); let view: &VecView = &vec; ``` -------------------------------- ### Example: Pushing elements to a Max SortedLinkedList Source: https://docs.rs/heapless/0.9.3/heapless/sorted_linked_list/type.SortedLinkedListView.html Demonstrates pushing elements into a `SortedLinkedList` configured for maximum value priority. Shows how the largest value is always at the front and how pushing to a full list results in an error. ```rust use heapless::sorted_linked_list::{Max, SortedLinkedList}; let mut ll: SortedLinkedList<_, Max, 3, u8> = SortedLinkedList::new_u8(); // The largest value will always be first ll.push(1).unwrap(); assert_eq!(ll.peek(), Some(&1)); ll.push(2).unwrap(); assert_eq!(ll.peek(), Some(&2)); ll.push(3).unwrap(); assert_eq!(ll.peek(), Some(&3)); // This will not fit in the queue. assert_eq!(ll.push(4), Err(4)); ``` -------------------------------- ### Get Reference to Underlying Array Source: https://docs.rs/heapless/0.9.3/heapless/history_buf/struct.HistoryBufInner.html Use `as_array` to get a reference to the underlying array if its length exactly matches the specified size `N`. Returns `None` otherwise. -------------------------------- ### Using BinaryHeapView as a Max-Heap Source: https://docs.rs/heapless/0.9.3/heapless/binary_heap/type.BinaryHeapView.html Demonstrates basic usage of BinaryHeapView, including peeking, pushing, checking length, iterating, popping, clearing, and checking emptiness. This example uses a max-heap. ```rust use heapless::binary_heap::{BinaryHeap, BinaryHeapView, Max}; let mut heap_buffer: BinaryHeap<_, Max, 8> = BinaryHeap::new(); let heap: &mut BinaryHeapView<_, Max> = &mut heap_buffer; // We can use peek to look at the next item in the heap. In this case, // there's no items in there yet so we get None. assert_eq!(heap.peek(), None); // Let's add some scores... heap.push(1).unwrap(); heap.push(5).unwrap(); heap.push(2).unwrap(); // Now peek shows the most important item in the heap. assert_eq!(heap.peek(), Some(&5)); // We can check the length of a heap. assert_eq!(heap.len(), 3); // We can iterate over the items in the heap, although they are returned in // a random order. for x in &*heap { println!("{}", x); } // If we instead pop these scores, they should come back in order. assert_eq!(heap.pop(), Some(5)); assert_eq!(heap.pop(), Some(2)); assert_eq!(heap.pop(), Some(1)); assert_eq!(heap.pop(), None); // We can clear the heap of any remaining items. heap.clear(); // The heap should now be empty. assert!(heap.is_empty()) ``` -------------------------------- ### Get mutable non-overlapping chunks from a slice Source: https://docs.rs/heapless/0.9.3/heapless/vec/struct.VecInner.html Use `chunks_mut(chunk_size)` to get an iterator over mutable non-overlapping sub-slices. The last chunk may be smaller. Panics if `chunk_size` is zero. ```rust let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; for chunk in v.chunks_mut(2) { for elem in chunk.iter_mut() { *elem += count; } count += 1; } assert_eq!(v, &[1, 1, 2, 2, 3]); ``` -------------------------------- ### Create and Use FnvIndexMap Source: https://docs.rs/heapless/0.9.3/heapless/index_map/struct.IndexMap.html Demonstrates creating an FnvIndexMap, inserting elements, checking for keys, removing elements, and iterating over the map. Use this for general-purpose hash map operations on the stack. ```rust use heapless::index_map::FnvIndexMap; // A hash map with a capacity of 16 key-value pairs allocated on the stack let mut book_reviews = FnvIndexMap::<_, _, 16>::new(); // review some books. book_reviews .insert("Adventures of Huckleberry Finn", "My favorite book.") .unwrap(); book_reviews .insert("Grimms' Fairy Tales", "Masterpiece.") .unwrap(); book_reviews .insert("Pride and Prejudice", "Very enjoyable.") .unwrap(); book_reviews .insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.") .unwrap(); // check for a specific one. if !book_reviews.contains_key("Les Misérables") { println!( "We've got {} reviews, but Les Misérables ain't one.", book_reviews.len() ); } // oops, this review has a lot of spelling mistakes, let's delete it. book_reviews.remove("The Adventures of Sherlock Holmes"); // look up the values associated with some keys. let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"]; for book in &to_find { match book_reviews.get(book) { Some(review) => println!( \"{}: {}\", book, review), None => println!( \"{} is unreviewed.\", book), } } // iterate over everything. for (book, review) in &book_reviews { println!( \"{}: \"{}\"", book, review); } ``` -------------------------------- ### Get mutable key-value pair by index in IndexMap Source: https://docs.rs/heapless/0.9.3/heapless/index_map/struct.IndexMap.html Use `get_index_mut()` to get a mutable reference to the value at a specific index, along with a reference to the key. This allows modification of the value. This operation is O(1) on average. ```rust use heapless::index_map::FnvIndexMap; let mut map = FnvIndexMap::<_, _, 8>::new(); map.insert(1, "a").unwrap(); if let Some((_, x)) = map.get_index_mut(0) { *x = "b"; } assert_eq!(map[&1], "b"); ``` -------------------------------- ### DequeView Usage Example Source: https://docs.rs/heapless/0.9.3/heapless/deque/type.DequeView.html Demonstrates creating a DequeView from a Deque, using it as a FIFO queue, and employing its double-ended capabilities. Shows basic push and pop operations and iteration. ```rust use heapless::deque::{Deque, DequeView}; // A deque with a fixed capacity of 8 elements allocated on the stack let mut deque_buf = Deque::<_, 8>::new(); // A DequeView can be obtained through unsized coercion of a `Deque` let deque: &mut DequeView<_> = &mut deque_buf; // You can use it as a good old FIFO queue. deque.push_back(1); deque.push_back(2); assert_eq!(deque.storage_len(), 2); assert_eq!(deque.pop_front(), Some(1)); assert_eq!(deque.pop_front(), Some(2)); assert_eq!(deque.storage_len(), 0); // DequeView is double-ended, you can push and pop from the front and back. deque.push_back(1); deque.push_front(2); deque.push_back(3); deque.push_front(4); assert_eq!(deque.pop_front(), Some(4)); assert_eq!(deque.pop_front(), Some(2)); assert_eq!(deque.pop_front(), Some(1)); assert_eq!(deque.pop_front(), Some(3)); // You can iterate it, yielding all the elements front-to-back. for x in deque { println!("{}", x); } ``` -------------------------------- ### Vec Initialization from Slice Source: https://docs.rs/heapless/0.9.3/heapless/vec/type.Vec.html Demonstrates creating a Vec and filling it with data from a slice. This is equivalent to creating an empty Vec and extending it. ```rust use heapless::Vec; let mut v: Vec = Vec::new(); v.extend_from_slice(&[1, 2, 3]).unwrap(); ``` -------------------------------- ### Get a reference to a value by key in IndexMap Source: https://docs.rs/heapless/0.9.3/heapless/index_map/struct.IndexMap.html Use `get()` to retrieve an immutable reference to a value associated with a given key. The key can be any borrowed form that implements `Hash` and `Eq`. This operation is O(1) on average. ```rust use heapless::index_map::FnvIndexMap; let mut map = FnvIndexMap::<_, _, 16>::new(); map.insert(1, "a").unwrap(); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); ``` -------------------------------- ### type_id Source: https://docs.rs/heapless/0.9.3/heapless/history_buf/struct.HistoryBufInner.html Gets the TypeId of `self`. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `type_id` ### Parameters None ### Returns - `TypeId`: The type ID of the object. ``` -------------------------------- ### Basic LinearMap Usage and Iteration Source: https://docs.rs/heapless/0.9.3/heapless/linear_map/struct.LinearMapInner.html Demonstrates creating a LinearMap, inserting elements, updating values, and iterating over key-value pairs. ```rust use heapless::LinearMap; let mut map: LinearMap<_, _, 8> = LinearMap::new(); map.insert("a", 1).unwrap(); map.insert("b", 2).unwrap(); map.insert("c", 3).unwrap(); // Update all values for (_, val) in map.iter_mut() { *val = 2; } for (key, val) in &map { println!("key: {} val: {}", key, val); } ``` -------------------------------- ### Safe Get Disjoint Mutable References Source: https://docs.rs/heapless/0.9.3/heapless/vec/struct.VecInner.html Use to get mutable references to multiple disjoint elements with bounds and overlap checks. Returns an error if indices are out-of-bounds or overlapping. Be cautious as the overlap check is O(n^2). ```rust let v = &mut [1, 2, 3]; if let Ok([a, b]) = v.get_disjoint_mut([0, 2]) { *a = 413; *b = 612; } assert_eq!(v, &[413, 2, 612]); ``` ```rust let v = &mut [1, 2, 3]; if let Ok([a, b]) = v.get_disjoint_mut([0..1, 1..3]) { a[0] = 8; b[0] = 88; b[1] = 888; } assert_eq!(v, &[8, 88, 888]); ``` ```rust let v = &mut [1, 2, 3]; if let Ok([a, b]) = v.get_disjoint_mut([1..=2, 0..=0]) { a[0] = 11; a[1] = 111; b[0] = 1; } assert_eq!(v, &[1, 11, 111]); ``` -------------------------------- ### Initialize and Use HistoryBuf Source: https://docs.rs/heapless/0.9.3/heapless/history_buf/index.html Demonstrates initializing a HistoryBuf with a fixed capacity, writing elements, and accessing them for calculations like a rolling average. Ensure the buffer has elements before attempting to access them. ```rust use heapless::HistoryBuf; // Initialize a new buffer with 8 elements. let mut buf = HistoryBuf::<_, 8>::new(); // Starts with no data assert_eq!(buf.recent(), None); buf.write(3); buf.write(5); buf.extend(&[4, 4]); // The most recent written element is a four. assert_eq!(buf.recent(), Some(&4)); // To access all elements in an unspecified order, use `as_slice()`. for el in buf.as_slice() { println!("{:?}", el); } // Now we can prepare an average of all values, which comes out to 4. let avg = buf.as_slice().iter().sum::() / buf.len(); assert_eq!(avg, 4); ``` -------------------------------- ### Unsafe Get Disjoint Unchecked Mutable References Source: https://docs.rs/heapless/0.9.3/heapless/vec/struct.VecInner.html Use when you need to get mutable references to multiple disjoint elements without bounds or overlap checks. Calling with overlapping or out-of-bounds indices is undefined behavior. ```rust let x = &mut [1, 2, 4]; unsafe { let [a, b] = x.get_disjoint_unchecked_mut([0, 2]); *a *= 10; *b *= 100; } assert_eq!(x, &[10, 2, 400]); ``` ```rust let x = &mut [1, 2, 4]; unsafe { let [a, b] = x.get_disjoint_unchecked_mut([0..1, 1..3]); a[0] = 8; b[0] = 88; b[1] = 888; } assert_eq!(x, &[8, 88, 888]); ``` ```rust let x = &mut [1, 2, 4]; unsafe { let [a, b] = x.get_disjoint_unchecked_mut([1..=2, 0..=0]); a[0] = 11; a[1] = 111; b[0] = 1; } assert_eq!(x, &[1, 11, 111]); ``` -------------------------------- ### Consumer peek and dequeue Example Source: https://docs.rs/heapless/0.9.3/heapless/spsc/struct.Consumer.html Shows how to peek at the next item without removing it, and then dequeue it. Useful for inspecting the next element or conditionally processing it. ```rust use heapless::spsc::Queue; let mut queue: Queue = Queue::new(); let (mut producer, mut consumer) = queue.split(); assert_eq!(None, consumer.peek()); producer.enqueue(1); assert_eq!(Some(&1), consumer.peek()); assert_eq!(Some(1), consumer.dequeue()); assert_eq!(None, consumer.peek()); ``` -------------------------------- ### iter Source: https://docs.rs/heapless/0.9.3/heapless/sorted_linked_list/type.SortedLinkedListView.html Get an iterator over the sorted list. ```APIDOC ## iter ### Description Get an iterator over the sorted list. ### Example ```rust use heapless::sorted_linked_list::{Max, SortedLinkedList}; let mut ll: SortedLinkedList<_, Max, 3, u8> = SortedLinkedList::new_u8(); ll.push(1).unwrap(); ll.push(2).unwrap(); let mut iter = ll.iter(); assert_eq!(iter.next(), Some(&2)); assert_eq!(iter.next(), Some(&1)); assert_eq!(iter.next(), None); ``` ### Signature ```rust pub fn iter(&self) -> IterView<'_, T, Idx, K> ``` ``` -------------------------------- ### Get Raw Pointer Range for Slice Source: https://docs.rs/heapless/0.9.3/heapless/history_buf/struct.HistoryBufInner.html Use `as_ptr_range` to get a half-open range of raw pointers spanning the slice. This is useful for C-style interfaces and checking pointer containment. The end pointer points one past the last element. ```rust let a = [1, 2, 3]; let x = &a[1] as *const _; let y = &5 as *const _; assert!(a.as_ptr_range().contains(&x)); assert!(!a.as_ptr_range().contains(&y)); ``` -------------------------------- ### Basic BinaryHeap Usage Source: https://docs.rs/heapless/0.9.3/heapless/binary_heap/type.BinaryHeapView.html Demonstrates the basic creation and manipulation of a BinaryHeap, including peeking and modifying the top element. ```rust use heapless::binary_heap::{BinaryHeap, Max}; let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new(); assert!(heap.peek_mut().is_none()); heap.push(1); heap.push(5); heap.push(2); { let mut val = heap.peek_mut().unwrap(); *val = 0; } assert_eq!(heap.peek(), Some(&2)); ``` -------------------------------- ### FnvIndexSet::last Source: https://docs.rs/heapless/0.9.3/heapless/index_set/type.FnvIndexSet.html Get the last value in the set. ```APIDOC ## FnvIndexSet::last ### Description Get the last value. Computes in _O_(1) time. ### Method `pub fn last(&self) -> Option<&T>` ``` -------------------------------- ### Create and Use FnvIndexMap Source: https://docs.rs/heapless/0.9.3/heapless/index_map/type.FnvIndexMap.html Demonstrates creating a stack-allocated FnvIndexMap, inserting elements, checking for keys, removing elements, and iterating over the map. Use this for general-purpose hash map operations where heap allocation is not allowed. ```rust use heapless::index_map::FnvIndexMap; // A hash map with a capacity of 16 key-value pairs allocated on the stack let mut book_reviews = FnvIndexMap::<_, _, 16>::new(); // review some books. book_reviews .insert("Adventures of Huckleberry Finn", "My favorite book.") .unwrap(); book_reviews .insert("Grimms' Fairy Tales", "Masterpiece.") .unwrap(); book_reviews .insert("Pride and Prejudice", "Very enjoyable.") .unwrap(); book_reviews .insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.") .unwrap(); // check for a specific one. if !book_reviews.contains_key("Les Misérables") { println!( "We've got {} reviews, but Les Misérables ain't one.", book_reviews.len() ); } // oops, this review has a lot of spelling mistakes, let's delete it. book_reviews.remove("The Adventures of Sherlock Holmes"); // look up the values associated with some keys. let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"]; for book in &to_find { match book_reviews.get(book) { Some(review) => println!("{}: {}", book, review), None => println!("{} is unreviewed.", book), } } // iterate over everything. for (book, review) in &book_reviews { println!("{}: \"{}\"", book, review); } ``` -------------------------------- ### FnvIndexSet::first Source: https://docs.rs/heapless/0.9.3/heapless/index_set/type.FnvIndexSet.html Get the first value in the set. ```APIDOC ## FnvIndexSet::first ### Description Get the first value. Computes in _O_(1) time. ### Method `pub fn first(&self) -> Option<&T>` ``` -------------------------------- ### Basic VecInner Usage Example Source: https://docs.rs/heapless/0.9.3/heapless/vec/struct.VecInner.html Demonstrates basic usage of VecInner with splitting and subslice range operations. Requires nightly Rust. ```rust #![feature(substr_range)] use core::range::Range; let nums = &[0, 5, 10, 0, 0, 5]; let mut iter = nums .split(|t| *t == 0) .map(|n| nums.subslice_range(n).unwrap()); assert_eq!(iter.next(), Some(Range { start: 0, end: 0 })); assert_eq!(iter.next(), Some(Range { start: 1, end: 3 })); assert_eq!(iter.next(), Some(Range { start: 4, end: 4 })); assert_eq!(iter.next(), Some(Range { start: 5, end: 6 })); ``` -------------------------------- ### IndexSet::last Source: https://docs.rs/heapless/0.9.3/heapless/index_set/struct.IndexSet.html Gets the last value in the set. ```APIDOC ## IndexSet::last ### Description Get the last value. ### Method `last(&self) -> Option<&T>` ### Parameters None ### Returns An `Option` containing a reference to the last value, or `None` if the set is empty. ### Complexity O(1) ``` -------------------------------- ### Using SortedLinkedList with Max Ordering Source: https://docs.rs/heapless/0.9.3/heapless/sorted_linked_list/type.SortedLinkedListView.html Demonstrates creating a SortedLinkedList with a maximum capacity and pushing/popping elements. It also shows how to find a mutable reference to an element, update it, and then finish the mutation. ```rust use heapless::sorted_linked_list::{Max, SortedLinkedList}; let mut ll: SortedLinkedList<_, Max, 3, u8> = SortedLinkedList::new_u8(); ll.push(1).unwrap(); ll.push(2).unwrap(); ll.push(3).unwrap(); // Find a value and update it let mut find = ll.find_mut(|v| *v == 2).unwrap(); *find += 1000; find.finish(); assert_eq!(ll.pop(), Some(1002)); assert_eq!(ll.pop(), Some(3)); assert_eq!(ll.pop(), Some(1)); assert_eq!(ll.pop(), None); ``` -------------------------------- ### IndexSet::first Source: https://docs.rs/heapless/0.9.3/heapless/index_set/struct.IndexSet.html Gets the first value in the set. ```APIDOC ## IndexSet::first ### Description Get the first value. ### Method `first(&self) -> Option<&T>` ### Parameters None ### Returns An `Option` containing a reference to the first value, or `None` if the set is empty. ### Complexity O(1) ``` -------------------------------- ### Example: Popping elements from a Max SortedLinkedList Source: https://docs.rs/heapless/0.9.3/heapless/sorted_linked_list/type.SortedLinkedListView.html Demonstrates popping elements from a `SortedLinkedList` configured for maximum value priority. Shows that elements are removed in descending order. ```rust use heapless::sorted_linked_list::{Max, SortedLinkedList}; let mut ll: SortedLinkedList<_, Max, 3, u8> = SortedLinkedList::new_u8(); ll.push(1).unwrap(); ll.push(2).unwrap(); assert_eq!(ll.pop(), Some(2)); assert_eq!(ll.pop(), Some(1)); assert_eq!(ll.pop(), None); ``` -------------------------------- ### starts_with Source: https://docs.rs/heapless/0.9.3/heapless/vec/type.VecView.html Checks if the vector starts with a given slice. ```APIDOC ## pub fn starts_with(&self, needle: &[T]) -> bool ### Description Returns `true` if `needle` is a prefix of the Vec. Always returns `true` if `needle` is an empty slice. ### Parameters #### Path Parameters - **needle** (*&[T]*) - Description: The slice to check for as a prefix. ### Response - **bool** - `true` if `needle` is a prefix, `false` otherwise. ``` -------------------------------- ### Using heapless::Vec on Stack, Static, and Heap Source: https://docs.rs/heapless/0.9.3/heapless/index.html Demonstrates how to use `heapless::Vec` with fixed capacity on the stack, in a static variable, and within a Box. This illustrates the flexibility of heapless data structures in different memory contexts. ```rust use heapless::Vec; // on the stack let mut xs: Vec = Vec::new(); // can hold up to 8 elements xs.push(42)?; assert_eq!(xs.pop(), Some(42)); // in a `static` variable static mut XS: Vec = Vec::new(); let xs = unsafe { &mut XS }; xs.push(42)?; assert_eq!(xs.pop(), Some(42)); // in the heap (though kind of pointless because no reallocation) let mut ys: Box> = Box::new(Vec::new()); ys.push(42)?; assert_eq!(ys.pop(), Some(42)); ``` -------------------------------- ### Example: Peeking at Max and Min SortedLinkedLists Source: https://docs.rs/heapless/0.9.3/heapless/sorted_linked_list/type.SortedLinkedListView.html Illustrates peeking at the first element of both a `Max` (largest first) and a `Min` (smallest first) `SortedLinkedList`. Shows how the peeked element changes as new elements are pushed. ```rust use heapless::sorted_linked_list::{Max, Min, SortedLinkedList}; let mut ll_max: SortedLinkedList<_, Max, 3, u8> = SortedLinkedList::new_u8(); // The largest value will always be first ll_max.push(1).unwrap(); assert_eq!(ll_max.peek(), Some(&1)); ll_max.push(2).unwrap(); assert_eq!(ll_max.peek(), Some(&2)); ll_max.push(3).unwrap(); assert_eq!(ll_max.peek(), Some(&3)); let mut ll_min: SortedLinkedList<_, Min, 3, u8> = SortedLinkedList::new_u8(); // The Smallest value will always be first ll_min.push(3).unwrap(); assert_eq!(ll_min.peek(), Some(&3)); ll_min.push(2).unwrap(); assert_eq!(ll_min.peek(), Some(&2)); ll_min.push(1).unwrap(); assert_eq!(ll_min.peek(), Some(&1)); ``` -------------------------------- ### as_view Source: https://docs.rs/heapless/0.9.3/heapless/sorted_linked_list/type.SortedLinkedListView.html Get a reference to the SortedLinkedListView, erasing the const-generic N. ```APIDOC ## as_view ### Description Get a reference to the `SortedLinkedListView`, erasing the `N` const-generic. ### Signature ```rust pub fn as_view(&self) -> &SortedLinkedListView ``` ``` -------------------------------- ### Example: Checking if a SortedLinkedList is full Source: https://docs.rs/heapless/0.9.3/heapless/sorted_linked_list/type.SortedLinkedListView.html Demonstrates the `is_full` method by pushing elements into a `SortedLinkedList` until it reaches its capacity, then checking the status. ```rust use heapless::sorted_linked_list::{Max, SortedLinkedList}; let mut ll: SortedLinkedList<_, Max, 3, u8> = SortedLinkedList::new_u8(); assert_eq!(ll.is_full(), false); ll.push(1).unwrap(); assert_eq!(ll.is_full(), false); l l.push(2).unwrap(); assert_eq!(ll.is_full(), false); l l.push(3).unwrap(); assert_eq!(ll.is_full(), true); ``` -------------------------------- ### as_view Source: https://docs.rs/heapless/0.9.3/heapless/linear_map/type.LinearMapView.html Get a reference to the `LinearMap`, erasing the `N` const-generic. ```APIDOC ## `as_view(&self) -> &LinearMapView` Get a reference to the `LinearMap`, erasing the `N` const-generic. ``` -------------------------------- ### type_id Source: https://docs.rs/heapless/0.9.3/heapless/linear_map/struct.LinearMapInner.html Gets the `TypeId` of `self`. This is part of the `Any` trait implementation. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `type_id` ### Parameters - `&self`: An immutable reference to the object. ### Returns - `TypeId`: The type identifier of the object. ``` -------------------------------- ### Create and Split SPSC Queue at Runtime Source: https://docs.rs/heapless/0.9.3/heapless/spsc/type.Queue.html Demonstrates how to create a new SPSC queue and then split it into producer and consumer ends at runtime. This is useful when the queue's lifecycle is managed dynamically. ```rust let mut queue: Queue<(), 4> = Queue::new(); let (mut producer, mut consumer) = queue.split(); producer.enqueue(()).unwrap(); assert_eq!(consumer.dequeue(), Some(())); ``` -------------------------------- ### starts_with Source: https://docs.rs/heapless/0.9.3/heapless/vec/struct.VecInner.html Checks if the slice starts with the given prefix slice. ```APIDOC ## pub fn starts_with(&self, needle: &[T]) -> bool ### Description Returns `true` if `needle` is a prefix of the slice or equal to the slice. ### Parameters * `needle`: The slice to check as a prefix. ### Returns `true` if `needle` is a prefix, `false` otherwise. ### Examples ```rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(v.starts_with(&v)); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); ``` Always returns `true` if `needle` is an empty slice: ```rust let v = &[10, 40, 30]; assert!(v.starts_with(&[])); let v: &[u8] = &[]; assert!(v.starts_with(&[])); ``` ``` -------------------------------- ### Create and Split Queue in Const Context Source: https://docs.rs/heapless/0.9.3/heapless/spsc/type.Queue.html Demonstrates creating and splitting a queue at compile time, suitable for passing between different execution contexts like main and interrupt handlers. This example utilizes `critical-section` for safe access. ```rust use core::cell::RefCell; use critical_section::Mutex; use heapless::spsc::{Consumer, Producer, Queue}; static PC: ( Mutex>>>, Mutex>>>, ) = { static mut Q: Queue<(), 4> = Queue::new(); // SAFETY: `Q` is only accessible in this scope. #[allow(static_mut_refs)] let (p, c) = unsafe { Q.split_const() }; ( Mutex::new(RefCell::new(Some(p))), Mutex::new(RefCell::new(Some(c))), ) }; fn interrupt() { let mut producer = { static mut P: Option> = None; // SAFETY: Mutable access to `P` is allowed exclusively in this scope // and `interrupt` cannot be called directly or preempt itself. unsafe { &mut P } } .get_or_insert_with(|| { critical_section::with(|cs| PC.0.borrow_ref_mut(cs).take().unwrap()) }); producer.enqueue(()).unwrap(); } fn main() { let mut consumer = critical_section::with(|cs| PC.1.borrow_ref_mut(cs).take().unwrap()); // Interrupt occurs. consumer.dequeue().unwrap(); } ``` -------------------------------- ### strip_prefix Source: https://docs.rs/heapless/0.9.3/heapless/history_buf/struct.HistoryBufInner.html Returns a subslice with the prefix removed. If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the original slice, returns an empty slice. If the slice does not start with `prefix`, returns `None`. ```APIDOC ## pub fn strip_prefix

(&self, prefix: &P) -> Option<&[T]> where P: SlicePattern + ?Sized, T: PartialEq, ### Description Returns a subslice with the prefix removed. If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the original slice, returns an empty slice. If the slice does not start with `prefix`, returns `None`. ### Parameters #### Path Parameters - **prefix** (&P) - Required - The prefix pattern to remove from the slice. ### Returns - Option<&[T]> - A subslice with the prefix removed if found, otherwise `None`. ```