Struct DataBuffer

Source
pub struct DataBuffer { /* private fields */ }
Expand description

Buffer of data. The data is stored as an array of bytes (Vec<u8>). DataBuffer keeps track of the type stored within via an explicit TypeId member. This allows one to hide the type from the compiler and check it only when necessary. It is particularly useful when the type of data is determined at runtime (e.g. when parsing numeric data).

Implementations§

Source§

impl DataBuffer

Source

pub fn with_type<T: Any>() -> Self

Construct an empty DataBuffer with a specific type.

Source

pub fn with_buffer_type(other: &DataBuffer) -> Self

Construct a DataBuffer with the same type as the given buffer without copying its data.

Source

pub fn with_capacity<T: Any>(n: usize) -> Self

Construct an empty DataBuffer with a capacity for a given number of typed elements. For setting byte capacity use with_byte_capacity.

Source

pub fn with_size<T: Any + Clone>(n: usize, def: T) -> Self

Construct a typed DataBuffer with a given size and filled with the specified default value.

§Examples
let buf = DataBuffer::with_size(8, 42usize); // Create buffer
let buf_vec: Vec<usize> = buf.into_vec().unwrap(); // Convert into `Vec`
assert_eq!(buf_vec, vec![42usize; 8]);
Source

pub fn from_vec<T: Any>(vec: Vec<T>) -> Self

Construct a DataBuffer from a given Vec<T> reusing the space already allocated by the given vector.

§Examples
let vec = vec![1u8, 3, 4, 1, 2];
let buf = DataBuffer::from_vec(vec.clone()); // Convert into buffer
let nu_vec: Vec<u8> = buf.into_vec().unwrap(); // Convert back into `Vec`
assert_eq!(vec, nu_vec);
Source

pub fn from_slice<T: Any + Clone>(slice: &[T]) -> Self

Construct a DataBuffer from a given slice by cloning the data.

Source

pub fn resize<T: Any + Clone>( &mut self, new_len: usize, value: T, ) -> Option<&mut Self>

Resizes the buffer in-place to store new_len elements and returns an optional mutable reference to Self.

If T does not correspond to the underlying element type, then None is returned and the DataBuffer is left unchanged.

This function has the similar properties to Vec::resize.

Source

pub fn copy_from_slice<T: Any + Copy>(&mut self, slice: &[T]) -> &mut Self

Copy data from a given slice into the current buffer.

The DataBuffer is extended if the given slice is larger than the number of elements already stored in this DataBuffer.

Source

pub fn clear(&mut self)

Clear the data buffer without destroying its type information.

Source

pub fn fill<T: Any + Clone>(&mut self, def: T) -> Option<&mut Self>

Fill the current buffer with copies of the given value. The size of the buffer is left unchanged. If the given type doesn’t patch the internal type, None is returned, otherwise a mut reference to the modified buffer is returned.

§Examples
let vec = vec![1u8, 3, 4, 1, 2];
let mut buf = DataBuffer::from_vec(vec.clone()); // Convert into buffer
buf.fill(0u8);
assert_eq!(buf.into_vec::<u8>().unwrap(), vec![0u8, 0, 0, 0, 0]);
Source

pub fn push<T: Any>(&mut self, element: T) -> Option<&mut Self>

Add an element to this buffer. If the type of the given element coincides with the type stored by this buffer, then the modified buffer is returned via a mutable reference. Otherwise, None is returned.

Source

pub fn check<T: Any>(self) -> Option<Self>

Check if the current buffer contains elements of the specified type. Returns Some(self) if the type matches and None otherwise.

Source

pub fn check_ref<T: Any>(&self) -> Option<&Self>

Check if the current buffer contains elements of the specified type. Returns None if the check fails, otherwise a reference to self is returned.

Source

pub fn check_mut<'a, T: Any>(&'a mut self) -> Option<&'a mut Self>

Check if the current buffer contains elements of the specified type. Same as check_ref but consumes and produces a mut reference to self.

Source

pub fn element_type_id(&self) -> TypeId

Get the TypeId of data stored within this buffer.

Source

pub fn len(&self) -> usize

Get the number of elements stored in this buffer.

Source

pub fn is_empty(&self) -> bool

Check if there are any elements stored in this buffer.

Source

pub fn byte_capacity(&self) -> usize

Get the byte capacity of this buffer.

Source

pub fn element_size(&self) -> usize

Get the size of the element type in bytes.

Source

pub fn iter<'a, T: Any + 'a>(&'a self) -> Option<Iter<'_, T>>

Return an iterator to a slice representing typed data. Returs None if the given type T doesn’t match the internal.

§Examples
let vec = vec![1.0_f32, 23.0, 0.01, 42.0, 11.43];
let buf = DataBuffer::from(vec.clone()); // Convert into buffer
for (i, &val) in buf.iter::<f32>().unwrap().enumerate() {
    assert_eq!(val, vec[i]);
}
Source

pub fn iter_mut<'a, T: Any + 'a>(&'a mut self) -> Option<IterMut<'_, T>>

Return an iterator to a mutable slice representing typed data. Returs None if the given type T doesn’t match the internal.

Source

pub fn append_clone_to_vec<'a, T>( &self, vec: &'a mut Vec<T>, ) -> Option<&'a mut Vec<T>>
where T: Any + Clone,

Append cloned items from this buffer to a given Vec<T>. Return the mutable reference Some(vec) if type matched the internal type and None otherwise.

Source

pub fn append_copy_to_vec<'a, T>( &self, vec: &'a mut Vec<T>, ) -> Option<&'a mut Vec<T>>
where T: Any + Copy,

Append copied items from this buffer to a given Vec<T>. Return the mutable reference Some(vec) if type matched the internal type and None otherwise. This may be faster than append_clone_to_vec.

Source

pub fn clone_into_vec<T: Any + Clone>(&self) -> Option<Vec<T>>

Clones contents of self into the given Vec.

Source

pub fn copy_into_vec<T: Any + Copy>(&self) -> Option<Vec<T>>

Copies contents of self into the given Vec.

Source

pub fn into_vec<T: Any>(self) -> Option<Vec<T>>

An alternative to using the Into trait. This function helps the compiler determine the type T automatically.

Source

pub fn as_slice<T: Any>(&self) -> Option<&[T]>

Convert this buffer into a typed slice. Returs None if the given type T doesn’t match the internal.

Source

pub fn as_mut_slice<T: Any>(&mut self) -> Option<&mut [T]>

Convert this buffer into a typed mutable slice. Returs None if the given type T doesn’t match the internal.

Source

pub fn get<T: Any + Copy>(&self, i: usize) -> Option<T>

Get i’th element of the buffer by value.

Source

pub fn get_ref<T: Any>(&self, i: usize) -> Option<&T>

Get a const reference to the i’th element of the buffer.

Source

pub fn get_mut<T: Any>(&mut self, i: usize) -> Option<&mut T>

Get a mutable reference to the i’th element of the buffer.

Source

pub fn reserve_bytes(&mut self, additional: usize)

Reserves capacity for at least additional more bytes to be inserted in this buffer.

Source

pub unsafe fn get_unchecked<T: Any + Copy>(&self, i: usize) -> T

Get i’th element of the buffer by value without checking type. This can be used to reinterpret the internal data as a different type. Note that if the size of the given type T doesn’t match the size of the internal type, i will really index the ith T sized chunk in the current buffer. See the implementation for details.

Source

pub unsafe fn get_unchecked_ref<T: Any>(&self, i: usize) -> &T

Get a const reference to the i’th element of the buffer. This can be used to reinterpret the internal data as a different type. Note that if the size of the given type T doesn’t match the size of the internal type, i will really index the ith T sized chunk in the current buffer. See the implementation for details.

Source

pub unsafe fn get_unchecked_mut<T: Any>(&mut self, i: usize) -> &mut T

Get a mutable reference to the i’th element of the buffer. This can be used to reinterpret the internal data as a different type. Note that if the size of the given type T doesn’t match the size of the internal type, i will really index the ith T sized chunk in the current buffer. See the implementation for details.

Source

pub fn get_bytes(&self, i: usize) -> &[u8]

Get a const reference to the byte slice of the i’th element of the buffer.

Source

pub unsafe fn get_bytes_mut(&mut self, i: usize) -> &mut [u8]

Get a mutable reference to the byte slice of the i’th element of the buffer.

§Unsafety

This function is marked as unsafe since the returned bytes may be modified arbitrarily, which may potentially produce malformed values.

Source

pub unsafe fn reinterpret_into_vec<T>(self) -> Vec<T>

Move buffer data to a vector with a given type, reinterpreting the data type as required.

Source

pub unsafe fn reinterpret_as_slice<T>(&self) -> &[T]

Borrow buffer data and reinterpret it as a slice of a given type.

Source

pub unsafe fn reinterpret_as_mut_slice<T>(&mut self) -> &mut [T]

Mutably borrow buffer data and reinterpret it as a mutable slice of a given type.

Source

pub unsafe fn reinterpret_iter<T>(&self) -> Iter<'_, T>

Borrow buffer data and iterate over reinterpreted underlying data.

Source

pub unsafe fn reinterpret_iter_mut<T>(&mut self) -> IterMut<'_, T>

Mutably borrow buffer data and mutably iterate over reinterpreted underlying data.

Source

pub fn as_bytes(&self) -> &[u8]

Peak at the internal representation of the data.

Source

pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8]

Get a mutable reference to the internal data representation.

§Unsafety

This function is marked as unsafe since the returned bytes may be modified arbitrarily, which may potentially produce malformed values.

Source

pub fn byte_chunks<'a>(&'a self) -> impl Iterator<Item = &'a [u8]> + 'a

Iterate over chunks type sized chunks of bytes without interpreting them. This avoids needing to know what type data you’re dealing with. This type of iterator is useful for transferring data from one place to another for a generic buffer.

Source

pub unsafe fn byte_chunks_mut<'a>( &'a mut self, ) -> impl Iterator<Item = &'a mut [u8]> + 'a

Mutably iterate over chunks type sized chunks of bytes without interpreting them. This avoids needing to know what type data you’re dealing with. This type of iterator is useful for transferring data from one place to another for a generic buffer, or modifying the underlying untyped bytes (e.g. bit twiddling).

§Unsafety

This function is marked as unsafe since the returned bytes may be modified arbitrarily, which may potentially produce malformed values.

Source

pub unsafe fn push_bytes(&mut self, bytes: &[u8]) -> Option<&mut Self>

Add bytes to this buffer. If the size of the given slice coincides with the number of bytes occupied by the underlying element type, then these bytes are added to the underlying data buffer and a mutable reference to the buffer is returned. Otherwise, None is returned, and the buffer remains unmodified.

Source

pub unsafe fn extend_bytes(&mut self, bytes: &[u8]) -> Option<&mut Self>

Add bytes to this buffer. If the size of the given slice is a multiple of the number of bytes occupied by the underlying element type, then these bytes are added to the underlying data buffer and a mutable reference to the buffer is returned. Otherwise, None is returned and the buffer is unmodified.

Source

pub unsafe fn append_bytes(&mut self, bytes: &mut Vec<u8>) -> Option<&mut Self>

Move bytes to this buffer. If the size of the given vector is a multiple of the number of bytes occupied by the underlying element type, then these bytes are moved to the underlying data buffer and a mutable reference to the buffer is returned. Otherwise, None is returned and both the buffer and the input vector remain unmodified.

Source

pub fn append(&mut self, buf: &mut DataBuffer) -> Option<&mut Self>

Move bytes to this buffer. The given buffer must have the same underlying type as self.

Source

pub fn rotate_left(&mut self, mid: usize)

Rotates the slice in-place such that the first mid elements of the slice move to the end while the last self.len() - mid elements move to the front. After calling rotate_left, the element previously at index mid will become the first element in the slice.

§Example
let mut buf = DataBuffer::from_vec(vec![1u32,2,3,4,5]);
buf.rotate_left(3);
assert_eq!(buf.as_slice::<u32>().unwrap(), &[4,5,1,2,3]);
Source

pub fn rotate_right(&mut self, k: usize)

Rotates the slice in-place such that the first self.len() - k elements of the slice move to the end while the last k elements move to the front. After calling rotate_right, the element previously at index k will become the first element in the slice.

§Example
let mut buf = DataBuffer::from_vec(vec![1u32,2,3,4,5]);
buf.rotate_right(3);
assert_eq!(buf.as_slice::<u32>().unwrap(), &[3,4,5,1,2]);

Trait Implementations§

Source§

impl Clone for DataBuffer

Source§

fn clone(&self) -> DataBuffer

Returns a copy of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for DataBuffer

Source§

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

Formats the value using the given formatter. Read more
Source§

impl<'a, T> From<&'a [T]> for DataBuffer
where T: Any + Clone,

Convert a &[T] to a DataBuffer.

Source§

fn from(slice: &'a [T]) -> DataBuffer

Converts to this type from the input type.
Source§

impl<T> From<Vec<T>> for DataBuffer
where T: Any,

Convert a Vec<T> to a DataBuffer.

Source§

fn from(vec: Vec<T>) -> DataBuffer

Converts to this type from the input type.
Source§

impl Hash for DataBuffer

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<T> Into<Option<Vec<T>>> for DataBuffer
where T: Any + Clone,

Convert a DataBuffer to a Option<Vec<T>>.

Source§

fn into(self) -> Option<Vec<T>>

Converts this type into the (usually inferred) input type.
Source§

impl PartialEq for DataBuffer

Source§

fn eq(&self, other: &DataBuffer) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for DataBuffer

Auto Trait Implementations§

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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.