ByteArray

Struct ByteArray 

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

Debug derive and Display is intentionally left out to avoid any intentional data leakages through formatters

Implementations§

Source§

impl ByteArray

Source

pub fn new() -> Self

Standard constructor, use Self::with_capacity if you already know the capacity of your bytes for performance reasons

Source

pub fn with_capacity(size_in_bytes: usize) -> Self

reserves memory for a certain number of bytes for efficiency purposes

Source

pub fn fill_zeros(self) -> Self

👎Deprecated since 0.3.3: This will be renamed to with_zeros at a future version

fills the byte array with zeros to capacity this is usually only useful in the rare case where an odd word padding needs to be set in all other cases use ByteArray::init_zeros. This function does nothing if the ByteArray capacity has not been set (is 0)

§Example
use byte_array_ops::model::ByteArray;
let arr = ByteArray::default().fill_zeros(); // does nothing on an array with zero capacity
assert!(arr.as_bytes().is_empty());

let arr = ByteArray::with_capacity(5).fill_zeros();
assert_eq!(arr.as_bytes(),[0u8,0,0,0,0]);

// or in the rare cases where a different odd word padding is set

let arr = ByteArray::with_capacity(7)
                .fill_zeros();

assert_eq!(arr.as_bytes(),[0u8,0,0,0,0,0,0])

Source

pub fn fill_with(self, value: u8) -> Self

👎Deprecated since 0.3.3: This will be renamed to with_value at a future version

fills the byte array with the given value to capacity this is usually only useful in the rare case where an odd word padding needs to be set in all other cases use ByteArray::init_value.

§Note

This function does nothing (noop) if the ByteArray capacity has not been set (is 0)

§Example
use byte_array_ops::model::ByteArray;
let arr = ByteArray::default().fill_zeros(); // does nothing on an array with zero capacity
assert!(arr.as_bytes().is_empty());

let arr = ByteArray::with_capacity(5).fill_with(126);
assert_eq!(arr.as_bytes(),[126u8,126,126,126,126]);

// or in the rare cases where a different odd word padding is set

let arr = ByteArray::with_capacity(7)
                .fill_with(5);

assert_eq!(arr.as_bytes(),[5u8,5,5,5,5,5,5]);

Source

pub fn from_hex(hex_str: &str) -> Result<Self, ByteArrayError>

Create a byte array from a hex string (without 0x prefix)

§Example
use byte_array_ops::ByteArray;
let arr = ByteArray::from_hex("deadbeef")?;
assert_eq!(arr.as_bytes(), [0xde, 0xad, 0xbe, 0xef]);
Source

pub fn from_bin(bin_str: &str) -> Result<Self, ByteArrayError>

Create a byte array from a binary string (without 0b prefix)

§Example
use byte_array_ops::ByteArray;
let arr = ByteArray::from_bin("1010010")?;
assert_eq!(arr.as_bytes(), [0x52]);
Source

pub fn init_zeros(count: usize) -> Self

initialize the array with a certain amount of zeros internally this creates the byte array representation with vec![0u8;count] the rest is default initialized

Source

pub fn init_value(value: u8, count: usize) -> Self

initialize the array with a certain amount of value internally this creates the byte array representation with vec![value;count] the rest is default initialized

Source

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

returns a slices to the interior bytes

§NOTE

There is another method that provides a zero-cost move of the interior bytes using the Vec::from::<ByteArray> implementation. Please check the ByteArray’s From<ByteArray> implementation documentation

§Example
use byte_array_ops::model::ByteArray;

let arr : ByteArray = "0xff2569".parse().unwrap();

let slice = arr.as_bytes();

assert_eq!(slice, [0xff,0x25,0x69]);
Source

pub fn try_extend(self, other: ByteArray) -> Result<Self, ByteArrayError>

Chained constructor helper for concatening ByteArrays together into one while ensuring to unintended reallocations happens to avoid data remnance. Preallocate the correct size with ByteArray::with_capacity then unintended reallocations might happen)

§Capacity allocation caveat

this function adjusts the inner bytes capacity according to the sum of the lengths of the actual data of both ByteArrays, if you want to preserve the capacity to be the sum of the total capacities of both arrays; then use [ByteArray::with_extend_preserve_cap]

§Errors

This function fails if a reallocation happens with crate::errors::ByteArraySecurityError::DataRemnanceRisk

§Example
use byte_array_ops::ByteArray;

let arr1 = ByteArray::from_hex("dead")?;
let arr2 = ByteArray::from_hex("beef")?;
let result = arr1.try_extend(arr2)?;

assert_eq!(result.as_bytes(), [0xde, 0xad, 0xbe, 0xef]);
Source

pub fn try_extend_with_preserve_cap( self, other: ByteArray, ) -> Result<Self, ByteArrayError>

Same as ByteArray::try_extend but instead of reserving actual lengths, this reserves the sum of capacities of both bytearrays

§Warning

For Bytearrays with very large capacities but whose actual length is very small this tends to be very inefficient and might allocate too much memory on constrained environments. For these cases use ByteArray::try_extend chained , this might be safer at the cost of more secure reallocations

§Example
use byte_array_ops::ByteArray;

let arr1 = ByteArray::with_capacity(100);
let arr2 = ByteArray::from_hex("ff")?;
let result = arr1.try_extend_with_preserve_cap(arr2)?;

// Result has the data from arr2
assert_eq!(result.as_bytes(), [0xff]);
assert_eq!(result.len(), 1);
Source§

impl ByteArray

Source

pub fn iter(&self) -> ByteArrayIter<'_>

Returns an iterator over the bytes.

§Example
use byte_array_ops::ByteArray;

let arr: ByteArray = "0xdeadbeef".parse().unwrap();
let mut iter = arr.iter();
assert_eq!(iter.next(), Some(&0xde));
assert_eq!(iter.next(),Some(&0xad));
assert_eq!(iter.next(),Some(&0xbe));
assert_eq!(iter.next(),Some(&0xef));
assert_eq!(iter.next(),None);
Source

pub fn iter_mut(&mut self) -> ByteArrayIterMut<'_>

Returns an iterator that allows modifying each byte.

§Example
use byte_array_ops::ByteArray;

let mut arr: ByteArray = "0xff00ff".parse().unwrap();
let mut iter_mut = arr.iter_mut();
iter_mut.next();
let mut byte = iter_mut.next().unwrap();
*byte = 0xee;
assert_eq!(arr.as_bytes(),[0x0ff,0xee,0xff]);
Source§

impl ByteArray

Source

pub unsafe fn as_ptr(&self) -> *const u8

raw pointer access for cases where the data is passed over an ffi interface and needs to be read

§Safety

Do NOT use only if you must. use ByteArray::as_bytes or ByteArray::as_ref as a safe alternative

This function returns the raw pointer to the inner type as is and avoids any checks it is thus marked unsafe

Source

pub unsafe fn as_mut_ptr(&mut self) -> *mut u8

raw mutable pointer access for cases where the data is passed over an ffi interface and needs to be mutated

§Safety

Do NOT use only if you must. use ByteArray::as_mut as a safe alternative

This function returns the raw pointer to the inner type as is and avoids any checks it is thus marked unsafe

Source§

impl ByteArray

Source

pub fn len(&self) -> usize

Returns the number of bytes in the array

Source

pub fn is_empty(&self) -> bool

Returns true if there are no bytes in the array

Source

pub fn get(&self, index: usize) -> Option<&u8>

Returns a reference to the byte at the given index, or None if out of bounds

Source

pub fn truncate(&mut self, len: usize)

Truncate function similar to alloc::vec::Vec::truncate but zeroizes the discarded portions before truncating to avoid leaking sensitive data. the len represents the new ByteArray length in bytes.

Trait Implementations§

Source§

impl AsMut<[u8]> for ByteArray

Source§

fn as_mut(&mut self) -> &mut [u8]

Converts this type into a mutable reference of the (usually inferred) input type.
Source§

impl AsRef<[u8]> for ByteArray

Source§

fn as_ref(&self) -> &[u8]

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl BitAnd for ByteArray

Source§

type Output = ByteArray

The resulting type after applying the & operator.
Source§

fn bitand(self, rhs: Self) -> Self::Output

Performs the & operation. Read more
Source§

impl BitAndAssign for ByteArray

Source§

fn bitand_assign(&mut self, rhs: Self)

Performs the &= operation. Read more
Source§

impl BitOr for ByteArray

Source§

type Output = ByteArray

The resulting type after applying the | operator.
Source§

fn bitor(self, rhs: Self) -> Self::Output

Performs the | operation. Read more
Source§

impl BitOrAssign for ByteArray

Source§

fn bitor_assign(&mut self, rhs: Self)

Performs the |= operation. Read more
Source§

impl BitXor for ByteArray

Source§

type Output = ByteArray

The resulting type after applying the ^ operator.
Source§

fn bitxor(self, rhs: Self) -> Self::Output

Performs the ^ operation. Read more
Source§

impl BitXorAssign for ByteArray

Source§

fn bitxor_assign(&mut self, rhs: Self)

Performs the ^= operation. Read more
Source§

impl Clone for ByteArray

Source§

fn clone(&self) -> ByteArray

Returns a duplicate 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 ByteArray

Debug implementation delegates to Display for consistent behavior

Source§

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

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

impl Default for ByteArray

Source§

fn default() -> ByteArray

Returns the “default value” for a type. Read more
Source§

impl Display for ByteArray

Source§

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

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

impl Drop for ByteArray

Source§

fn drop(&mut self)

zeroizes ByteArray before dropping it

Source§

impl From<&[u8]> for ByteArray

Source§

fn from(value: &[u8]) -> Self

converts a byte slice into our Byte array, odd word padding is not needed here as arrays are always aligned TODO document this as potentially expensive copy

Source§

impl<const N: usize> From<&[u8; N]> for ByteArray

Source§

fn from(value: &[u8; N]) -> Self

converts a byte slice into our Byte array, odd word padding is not needed here as arrays are always aligned TODO document this as potentially expensive copy

Source§

impl<const N: usize> From<[u8; N]> for ByteArray

Source§

fn from(value: [u8; N]) -> Self

Converts to this type from the input type.
Source§

impl From<Vec<u8>> for ByteArray

Source§

fn from(bytes: Vec<u8>) -> Self

Converts to this type from the input type.
Source§

impl From<u8> for ByteArray

Source§

fn from(value: u8) -> Self

Converts to this type from the input type.
Source§

impl FromStr for ByteArray

Source§

fn from_str(s: &str) -> Result<Self, Self::Err>

parses a &str as follows :

  • does it start with a format identifier with 0x, 0b, or 0o then parses in hex, binary or octal respectively (case insensitive)
    • The routines for the conversion here ignore underscore _ allowing its use as a separator for example "0b1110_0010_0110"
  • for all other cases defaults to UTF-8 as encoding and parses the slice as such

TODO add example with string slice lower than 2 chars

Source§

type Err = ByteArrayError

The associated error which can be returned from parsing.
Source§

impl Index<Range<usize>> for ByteArray

Source§

type Output = [u8]

The returned type after indexing.
Source§

fn index(&self, range: Range<usize>) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl Index<RangeFrom<usize>> for ByteArray

Source§

type Output = [u8]

The returned type after indexing.
Source§

fn index(&self, range: RangeFrom<usize>) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl Index<RangeFull> for ByteArray

Source§

type Output = [u8]

The returned type after indexing.
Source§

fn index(&self, range: RangeFull) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl Index<RangeInclusive<usize>> for ByteArray

Source§

type Output = [u8]

The returned type after indexing.
Source§

fn index(&self, range: RangeInclusive<usize>) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl Index<RangeTo<usize>> for ByteArray

Source§

type Output = [u8]

The returned type after indexing.
Source§

fn index(&self, range: RangeTo<usize>) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl Index<usize> for ByteArray

Source§

fn index(&self, index: usize) -> &Self::Output

index accessor for ByteArray

§Panics

When out of bounds. Use ByteArray::get() for a checked getter that returns Option<&u8>

Source§

type Output = u8

The returned type after indexing.
Source§

impl IndexMut<Range<usize>> for ByteArray

Source§

fn index_mut(&mut self, range: Range<usize>) -> &mut Self::Output

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl IndexMut<RangeFrom<usize>> for ByteArray

Source§

fn index_mut(&mut self, range: RangeFrom<usize>) -> &mut Self::Output

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl IndexMut<RangeFull> for ByteArray

Source§

fn index_mut(&mut self, range: RangeFull) -> &mut Self::Output

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl IndexMut<RangeInclusive<usize>> for ByteArray

Source§

fn index_mut(&mut self, range: RangeInclusive<usize>) -> &mut Self::Output

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl IndexMut<RangeTo<usize>> for ByteArray

Source§

fn index_mut(&mut self, range: RangeTo<usize>) -> &mut Self::Output

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl IndexMut<usize> for ByteArray

Source§

fn index_mut(&mut self, index: usize) -> &mut Self::Output

Mutable index accessor for ByteArray

§Panics

When out of bounds. Use ByteArray::get() for a checked getter that returns Option<&u8>

Source§

impl<'a> IntoIterator for &'a ByteArray

Source§

type Item = &'a u8

The type of the elements being iterated over.
Source§

type IntoIter = ByteArrayIter<'a>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a> IntoIterator for &'a mut ByteArray

Source§

type Item = &'a mut u8

The type of the elements being iterated over.
Source§

type IntoIter = ByteArrayIterMut<'a>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl Not for ByteArray

Source§

type Output = ByteArray

The resulting type after applying the ! operator.
Source§

fn not(self) -> Self::Output

Performs the unary ! operation. Read more
Source§

impl PartialEq for ByteArray

Source§

fn eq(&self, other: &Self) -> 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 Eq for ByteArray

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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. 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.