Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Ringbuf
https://docs.rs/ringbuf/
Admin
Lock-free SPSC FIFO ring buffer with direct access to inner data for Rust.
Tokens:
165,539
Snippets:
1,485
Trust Score:
9.7
Update:
5 months ago
Context
Chat
Benchmark
81.67
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Chain Iterator Default Implementation Example Source: https://docs.rs/ringbuf/latest/ringbuf/traits/consumer/type.Iter.html Demonstrates how to create a `Chain` iterator from default values, useful when the iterator type implements `Default`. This example uses `mem::take` to obtain a default `Chain` instance. ```rust struct Foo<'a>(Chain<slice::Iter<'a, u8>, btree_set::Iter<'a, u8>>); let set = BTreeSet::<u8>::new(); let slice: &[u8] = &[]; let mut foo = Foo(slice.iter().chain(set.iter())); // take requires `Default` let _: Chain<_, _> = mem::take(&mut foo.0); ``` -------------------------------- ### Arc::new_uninit_slice Example Source: https://docs.rs/ringbuf/latest/ringbuf/struct.Arc.html Demonstrates creating a new Arc-allocated slice with uninitialized contents and performing deferred initialization. ```rust use std::sync::Arc; let mut values = Arc::<[u32]>::new_uninit_slice(3); // Deferred initialization: let data = Arc::get_mut(&mut values).unwrap(); data[0].write(1); data[1].write(2); data[2].write(3); let values = unsafe { values.assume_init() }; assert_eq!(*values, [1, 2, 3]) ``` -------------------------------- ### Step By for PopIter Source: https://docs.rs/ringbuf/latest/ringbuf/traits/consumer/struct.PopIter.html Creates a new iterator that starts at the same point as PopIter but steps by a specified amount at each iteration. ```rust fn step_by(self, step: usize) -> StepBy<Self> where Self: Sized, ``` -------------------------------- ### Arc::new_uninit_slice_in Example (Nightly) Source: https://docs.rs/ringbuf/latest/ringbuf/struct.Arc.html Demonstrates creating an Arc-allocated slice with uninitialized contents using a specified allocator. This is a nightly-only experimental API. ```rust #![feature(get_mut_unchecked)] #![feature(allocator_api)] use std::sync::Arc; use std::alloc::System; let mut values = Arc::<[u32], _>::new_uninit_slice_in(3, System); let values = unsafe { // Deferred initialization: Arc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1); Arc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2); Arc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3); values.assume_init() }; assert_eq!(*values, [1, 2, 3]) ``` -------------------------------- ### SharedRb Example with Threading Source: https://docs.rs/ringbuf/latest/ringbuf/rb/shared/struct.SharedRb.html Demonstrates how to use SharedRb with multiple threads for concurrent data access. It shows splitting the buffer into producer and consumer, pushing an item in one thread, and popping it in another. ```rust use std::thread; use ringbuf::{SharedRb, storage::Heap, traits::*}; let rb = SharedRb::<Heap<i32>>::new(256); let (mut prod, mut cons) = rb.split(); thread::spawn(move || { prod.try_push(123).unwrap(); }) .join(); thread::spawn(move || { assert_eq!(cons.try_pop().unwrap(), 123); }) .join(); ``` -------------------------------- ### Arc::new_zeroed_slice_in Example (Nightly) Source: https://docs.rs/ringbuf/latest/ringbuf/struct.Arc.html Shows creating an Arc-allocated slice with zeroed memory using a specified allocator. This is a nightly-only experimental API. ```rust #![feature(allocator_api)] use std::sync::Arc; use std::alloc::System; let values = Arc::<[u32], _>::new_zeroed_slice_in(3, System); let values = unsafe { values.assume_init() }; assert_eq!(*values, [0, 0, 0]) ``` -------------------------------- ### Arc::new_zeroed_slice Example Source: https://docs.rs/ringbuf/latest/ringbuf/struct.Arc.html Shows how to construct an Arc-allocated slice with uninitialized contents, where the memory is zeroed. ```rust use std::sync::Arc; let values = Arc::<[u32]>::new_zeroed_slice(3); let values = unsafe { values.assume_init() }; assert_eq!(*values, [0, 0, 0]) ``` -------------------------------- ### unsafe_slices Source: https://docs.rs/ringbuf/latest/ringbuf/rb/shared/struct.SharedRb.html Gets slices of the ring buffer between `start` and `end` indices. This is an unsafe operation. ```APIDOC ## unsafe_slices ### Description Gets slices of the ring buffer between `start` and `end` indices. This is an unsafe operation. ### Signature `unsafe fn unsafe_slices(&self, start: usize, end: usize) -> (&[MaybeUninit<S::Item>], &[MaybeUninit<S::Item>])` ``` -------------------------------- ### take Source: https://docs.rs/ringbuf/latest/ringbuf/type.StaticRb.html Creates an adapter which will read at most `limit` bytes from it. ```APIDOC ## take ### Description Creates an adapter which will read at most `limit` bytes from it. ### Method `take` ### Parameters #### Query Parameters - **limit** (u64) - Required - The maximum number of bytes to read. ### Request Example None ### Response #### Success Response `Take<Self>` #### Response Example None ``` -------------------------------- ### fn take(self, limit: u64) -> Take<Self> Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/frozen/type.FrozenCons.html Creates an adapter which will read at most `limit` bytes from it. ```APIDOC ## fn take(self, limit: u64) -> Take<Self> ### Description Creates an adapter which will read at most `limit` bytes from it. ### Method `take` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (Take<Self>) - `Take<Self>`: An adapter that limits the number of bytes read. #### Response Example None ``` -------------------------------- ### unsafe_slices_mut Source: https://docs.rs/ringbuf/latest/ringbuf/rb/shared/struct.SharedRb.html Gets mutable slices of the ring buffer between `start` and `end` indices. This is an unsafe operation. ```APIDOC ## unsafe_slices_mut ### Description Gets mutable slices of the ring buffer between `start` and `end` indices. This is an unsafe operation. ### Signature `unsafe fn unsafe_slices_mut(&self, start: usize, end: usize) -> (&mut [MaybeUninit<S::Item>], &mut [MaybeUninit<S::Item>])` ``` -------------------------------- ### Direct::new Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/direct/type.Obs.html Creates a new ring buffer direct wrapper. Panics if a wrapper with matching rights already exists. ```APIDOC ## Function new `pub fn new(rb: R) -> Self` ### Description Create a new ring buffer direct wrapper. Panics if wrapper with matching rights already exists. ### Parameters #### Path Parameters - `rb` (R) - Required - The ring buffer to wrap. ``` -------------------------------- ### unsafe fn unsafe_slices(&self, start: usize, end: usize) -> (&[MaybeUninit<S::Item>], &[MaybeUninit<S::Item>]) Source: https://docs.rs/ringbuf/latest/ringbuf/type.HeapRb.html Gets immutable slices representing the data between `start` and `end` indices. This is an unsafe operation. ```APIDOC ## unsafe fn unsafe_slices(&self, start: usize, end: usize) -> (&[MaybeUninit<S::Item>], &[MaybeUninit<S::Item>]) ### Description Gets immutable slices representing the data between `start` and `end` indices. This is an unsafe operation and requires careful handling to ensure memory safety. ### Parameters #### Path Parameters - **start** (usize) - Required - The starting index. - **end** (usize) - Required - The ending index. ### Returns - **(&[MaybeUninit<S::Item>], &[MaybeUninit<S::Item>])** - A tuple containing two slices representing the data within the specified range. ``` -------------------------------- ### Convert Arc to Raw Pointer (Simplified) Source: https://docs.rs/ringbuf/latest/ringbuf/struct.Arc.html A simplified example of consuming an Arc into a raw pointer. It highlights the immediate dereferencing of the raw pointer to verify its content. ```rust use std::sync::Arc; let x = Arc::new("hello".to_owned()); let x_ptr = Arc::into_raw(x); assert_eq!(unsafe { &*x_ptr }, "hello"); ``` -------------------------------- ### Basic Ring Buffer Operations Source: https://docs.rs/ringbuf/latest/index.html Demonstrates the fundamental usage of a HeapRb, including splitting into producer and consumer, pushing, and popping elements. Shows how to handle insertion errors when the buffer is full. ```rust use ringbuf::{traits::*, HeapRb}; let rb = HeapRb::<i32>::new(2); let (mut prod, mut cons) = rb.split(); prod.try_push(0).unwrap(); prod.try_push(1).unwrap(); assert_eq!(prod.try_push(2), Err(2)); assert_eq!(cons.try_pop(), Some(0)); prod.try_push(2).unwrap(); assert_eq!(cons.try_pop(), Some(1)); assert_eq!(cons.try_pop(), Some(2)); assert_eq!(cons.try_pop(), None); ``` -------------------------------- ### unsafe fn unsafe_slices_mut(&self, start: usize, end: usize) -> (&mut [MaybeUninit<S::Item>], &mut [MaybeUninit<S::Item>]) Source: https://docs.rs/ringbuf/latest/ringbuf/type.HeapRb.html Gets mutable slices representing the data between `start` and `end` indices. This is an unsafe operation. ```APIDOC ## unsafe fn unsafe_slices_mut(&self, start: usize, end: usize) -> (&mut [MaybeUninit<S::Item>], &mut [MaybeUninit<S::Item>]) ### Description Gets mutable slices representing the data between `start` and `end` indices. This is an unsafe operation and requires careful handling to ensure memory safety. ### Parameters #### Path Parameters - **start** (usize) - Required - The starting index. - **end** (usize) - Required - The ending index. ### Returns - **(&mut [MaybeUninit<S::Item>], &mut [MaybeUninit<S::Item>])** - A tuple containing two mutable slices representing the data within the specified range. ``` -------------------------------- ### Get Unsafe Slices Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/caching/struct.Caching.html Provides unsafe access to slices of the ring buffer between specified start and end indices. ```rust unsafe fn unsafe_slices( &self, start: usize, end: usize, ) -> (&[MaybeUninit<Self::Item>], &[MaybeUninit<Self::Item>]) ``` -------------------------------- ### Get Unsafe Mutable Slices Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/caching/struct.Caching.html Provides unsafe mutable access to slices of the ring buffer between specified start and end indices. ```rust unsafe fn unsafe_slices_mut( &self, start: usize, end: usize, ) -> (&mut [MaybeUninit<Self::Item>], &mut [MaybeUninit<Self::Item>]) ``` -------------------------------- ### Sharing Immutable Data Between Threads Source: https://docs.rs/ringbuf/latest/ringbuf/struct.Arc.html Example of sharing an immutable Arc<i32> across multiple threads, where each thread gets its own reference. ```rust use std::sync::Arc; use std::thread; let five = Arc::new(5); for _ in 0..10 { let five = Arc::clone(&five); thread::spawn(move || { println!("{five:?}"); }); } ``` -------------------------------- ### Getting Mutable Slices of Ring Buffer Data Source: https://docs.rs/ringbuf/latest/src/ringbuf/rb/shared.rs.html Provides mutable slices of the ring buffer's data for a given range. Requires the start and end indices to be valid. ```rust unsafe fn unsafe_slices_mut(&self, start: usize, end: usize) -> (&mut [MaybeUninit<S::Item>], &mut [MaybeUninit<S::Item>]) { let (first, second) = ranges(self.capacity(), start, end); unsafe { (self.storage.slice_mut(first), self.storage.slice_mut(second)) } } ``` -------------------------------- ### Take Bytes Source: https://docs.rs/ringbuf/latest/ringbuf/type.HeapRb.html Creates an adapter that reads at most a specified limit of bytes from the source. ```APIDOC ## fn take(self, limit: u64) -> Take<Self> ### Description Creates an adapter which will read at most `limit` bytes from it. ### Method `take` ### Parameters #### Path Parameters - `limit` (*u64*): The maximum number of bytes to read. ### Response #### Success Response (Take<Self>) - `Take<Self>`: A reader adapter that limits the number of bytes read. ``` -------------------------------- ### Getting Slices of Ring Buffer Data (Read) Source: https://docs.rs/ringbuf/latest/src/ringbuf/rb/shared.rs.html Provides immutable slices of the ring buffer's data for a given range. Requires the start and end indices to be valid. ```rust unsafe fn unsafe_slices(&self, start: usize, end: usize) -> (&[MaybeUninit<S::Item>], &[MaybeUninit<S::Item>]) { let (first, second) = ranges(self.capacity(), start, end); unsafe { (self.storage.slice(first), self.storage.slice(second)) } } ``` -------------------------------- ### Heap::new Source: https://docs.rs/ringbuf/latest/ringbuf/storage/struct.Heap.html Creates a new Heap storage with a specified capacity. This is the primary way to instantiate a Heap for use as a ring buffer. ```APIDOC ## Heap::new ### Description Creates a new heap storage with exact capacity. ### Method `new` ### Parameters #### Path Parameters - **capacity** (usize) - Required - The exact capacity for the heap storage. ### Response #### Success Response - **Self** - A new instance of Heap<T>. ### Request Example ```rust let heap_storage = Heap::<u8>::new(1024); ``` ### Response Example ```rust // Returns a Heap<u8> with a capacity of 1024 ``` ``` -------------------------------- ### Get Mutable Vacant Slices for Writing Source: https://docs.rs/ringbuf/latest/src/ringbuf/traits/producer.rs.html Provides mutable access to the uninitialized memory regions for writing new elements. Items must be written starting from the beginning of the first slice, then the second. This must be followed by `advance_write_index`. ```rust fn vacant_slices_mut(&mut self) -> (&mut [MaybeUninit<Self::Item>], &mut [MaybeUninit<Self::Item>]) { unsafe { self.unsafe_slices_mut(self.write_index(), self.read_index() + self.capacity().get()) } } ``` -------------------------------- ### fn chain<R>(self, next: R) -> Chain<Self, R> Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/frozen/type.FrozenCons.html Creates an adapter which will chain this stream with another. ```APIDOC ## fn chain<R>(self, next: R) -> Chain<Self, R> ### Description Creates an adapter which will chain this stream with another. ### Method `chain` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (Chain<Self, R>) - `Chain<Self, R>`: An adapter that chains two `Read`ers. #### Response Example None ``` -------------------------------- ### PopIter Methods Source: https://docs.rs/ringbuf/latest/ringbuf/traits/consumer/struct.PopIter.html Provides documentation for the core methods of the PopIter struct, including its creation and commit functionality. ```APIDOC ## Struct PopIter ringbuf::traits::consumer An iterator that removes items from the ring buffer. Producer will see removed items only when iterator is dropped or `PopIter::commit` is called. ### `fn new(inner: &'a mut C) -> Self` Create an iterator. ### `fn commit(&mut self)` Send information about removed items to the ring buffer. ``` -------------------------------- ### Get Type ID Source: https://docs.rs/ringbuf/latest/ringbuf/storage/struct.Heap.html Gets the TypeId of the current type. This is a blanket implementation for any type that is 'static. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Get Weak Reference Count Source: https://docs.rs/ringbuf/latest/ringbuf/struct.Arc.html Illustrates how to get the number of weak references to an Arc. This method is safe but requires careful handling as the count can change concurrently. ```rust use std::sync::Arc; let five = Arc::new(5); let _weak_five = Arc::downgrade(&five); // This assertion is deterministic because we haven't shared // the `Arc` or `Weak` between threads. assert_eq!(1, Arc::weak_count(&five)); ``` -------------------------------- ### Ring Buffer Initialization Macro Source: https://docs.rs/ringbuf/latest/src/ringbuf/rb/macros.rs.html The `rb_impl_init` macro provides implementations for `Default` and `From` traits for ring buffers backed by `Array`, `Heap`, and `Box<[T]>` storage. It simplifies the creation of ring buffers from different data structures. ```rust macro_rules! rb_impl_init { ($type:ident) => { impl<T, const N: usize> Default for $type<crate::storage::Array<T, N>> { fn default() -> Self { unsafe { Self::from_raw_parts(crate::utils::uninit_array().into(), usize::default(), usize::default()) } } } impl<T, const N: usize> From<[T; N]> for $type<crate::storage::Array<T, N>> { fn from(value: [T; N]) -> Self { let (read, write) = (0, value.len()); unsafe { Self::from_raw_parts(crate::utils::array_to_uninit(value).into(), read, write) } } } #[cfg(feature = "alloc")] impl<T> $type<crate::storage::Heap<T>> { /// Creates a new instance of a ring buffer. /// /// *Panics if allocation failed or `capacity` is zero.* pub fn new(capacity: usize) -> Self { unsafe { Self::from_raw_parts(crate::storage::Heap::<T>::new(capacity), usize::default(), usize::default()) } } /// Creates a new instance of a ring buffer returning an error if allocation failed. /// /// *Panics if `capacity` is zero.* pub fn try_new(capacity: usize) -> Result<Self, alloc::collections::TryReserveError> { let mut vec = alloc::vec::Vec::<core::mem::MaybeUninit<T>>::new(); vec.try_reserve_exact(capacity)?; unsafe { vec.set_len(capacity) }; Ok(unsafe { Self::from_raw_parts(vec.into_boxed_slice().into(), usize::default(), usize::default()) }) } } #[cfg(feature = "alloc")] impl<T> From<alloc::vec::Vec<T>> for $type<crate::storage::Heap<T>> { fn from(value: alloc::vec::Vec<T>) -> Self { let (read, write) = (0, value.len()); unsafe { Self::from_raw_parts(crate::utils::vec_to_uninit(value).into(), read, write) } } } #[cfg(feature = "alloc")] impl<T> From<alloc::boxed::Box<[T]>> for $type<crate::storage::Heap<T>> { fn from(value: alloc::boxed::Box<[T]>) -> Self { let (read, write) = (0, value.len()); unsafe { Self::from_raw_parts(crate::utils::boxed_slice_to_uninit(value).into(), read, write) } } } }; } pub(crate) use rb_impl_init; ``` -------------------------------- ### Ring Buffer with Static Allocation Source: https://docs.rs/ringbuf/latest/index.html Illustrates how to use StaticRb for ring buffer functionality without heap allocation, suitable for embedded systems or scenarios where dynamic memory is restricted. Shows basic push and pop operations. ```rust use ringbuf::{traits::*, StaticRb}; const RB_SIZE: usize = 1; let mut rb = StaticRb::<i32, RB_SIZE>::default(); let (mut prod, mut cons) = rb.split_ref(); assert_eq!(prod.try_push(123), Ok(())); assert_eq!(prod.try_push(321), Err(321)); assert_eq!(cons.try_pop(), Some(123)); assert_eq!(cons.try_pop(), None); ``` -------------------------------- ### type_id Source: https://docs.rs/ringbuf/latest/ringbuf/struct.Arc.html Gets the `TypeId` of `self`. This is a blanket implementation for `Any`. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Returns * `TypeId` - The `TypeId` of the object. ``` -------------------------------- ### fn by_ref(&mut self) -> &mut Self Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/frozen/type.FrozenCons.html Creates a “by reference” adapter for this instance of `Read`. ```APIDOC ## fn by_ref(&mut self) -> &mut Self ### Description Creates a “by reference” adapter for this instance of `Read`. ### Method `by_ref` ### Parameters None ### Request Example None ### Response #### Success Response (&mut Self) - `&mut Self`: A mutable reference to the `Read`er. #### Response Example None ``` -------------------------------- ### Get Ring Buffer Capacity Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/caching/struct.Caching.html Returns the total capacity of the ring buffer. ```rust fn capacity(&self) -> NonZeroUsize ``` -------------------------------- ### Get Ring Buffer Reference Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/caching/struct.Caching.html Returns a reference to the underlying ring buffer. ```rust fn rb_ref(&self) -> &R ``` -------------------------------- ### Get Storage Length Source: https://docs.rs/ringbuf/latest/ringbuf/storage/type.Array.html Returns the total number of elements the storage can hold. ```rust fn len(&self) -> usize; ``` -------------------------------- ### by_ref Source: https://docs.rs/ringbuf/latest/ringbuf/rb/shared/struct.SharedRb.html Creates a “by reference” adapter for this instance of `Write`. ```APIDOC ## by_ref ### Description Creates a “by reference” adapter for this instance of `Write`. ### Method `by_ref` ### Parameters None ### Returns - `&mut Self`: A mutable reference to the writer. ``` -------------------------------- ### Create and Convert Arc with Custom Allocator Source: https://docs.rs/ringbuf/latest/ringbuf/struct.Arc.html Demonstrates creating an Arc with a custom allocator, converting it to raw pointers, and then back into an Arc. This is useful for managing shared, mutable data across threads with specific allocation strategies. Ensure proper handling to avoid memory unsafety. ```rust #![feature(allocator_api)] use std::sync::Arc; use std::alloc::System; let x = Arc::new_in("hello".to_owned(), System); let (x_ptr, alloc) = Arc::into_raw_with_allocator(x); unsafe { // Convert back to an `Arc` to prevent leak. let x = Arc::from_raw_in(x_ptr, System); assert_eq!(&*x, "hello"); // Further calls to `Arc::from_raw(x_ptr)` would be memory-unsafe. } // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling! ``` -------------------------------- ### Get Vacant Length Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/caching/struct.Caching.html Returns the number of empty slots available in the ring buffer. ```rust fn vacant_len(&self) -> usize ``` -------------------------------- ### Get Occupied Length Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/caching/struct.Caching.html Returns the number of items currently stored in the ring buffer. ```rust fn occupied_len(&self) -> usize ``` -------------------------------- ### Create New Direct Wrapper Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/direct/struct.Direct.html Creates a new Direct wrapper for a ring buffer. Panics if a wrapper with matching rights already exists. ```rust pub fn new(rb: R) -> Self> ``` -------------------------------- ### Create By Reference Adapter (std feature) Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/direct/type.Prod.html Creates a "by reference" adapter for the `Write` instance. Available only when the `std` feature is enabled. ```rust fn by_ref(&mut self) -> &mut Self where Self: Sized, ``` -------------------------------- ### Get Underlying Ring Buffer Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/caching/struct.Caching.html Provides direct access to the underlying ring buffer. ```rust fn rb(&self) -> &<Self::RbRef as RbRef>::Rb ``` -------------------------------- ### Get Immutable Pointer to Storage Source: https://docs.rs/ringbuf/latest/ringbuf/storage/type.Array.html Returns a constant pointer to the beginning of the storage items. ```rust fn as_ptr(&self) -> *const MaybeUninit<Self::Item>; ``` -------------------------------- ### By Reference Adapter Source: https://docs.rs/ringbuf/latest/ringbuf/type.HeapRb.html Creates a "by reference" adapter for a Read instance. ```APIDOC ## fn by_ref(&mut self) -> &mut Self ### Description Creates a “by reference” adapter for this instance of `Read`. ### Method `by_ref` ### Response #### Success Response (&mut Self) - `&mut Self`: A mutable reference to the by-reference adapter. ``` -------------------------------- ### Get Next Write Index Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/caching/struct.Caching.html Returns the index where the next item will be written in the ring buffer. ```rust fn write_index(&self) -> usize ``` -------------------------------- ### write_all Source: https://docs.rs/ringbuf/latest/ringbuf/type.StaticRb.html Attempts to write an entire buffer into this writer. Available on crate feature `std` only. ```APIDOC ## write_all ### Description Attempts to write an entire buffer into this writer. Available on crate feature `std` only. ### Method `write_all` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **buf** (&[u8]) - Required - The buffer to write entirely. ### Request Example None ### Response #### Success Response `Result<(), Error>` #### Response Example None ``` -------------------------------- ### pub fn try_new_uninit() -> Result<Arc<MaybeUninit<T>>, AllocError> Source: https://docs.rs/ringbuf/latest/ringbuf/struct.Arc.html Nightly-only experimental API. Constructs a new Arc with uninitialized contents, returning an error if allocation fails. ```APIDOC ## pub fn try_new_uninit() -> Result<Arc<MaybeUninit<T>>, AllocError> ### Description Nightly-only experimental API. (`allocator_api`) Constructs a new `Arc` with uninitialized contents, returning an error if allocation fails. ### Examples ```rust #![feature(allocator_api)] use std::sync::Arc; let mut five = Arc::<u32>::try_new_uninit()?; // Deferred initialization: Arc::get_mut(&mut five).unwrap().write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5); ``` ### Source Source ``` -------------------------------- ### Get Last Read Index Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/caching/struct.Caching.html Returns the index of the last item that was read from the ring buffer. ```rust fn read_index(&self) -> usize ``` -------------------------------- ### Get Storage Length Source: https://docs.rs/ringbuf/latest/ringbuf/storage/struct.Heap.html Returns the current length of the storage. Implemented as part of the Storage trait. ```rust fn len(&self) -> usize ``` -------------------------------- ### from (Array) Source: https://docs.rs/ringbuf/latest/ringbuf/rb/local/struct.LocalRb.html Converts a fixed-size array into a `LocalRb`. ```APIDOC ## from (Array) ### Description Converts a fixed-size array into a `LocalRb`. ### Method `from` ### Parameters - **value** (`[T; N]`) - The array to convert. ### Returns - `Self` - A `LocalRb` instance initialized with the array's elements. ``` -------------------------------- ### Clone Arc<str, System> from Reference into Allocator Source: https://docs.rs/ringbuf/latest/ringbuf/struct.Arc.html Shows how to construct a new Arc<str, System> by cloning a string slice reference into a specific allocator using `clone_from_ref_in`. This experimental API requires `clone_from_ref` and `allocator_api` features. ```rust #![feature(clone_from_ref)] #![feature(allocator_api)] use std::sync::Arc; use std::alloc::System; let hello: Arc<str, System> = Arc::clone_from_ref_in("hello", System); ``` -------------------------------- ### Get Vacant Slices Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/direct/type.Prod.html Provides direct, read-only access to the vacant memory slices in the ring buffer. ```rust fn vacant_slices( &self, ) -> (&[MaybeUninit<Self::Item>], &[MaybeUninit<Self::Item>]) ``` -------------------------------- ### try_new_uninit_in Source: https://docs.rs/ringbuf/latest/ringbuf/struct.Arc.html Constructs a new Arc with uninitialized contents in the provided allocator. This is a nightly-only experimental API. ```APIDOC ## try_new_uninit_in ### Description Constructs a new `Arc` with uninitialized contents, in the provided allocator, returning an error if allocation fails. ### Method `Arc::<T, A>::try_new_uninit_in(alloc: A) -> Result<Arc<MaybeUninit<T>, A>, AllocError>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust #![feature(allocator_api)] #![feature(get_mut_unchecked)] use std::sync::Arc; use std::alloc::System; let mut five = Arc::<u32, _>::try_new_uninit_in(System)?; let five = unsafe { // Deferred initialization: Arc::get_mut_unchecked(&mut five).as_mut_ptr().write(5); five.assume_init() }; assert_eq!(*five, 5); ``` ### Response #### Success Response (200) `Arc<MaybeUninit<T>, A>` #### Response Example None ``` -------------------------------- ### Get Ring Buffer Item Type Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/direct/type.Obs.html Associated type representing the items stored in the ring buffer. ```rust type Item = <<R as RbRef>::Rb as Observer>::Item; ``` -------------------------------- ### take Source: https://docs.rs/ringbuf/latest/ringbuf/traits/consumer/type.Iter.html Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. ```APIDOC ## fn take(self, n: usize) -> Take<Self> ### Description Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. ### Method `take` ### Parameters #### Path Parameters - **n** (usize) - Required - The maximum number of elements to yield. ``` -------------------------------- ### Get Reference to LocalRb Source: https://docs.rs/ringbuf/latest/ringbuf/rb/local/struct.LocalRb.html Converts `self` into a shared reference to `LocalRb<S>`. This is part of the `AsRef` trait implementation. ```rust fn as_ref(&self) -> &Self ``` -------------------------------- ### Try Clone Arc<str, System> from Reference into Allocator Source: https://docs.rs/ringbuf/latest/ringbuf/struct.Arc.html Demonstrates attempting to construct a new Arc<str, System> by cloning a string slice reference into a specific allocator using `try_clone_from_ref_in`. This experimental API returns a Result for error handling on allocation failure and requires `clone_from_ref` and `allocator_api` features. ```rust #![feature(clone_from_ref)] #![feature(allocator_api)] use std::sync::Arc; use std::alloc::System; let hello: Arc<str, System> = Arc::try_clone_from_ref_in("hello", System)?; ``` -------------------------------- ### Get Reference to Last Item Source: https://docs.rs/ringbuf/latest/ringbuf/rb/local/struct.LocalRb.html Returns a reference to the most recent item in the ring buffer, if one exists. ```rust fn last(&self) -> Option<&Self::Item> ``` -------------------------------- ### Create New Heap Storage Source: https://docs.rs/ringbuf/latest/ringbuf/storage/struct.Heap.html Creates a new Heap storage with an exact capacity. This is the primary way to initialize Heap storage. ```rust pub fn new(capacity: usize) -> Self ``` -------------------------------- ### Get Reference to First Item Source: https://docs.rs/ringbuf/latest/ringbuf/rb/local/struct.LocalRb.html Returns a reference to the eldest item in the ring buffer, if one exists. ```rust fn first(&self) -> Option<&Self::Item> ``` -------------------------------- ### by_ref Source: https://docs.rs/ringbuf/latest/ringbuf/type.StaticRb.html Creates a “by reference” adapter for this instance of `Read`. ```APIDOC ## by_ref ### Description Creates a “by reference” adapter for this instance of `Read`. ### Method `by_ref` ### Parameters None ### Request Example None ### Response #### Success Response `&mut Self` #### Response Example None ``` -------------------------------- ### Getting Current Write Index Source: https://docs.rs/ringbuf/latest/src/ringbuf/rb/shared.rs.html Atomically loads and returns the current write index using Acquire ordering. ```rust #[inline] fn write_index(&self) -> usize { self.write_index.load(Ordering::Acquire) } ``` -------------------------------- ### Caching<R, P, C> Implementations for CachingCons Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/caching/type.CachingCons.html Provides methods for creating, observing, and freezing the Caching consumer. ```APIDOC ### impl<R: RbRef, const P: bool, const C: bool> Caching<R, P, C> #### `new(rb: R) -> Self` Create a new ring buffer cached wrapper. Panics if wrapper with matching rights already exists. #### `observe(&self) -> Obs<R>` Get ring buffer observer. #### `freeze(self) -> Frozen<R, P, C>` Freeze current state. ``` -------------------------------- ### Getting Current Read Index Source: https://docs.rs/ringbuf/latest/src/ringbuf/rb/shared.rs.html Atomically loads and returns the current read index using Acquire ordering. ```rust #[inline] fn read_index(&self) -> usize { self.read_index.load(Ordering::Acquire) } ``` -------------------------------- ### Creating Weak and Arc Pointers Source: https://docs.rs/ringbuf/latest/ringbuf/struct.Arc.html Shows how to create a Weak pointer from an Arc using `downgrade` and an Arc pointer. ```rust use std::sync::Arc; let my_arc = Arc::new(()); let my_weak = Arc::downgrade(&my_arc); ``` -------------------------------- ### Consumer Trait Documentation Source: https://docs.rs/ringbuf/latest/src/ringbuf/traits/consumer.rs.html This documentation outlines the methods available on the Consumer trait for interacting with a ring buffer. It covers setting and advancing the read index, accessing occupied memory, and retrieving elements. ```APIDOC ## `Consumer` Trait Provides the interface for consuming data from a ring buffer. ### Methods - **`set_read_index(&self, value: usize)`** - Sets the read index of the buffer. - **Safety**: The index must only move forward. All slots with indices less than `value` must be uninitialized until the write index, and all slots with indices equal to or greater must be initialized. - **`advance_read_index(&self, count: usize)`** - Moves the read pointer forward by `count` positions. - **Safety**: The first `count` items in the occupied memory must be moved out or dropped. Must not be called concurrently. - **`occupied_slices(&self) -> (&[MaybeUninit<Self::Item>], &[MaybeUninit<Self::Item>])`** - Provides direct access to the occupied memory of the ring buffer as two slices of `MaybeUninit`. - Elements with lower indices are older. The first slice contains older items than the second. - **Safety**: All items are initialized. Elements must be removed starting from the beginning of the first slice. If the first slice becomes empty, elements must be removed from the beginning of the second slice. This method must be followed by a call to `advance_read_index` with the number of items removed. - **`occupied_slices_mut(&mut self) -> (&mut [MaybeUninit<Self::Item>], &mut [MaybeUninit<Self::Item>])`** - Provides mutable direct access to the occupied memory of the ring buffer as two slices of `MaybeUninit`. - **Safety**: If an item is replaced with an uninitialized value, it must not be read afterward. This method must be followed by a call to `advance_read_index` with the number of items removed. - **`as_slices(&self) -> (&[Self::Item], &[Self::Item])`** - Returns two slices containing the contents of the ring buffer. - **`as_mut_slices(&mut self) -> (&mut [Self::Item], &mut [Self::Item])`** - Returns two mutable slices containing the contents of the ring buffer. - **`first(&self) -> Option<&Self::Item>`** - Returns a reference to the eldest item in the ring buffer, if it exists. - **`first_mut(&mut self) -> Option<&mut Self::Item>`** - Returns a mutable reference to the eldest item in the ring buffer, if it exists. - **`last(&self) -> Option<&Self::Item>`** - Returns a reference to the most recent item in the ring buffer, if it exists. Note: This may not be the actual most recent item if there is concurrent producer activity. - **`last_mut(&mut self) -> Option<&mut Self::Item>`** - Returns a mutable reference to the most recent item in the ring buffer, if it exists. Note: This may not be the actual most recent item if there is concurrent producer activity. - **`try_pop(&mut self) -> Option<Self::Item>`** - Removes the eldest item from the ring buffer and returns it. - Returns `None` if the ring buffer is empty. ``` -------------------------------- ### CachingProd Observer Methods Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/caching/type.CachingProd.html Provides methods for observing the state of the CachingProd, including getting the item type and capacity. ```APIDOC ## type Item = <<R as RbRef>::Rb as Observer>::Item ### Description The type of items stored in the ring buffer. ### Type Alias ``` ```APIDOC ## fn capacity(&self) -> NonZeroUsize ### Description Capacity of the ring buffer. ### Method `fn` ### Returns A `NonZeroUsize` representing the capacity of the ring buffer. ``` -------------------------------- ### Get Mutable Reference to LocalRb Source: https://docs.rs/ringbuf/latest/ringbuf/rb/local/struct.LocalRb.html Converts `self` into a mutable reference to `LocalRb<S>`. This is part of the `AsMut` trait implementation. ```rust fn as_mut(&mut self) -> &mut Self ``` -------------------------------- ### Try Create New LocalRb with Heap Allocation Source: https://docs.rs/ringbuf/latest/ringbuf/rb/local/struct.LocalRb.html Attempts to create a new LocalRb instance with a specified capacity using heap allocation, returning an error if allocation fails. Panics if capacity is zero. ```rust pub fn try_new(capacity: usize) -> Result<Self, TryReserveError> ``` -------------------------------- ### Heap Implementations Source: https://docs.rs/ringbuf/latest/ringbuf/storage/struct.Heap.html Provides implementations for Heap, including conversions from and to common Rust collection types like Box and Vec, and the Storage trait. ```APIDOC ## Heap Implementations ### `impl<T> From<Box<[MaybeUninit<T>]>> for Heap<T>` #### Description Converts a `Box<[MaybeUninit<T>]>` into a `Heap<T>`. ### `impl<T> From<Vec<MaybeUninit<T>>> for Heap<T>` #### Description Converts a `Vec<MaybeUninit<T>>` into a `Heap<T>`. ### `impl<T> From<Heap<T>> for Box<[MaybeUninit<T>]>` #### Description Converts a `Heap<T>` into a `Box<[MaybeUninit<T>]>`. ### `impl<T> Storage for Heap<T>` #### Description Implements the `Storage` trait for `Heap<T>`, providing methods to interact with the storage. ##### Methods: - `as_mut_ptr(&self) -> *mut MaybeUninit<T>`: Returns a mutable pointer to the beginning of the storage items. - `len(&self) -> usize`: Returns the current length of the storage. - `is_empty(&self) -> bool`: Checks if the storage is empty. - `as_ptr(&self) -> *const MaybeUninit<Self::Item>`: Returns a pointer to the beginning of the storage items. - `unsafe fn slice(&self, range: Range<usize>) -> &[MaybeUninit<Self::Item>]`: Returns a mutable slice of storage in the specified range. - `unsafe fn slice_mut(&self, range: Range<usize>) -> &mut [MaybeUninit<Self::Item>]`: Returns a mutable slice of storage in the specified range. ``` -------------------------------- ### Get Ring Buffer Observer Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/caching/struct.Caching.html Retrieves an observer for the underlying ring buffer, allowing read-only access to its state. ```rust pub fn observe(&self) -> Obs<R> ``` -------------------------------- ### Write Formatted Source: https://docs.rs/ringbuf/latest/ringbuf/type.HeapRb.html Glue for usage of the `write!` macro with implementors of this trait. ```APIDOC ## fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error> ### Description Glue for usage of the `write!` macro with implementors of this trait. ### Method `write_fmt` ### Parameters #### Path Parameters - `args` (*Arguments<'_>*): The arguments for formatting. ### Response #### Success Response (Result<(), Error>) - `Ok(())`: Indicates the operation was successful. #### Error Response (Result<(), Error>) - `Err(Error)`: An error encountered during formatting. ``` -------------------------------- ### Get Immutable Pointer to Storage Source: https://docs.rs/ringbuf/latest/ringbuf/storage/struct.Heap.html Returns a pointer to the beginning of the storage items. Implemented as part of the Storage trait. ```rust fn as_ptr(&self) -> *const MaybeUninit<Self::Item> ``` -------------------------------- ### From<Owning<[MaybeUninit<T>; N]>> for [MaybeUninit<T>; N] Source: https://docs.rs/ringbuf/latest/ringbuf/storage/struct.Owning.html This implementation allows converting an `Owning<[MaybeUninit<T>; N]>` into a `[MaybeUninit<T>; N]` array. ```APIDOC ## impl<T, const N: usize> From<Owning<[MaybeUninit<T>; N]>> for [MaybeUninit<T>; N] ### fn from(value: Owning<[MaybeUninit<T>; N]>) -> Self Converts an `Owning<[MaybeUninit<T>; N]>` into a `[MaybeUninit<T>; N]` array. ``` -------------------------------- ### stream_position Source: https://docs.rs/ringbuf/latest/ringbuf/struct.Arc.html Returns the current seek position from the start of the stream. This method is part of the Seek trait implementation for Arc<S>. ```APIDOC ## fn stream_position(&mut self) -> Result<u64, Error> ### Description Returns the current seek position from the start of the stream. ### Returns * `Result<u64, Error>` - A Result containing the current stream position if successful, or an Error if not. ``` -------------------------------- ### write_fmt Source: https://docs.rs/ringbuf/latest/ringbuf/type.StaticRb.html Glue for usage of the `write!` macro with implementors of this trait. ```APIDOC ## write_fmt ### Description Glue for usage of the `write!` macro with implementors of this trait. ### Method `write_fmt` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **args** (Arguments<'_>) - Required - The arguments for formatting. ### Request Example None ### Response #### Success Response `Result<(), Error>` #### Response Example None ``` -------------------------------- ### Direct Wrapper Methods for Cons Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/direct/type.Cons.html These methods are available on the Direct wrapper, which Cons is an alias for, allowing for the creation, observation, and freezing of the ring buffer state. ```APIDOC ## Implementations for `Direct<R, P, C>` ### `impl<R: RbRef, const P: bool, const C: bool> Direct<R, P, C>` #### `pub fn new(rb: R) -> Self` Create a new ring buffer direct wrapper. Panics if wrapper with matching rights already exists. #### `pub fn observe(&self) -> Obs<R>` Get ring buffer observer. #### `pub fn freeze(self) -> Frozen<R, P, C>` Freeze current state. ``` -------------------------------- ### Get minimum of two Arc<T, A> Source: https://docs.rs/ringbuf/latest/ringbuf/struct.Arc.html Returns the minimum of two `Arc` values. This method is available for `Arc<T, A>` where `T` implements `Ord`. ```rust fn min(self, other: Self) -> Self where Self: Sized, ``` -------------------------------- ### split (Box<LocalRb<S>>) Source: https://docs.rs/ringbuf/latest/ringbuf/rb/local/struct.LocalRb.html Perform splitting. Available on crate feature`alloc` only. ```APIDOC ## split (Box<LocalRb<S>>) ### Description Perform splitting. Available on crate feature`alloc` only. ### Method `split(self) -> (Self::Prod, Self::Cons)` ``` -------------------------------- ### Get maximum of two Arc<T, A> Source: https://docs.rs/ringbuf/latest/ringbuf/struct.Arc.html Returns the maximum of two `Arc` values. This method is available for `Arc<T, A>` where `T` implements `Ord`. ```rust fn max(self, other: Self) -> Self where Self: Sized, ``` -------------------------------- ### Get Mutable Reference to Last Item Source: https://docs.rs/ringbuf/latest/ringbuf/rb/local/struct.LocalRb.html Returns a mutable reference to the most recent item in the ring buffer, if one exists. ```rust fn last_mut(&mut self) -> Option<&mut Self::Item> ``` -------------------------------- ### Create New Frozen Ring Buffer Wrapper Source: https://docs.rs/ringbuf/latest/src/ringbuf/wrap/frozen.rs.html Initializes a new Frozen wrapper for a ring buffer. It asserts that no other wrapper with matching read/write rights already exists. ```rust pub fn new(rb: R) -> Self { if P { assert!(!unsafe { rb.rb().hold_write(true) }); } if C { assert!(!unsafe { rb.rb().hold_read(true) }); } unsafe { Self::new_unchecked(rb) } } ``` -------------------------------- ### Observer Methods Source: https://docs.rs/ringbuf/latest/ringbuf/wrap/direct/type.Cons.html Methods for observing the state and properties of the ring buffer. ```APIDOC ## fn capacity(&self) -> NonZeroUsize ### Description Capacity of the ring buffer. ### Method `capacity` ### Response #### Success Response (NonZeroUsize) - `NonZeroUsize` - The total capacity of the ring buffer. ``` ```APIDOC ## fn read_index(&self) -> usize ### Description Index of the last item in the ring buffer. ### Method `read_index` ### Response #### Success Response (usize) - `usize` - The current read index. ``` ```APIDOC ## fn write_index(&self) -> usize ### Description Index of the next empty slot in the ring buffer. ### Method `write_index` ### Response #### Success Response (usize) - `usize` - The current write index. ``` ```APIDOC ## unsafe fn unsafe_slices(&self, start: usize, end: usize) -> (&[MaybeUninit<Self::Item>], &[MaybeUninit<Self::Item>]) ### Description Get slice between `start` and `end` indices. ### Method `unsafe_slices` ### Parameters #### Path Parameters - `start` (usize) - Required - The starting index. - `end` (usize) - Required - The ending index. ### Response #### Success Response ((&[MaybeUninit<Self::Item>], &[MaybeUninit<Self::Item>])) - `(&[MaybeUninit<Self::Item>], &[MaybeUninit<Self::Item>])` - A tuple containing two slices representing the data between `start` and `end`. ``` ```APIDOC ## unsafe fn unsafe_slices_mut(&self, start: usize, end: usize) -> (&mut [MaybeUninit<Self::Item>], &mut [MaybeUninit<Self::Item>]) ### Description Get mutable slice between `start` and `end` indices. ### Method `unsafe_slices_mut` ### Parameters #### Path Parameters - `start` (usize) - Required - The starting index. - `end` (usize) - Required - The ending index. ### Response #### Success Response ((&mut [MaybeUninit<Self::Item>], &mut [MaybeUninit<Self::Item>])) - `(&mut [MaybeUninit<Self::Item>], &mut [MaybeUninit<Self::Item>])` - A tuple containing two mutable slices representing the data between `start` and `end`. ``` ```APIDOC ## fn read_is_held(&self) -> bool ### Description Whether read end is held by consumer. ### Method `read_is_held` ### Response #### Success Response (bool) - `bool` - `true` if the read end is held, `false` otherwise. ``` ```APIDOC ## fn write_is_held(&self) -> bool ### Description Whether write end is held by producer. ### Method `write_is_held` ### Response #### Success Response (bool) - `bool` - `true` if the write end is held, `false` otherwise. ``` ```APIDOC ## fn occupied_len(&self) -> usize ### Description The number of items stored in the buffer. ### Method `occupied_len` ### Response #### Success Response (usize) - `usize` - The number of occupied slots in the buffer. ``` ```APIDOC ## fn vacant_len(&self) -> usize ### Description The number of remaining free places in the buffer. ### Method `vacant_len` ### Response #### Success Response (usize) - `usize` - The number of vacant slots in the buffer. ``` ```APIDOC ## fn is_empty(&self) -> bool ### Description Checks if the ring buffer is empty. ### Method `is_empty` ### Response #### Success Response (bool) - `bool` - `true` if the buffer is empty, `false` otherwise. ``` ```APIDOC ## fn is_full(&self) -> bool ### Description Checks if the ring buffer is full. ### Method `is_full` ### Response #### Success Response (bool) - `bool` - `true` if the buffer is full, `false` otherwise. ``` -------------------------------- ### Get Mutable Reference to First Item Source: https://docs.rs/ringbuf/latest/ringbuf/rb/local/struct.LocalRb.html Returns a mutable reference to the eldest item in the ring buffer, if one exists. ```rust fn first_mut(&mut self) -> Option<&mut Self::Item> ```