Skip to main content

Buffer

Struct Buffer 

Source
pub struct Buffer<T>
where T: Clone + Default,
{ /* private fields */ }
Expand description

Low-level contiguous storage with a readable window and spare tail capacity.

Buffer stores initialized values and tracks a readable window as data[position..limit]. Values before position are considered consumed, and values after limit are spare capacity that callers may fill before advancing the limit.

The backing storage is fully initialized up front, so T is constrained to Clone + Default. Cloning is used when values enter or leave the buffer, while default initialization keeps every spare slot valid for the slice-based stream traits.

This type is intentionally a low-level, hot-path API. It exposes the full backing storage through Self::data and Self::data_mut so higher-level buffering code can avoid repeated slicing and bounds checks. Callers that mutate the backing storage directly must preserve the position <= limit <= capacity invariant and must only make initialized spare elements readable by calling Self::advance.

The unsafe methods are for code that has already validated ranges at a higher level. They keep debug assertions for development builds, but those assertions are not a substitute for the documented safety preconditions.

§Window model

§Examples

use qubit_io::Buffer;

let mut buffer = Buffer::<u8>::with_capacity(4);
buffer.data_mut()[0..2].copy_from_slice(b"ab");
// SAFETY: Two initialized spare elements fit in this buffer.
unsafe {
    buffer.advance(2);
}

assert_eq!(b"ab", buffer.readable());
// SAFETY: One readable element is currently available.
unsafe {
    buffer.consume(1);
}
assert_eq!(b"b", buffer.readable());

§Type Parameters

  • T: Cloneable item type used for initialized backing storage.

Implementations§

Source§

impl<T> Buffer<T>
where T: Clone + Default,

Source

pub fn with_capacity(capacity: usize) -> Self

Creates an empty buffer with at least the requested capacity.

A requested capacity of 0 is raised to 1.

§Parameters
  • capacity: Requested element capacity.
§Returns

Returns a buffer with position == 0 and limit == 0.

§Panics

Panics if T::default() or T::clone() panics, or the requested backing length exceeds Vec’s supported capacity.

Source

pub fn try_with_capacity(capacity: usize) -> Result<Self, TryReserveError>

Tries to create an empty buffer with at least the requested capacity.

A requested capacity of 0 is raised to 1.

§Parameters
  • capacity: Requested element capacity.
§Returns

Returns an empty buffer with at least one element of capacity.

§Errors

Returns the original allocation error when the backing storage cannot reserve the requested capacity.

§Panics

Panics if T::default() or T::clone() panics.

Source

pub fn try_reserve_capacity( &mut self, capacity: usize, ) -> Result<(), TryReserveError>

Tries to ensure that the total element capacity is at least capacity.

Existing consumed, readable, and spare windows retain their positions.

§Parameters
  • capacity: Required total element capacity.
§Returns

Returns Ok(()) after the requested capacity is available.

§Errors

Returns the original allocation error when the backing storage cannot reserve the additional capacity.

§Panics

Panics if growing the backing storage requires T::default() or T::clone() and either operation panics.

Source

pub fn capacity(&self) -> usize

Returns the total element capacity.

§Returns

The length of the backing storage.

Source

pub const fn position(&self) -> usize

Returns the current readable cursor.

§Returns

The start index of the readable window.

Source

pub const fn limit(&self) -> usize

Returns the current readable limit.

§Returns

The exclusive end index of the readable window.

Source

pub fn data(&self) -> &[T]

Returns the backing storage.

§Returns

The full initialized backing slice.

Source

pub fn data_mut(&mut self) -> &mut [T]

Returns the mutable backing storage.

Mutating elements outside the current readable or spare operation may invalidate higher-level assumptions about buffered contents.

§Returns

The full initialized backing slice.

Source

pub const fn available(&self) -> usize

Returns the number of readable elements.

§Returns

The length of data[position..limit].

Source

pub fn consumed(&self) -> &[T]

Returns the consumed prefix.

§Returns

The slice data[..position].

Source

pub fn readable(&self) -> &[T]

Returns the readable window.

§Returns

The slice data[position..limit].

Source

pub fn spare(&self) -> &[T]

Returns the spare tail.

§Returns

The slice data[limit..capacity].

Source

pub fn spare_mut(&mut self) -> &mut [T]

Returns the mutable spare tail.

§Returns

The slice data[limit..capacity].

Source

pub fn spare_capacity(&self) -> usize

Returns the number of spare elements after the limit.

§Returns

The length of data[limit..].

Source

pub const fn is_empty(&self) -> bool

Returns whether the readable window is empty.

§Returns

true when no elements are available for consumption.

Source

pub fn is_full(&self) -> bool

Returns whether the spare tail is empty.

§Returns

true when limit == capacity.

Source

pub fn spare_raw_parts_mut(&mut self) -> (&mut [T], usize, usize)

Returns raw spare-tail parts for hot-path callers.

The returned slice is the full backing storage. index is the start of the spare window, and count is the number of spare elements. Callers that need a slice can use Self::spare_mut; callers that already validated bounds can pass buffer and index directly to indexed unchecked operations that write from index.

§Returns

The backing storage, the spare start index, and the spare element count.

Source

pub fn clear(&mut self)

Clears all buffered contents.

This resets both cursors to zero without modifying stored values.

Source

pub unsafe fn consume(&mut self, count: usize)

Advances the readable cursor without checking bounds.

§Parameters
  • count: Number of readable elements to consume.
§Panics

Panics in debug builds if count > self.available().

§Safety

The caller must guarantee that count <= self.available().

Source

pub unsafe fn advance(&mut self, count: usize)

Advances the readable limit without checking bounds.

§Parameters
  • count: Number of initialized spare elements to make readable.
§Panics

Panics in debug builds if count > self.spare_capacity().

§Safety

The caller must guarantee that count <= self.spare_capacity().

Source

pub fn compact(&mut self)

Moves unread elements to the front of the backing storage.

Consumed elements are discarded. The unread element count is preserved, and the readable window starts at zero after compaction.

Source

pub unsafe fn copy_from( &mut self, input: &[T], input_index: usize, count: usize, )

Copies values from an external slice into the spare tail.

The cloned values are made readable by advancing the limit by count.

§Parameters
  • input: Source storage.
  • input_index: Start index inside input.
  • count: Number of values to copy.
§Panics

Panics if cloning an input item panics. Debug builds also panic if the requested input range does not fit or count > self.spare_capacity().

§Safety

The caller must guarantee that input_index..input_index + count is a valid range inside input, that the addition does not overflow, that count <= self.spare_capacity(), and that the source range does not overlap with this buffer’s destination range.

Source

pub unsafe fn copy_to( &mut self, output: &mut [T], output_index: usize, count: usize, )

Copies readable values into an external slice.

The cloned values are consumed by advancing the position by count.

§Parameters
  • output: Destination storage.
  • output_index: Start index inside output.
  • count: Number of values to copy.
§Panics

Panics if cloning a readable item panics. Debug builds also panic if the requested output range does not fit or count > self.available().

§Safety

The caller must guarantee that output_index..output_index + count is a valid range inside output, that the addition does not overflow, that count <= self.available(), and that the source range does not overlap with the destination range.

Trait Implementations§

Source§

impl<T> Clone for Buffer<T>
where T: Clone + Default + Clone,

Source§

fn clone(&self) -> Buffer<T>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T> Debug for Buffer<T>
where T: Clone + Default + Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T> Freeze for Buffer<T>
where Vec<T>: Freeze,

§

impl<T> RefUnwindSafe for Buffer<T>
where Vec<T>: RefUnwindSafe,

§

impl<T> Send for Buffer<T>
where Vec<T>: Send,

§

impl<T> Sync for Buffer<T>
where Vec<T>: Sync,

§

impl<T> Unpin for Buffer<T>
where Vec<T>: Unpin,

§

impl<T> UnsafeUnpin for Buffer<T>
where Vec<T>: UnsafeUnpin,

§

impl<T> UnwindSafe for Buffer<T>
where Vec<T>: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.