Skip to main content

Bytes

Struct Bytes 

Source
pub struct Bytes<const SIZE: usize>(pub [u8; SIZE]);

Tuple Fields§

§0: [u8; SIZE]

Implementations§

Source§

impl<const SIZE: usize> Bytes<SIZE>

Source

pub const fn new() -> Self

Creates a new Bytes instance filled with zeros.

This is a const function, allowing it to be used in const contexts and static variable declarations.

§Returns

A Bytes instance with all bytes set to 0.

§Examples
use osal_rs::utils::Bytes;
 
const BUFFER: Bytes<64> = Bytes::new();
 
let runtime_buffer = Bytes::<32>::new();
assert_eq!(runtime_buffer[0], 0);
Source

pub fn new_by_str(str: &str) -> Self

Creates a new Bytes instance from a string slice.

Copies the bytes from the input string into the fixed-size array. If the string is shorter than SIZE, the remaining bytes are zero-filled. If the string is longer, it is truncated to fit.

§Parameters
  • str - The source string to convert
§Returns

A Bytes instance containing the string data.

§Examples
use osal_rs::utils::Bytes;

let short = Bytes::<16>::new_by_str("Hi");
// Internal array: [b'H', b'i', 0, 0, 0, ...]

let exact = Bytes::<5>::new_by_str("Hello");
// Internal array: [b'H', b'e', b'l', b'l', b'o']

let long = Bytes::<3>::new_by_str("Hello");
// Internal array: [b'H', b'e', b'l'] (truncated)
Source

pub fn new_by_ptr(str: *const c_char) -> Self

Creates a new Bytes instance from a C string pointer.

Safely converts a null-terminated C string pointer into a Bytes instance. If the pointer is null, returns a zero-initialized Bytes. The function copies bytes from the C string into the fixed-size array, truncating if the source is longer than SIZE.

§Parameters
  • str - A pointer to a null-terminated C string (*const c_char)
§Safety

While this function is not marked unsafe, it internally uses unsafe code to dereference the pointer. The caller must ensure that:

  • If not null, the pointer points to a valid null-terminated C string
  • The memory the pointer references remains valid for the duration of the call
§Returns

A Bytes instance containing the C string data, or zero-initialized if the pointer is null.

§Examples
use osal_rs::utils::Bytes;
use core::ffi::c_char;
use alloc::ffi::CString;

// From a CString
let c_string = CString::new("Hello").unwrap();
let bytes = Bytes::<16>::new_by_ptr(c_string.as_ptr());

// From a null pointer
let null_bytes = Bytes::<16>::new_by_ptr(core::ptr::null());
// Returns zero-initialized Bytes

// Truncation example
let long_string = CString::new("This is a very long string").unwrap();
let short_bytes = Bytes::<8>::new_by_ptr(long_string.as_ptr());
// Only first 8 bytes are copied
Source

pub fn new_by_as_sync_str(str: &impl ToString) -> Self

Creates a new Bytes instance from any type implementing ToString.

This is a convenience wrapper around new_by_str that first converts the input to a string.

§Parameters
  • str - Any value that implements ToString
§Returns

A Bytes instance containing the string representation of the input.

§Examples
use osal_rs::utils::Bytes;

// From integer
let num_bytes = Bytes::<8>::new_by_string(&42);

// From String
let string = String::from("Task");
let str_bytes = Bytes::<16>::new_by_string(&string);

// From custom type with ToString
#[derive(Debug)]
struct TaskId(u32);
impl ToString for TaskId {
    fn to_string(&self) -> String {
        format!("Task-{}", self.0)
    }
}
let task_bytes = Bytes::<16>::new_by_string(&TaskId(5));
Source

pub fn new_by_bytes(bytes: &[u8]) -> Self

Source

pub fn fill_str(&mut self, dest: &mut str) -> Result<()>

Fills a mutable string slice with the contents of the byte array.

Attempts to convert the internal byte array to a UTF-8 string and copies it into the destination string slice. Only copies up to the minimum of the source and destination lengths.

§Parameters
  • dest - The destination string slice to fill
§Returns

Ok(()) if the operation succeeds, or Err(Error::StringConversionError) if the byte array cannot be converted to a valid UTF-8 string.

§Examples
use osal_rs::utils::Bytes;
 
let bytes = Bytes::<16>::new_by_str("Hello World");
 
let mut output = String::from("                "); // 16 spaces
bytes.fill_str(unsafe { output.as_mut_str() });
 
assert_eq!(&output[..11], "Hello World");
Source

pub fn as_c_str(&self) -> &CStr

Converts the byte array to a C string reference.

Creates a CStr reference from the internal byte array, treating it as a null-terminated C string. This is useful for passing strings to C FFI functions that expect *const c_char or &CStr.

§Safety

This method is unsafe because it assumes:

  • The byte array contains valid UTF-8 data
  • The byte array is null-terminated
  • There are no interior null bytes before the terminating null

Violating these assumptions may lead to undefined behavior.

§Returns

A reference to a CStr with lifetime tied to self.

§Examples
use osal_rs::utils::Bytes;
 
let bytes = Bytes::<16>::new_by_str("Hello");
let c_str = bytes.as_c_str();
 
extern "C" {
    fn print_string(s: *const core::ffi::c_char);
}
 
unsafe {
    print_string(c_str.as_ptr());
}
Source

pub fn as_cstring(&self) -> CString

Converts the byte array to an owned C string.

Creates a new CString by copying the contents of the internal byte array. Unlike as_c_str, this method allocates heap memory and returns an owned string that can outlive the original Bytes instance.

§Safety

This method uses from_vec_unchecked which assumes the byte array does not contain any interior null bytes. If this assumption is violated, the resulting CString will be invalid.

§Returns

An owned CString containing a copy of the byte array data.

§Memory Allocation

This method allocates on the heap. In memory-constrained embedded systems, prefer as_c_str when possible.

§Examples
use osal_rs::utils::Bytes;
 
fn process_name(bytes: &Bytes<16>) -> alloc::ffi::CString {
    // Create an owned copy that can be returned
    bytes.as_cstring()
}
 
let name = Bytes::<16>::new_by_str("Task");
let owned = process_name(&name);
// 'name' can be dropped, 'owned' still valid
Source

pub fn append_str(&mut self, str: &str)

Appends a string slice to the existing content in the Bytes buffer.

This method finds the current end of the content (first null byte) and appends the provided string starting from that position. If the buffer is already full or if the appended content would exceed the buffer size, the content is truncated to fit within the SIZE limit.

§Parameters
  • str - The string slice to append
§Examples
use osal_rs::utils::Bytes;

let mut bytes = Bytes::<16>::new_by_str("Hello");
bytes.append_str(" World");
assert_eq!(bytes.as_str(), "Hello World");

// Truncation when exceeding buffer size
let mut small_bytes = Bytes::<8>::new_by_str("Hi");
small_bytes.append_str(" there friend");
assert_eq!(small_bytes.as_str(), "Hi ther");
Source

pub fn append_as_sync_str(&mut self, c_str: &impl AsSyncStr)

Appends content from any type implementing AsSyncStr to the buffer.

This method accepts any type that implements the AsSyncStr trait, converts it to a string slice, and appends it to the existing content. If the buffer is already full or if the appended content would exceed the buffer size, the content is truncated to fit within the SIZE limit.

§Parameters
  • c_str - A reference to any type implementing AsSyncStr
§Examples
use osal_rs::utils::Bytes;

let mut bytes = Bytes::<16>::new_by_str("Hello");
let other_bytes = Bytes::<8>::new_by_str(" World");
bytes.append_as_sync_str(&other_bytes);
assert_eq!(bytes.as_str(), "Hello World");
Source

pub fn append_bytes(&mut self, bytes: &[u8])

Appends raw bytes to the existing content in the Bytes buffer.

This method finds the current end of the content (first null byte) and appends the provided byte slice starting from that position. If the buffer is already full or if the appended content would exceed the buffer size, the content is truncated to fit within the SIZE limit.

§Parameters
  • bytes - The byte slice to append
§Examples
use osal_rs::utils::Bytes;

let mut bytes = Bytes::<16>::new_by_str("Hello");
bytes.append_bytes(b" World");
assert_eq!(bytes.as_str(), "Hello World");

// Appending arbitrary bytes
let mut data = Bytes::<16>::new_by_str("Data: ");
data.append_bytes(&[0x41, 0x42, 0x43]);
assert_eq!(data.as_str(), "Data: ABC");
Source

pub fn append<const OHTER_SIZE: usize>(&mut self, other: &Bytes<OHTER_SIZE>)

Appends the content of another Bytes instance to this buffer.

This method allows appending content from a Bytes instance of a different size (specified by the generic parameter OHTER_SIZE). The method finds the current end of the content (first null byte) and appends the content from the other Bytes instance. If the buffer is already full or if the appended content would exceed the buffer size, the content is truncated to fit within the SIZE limit.

§Type Parameters
  • OHTER_SIZE - The size of the source Bytes buffer (can be different from SIZE)
§Parameters
  • other - A reference to the Bytes instance to append
§Examples
use osal_rs::utils::Bytes;

let mut bytes = Bytes::<16>::new_by_str("Hello");
let other = Bytes::<8>::new_by_str(" World");
bytes.append(&other);
assert_eq!(bytes.as_str(), "Hello World");

// Appending from a larger buffer
let mut small = Bytes::<8>::new_by_str("Hi");
let large = Bytes::<32>::new_by_str(" there friend");
small.append(&large);
assert_eq!(small.as_str(), "Hi ther");

Trait Implementations§

Source§

impl<const SIZE: usize> AsSyncStr for Bytes<SIZE>

Source§

fn as_str(&self) -> &str

Returns a string slice reference.

This method provides access to the underlying string data in a way that is safe to use across thread boundaries.

§Returns

A reference to a string slice with lifetime tied to self.

Source§

impl<const SIZE: usize> Clone for Bytes<SIZE>

Source§

fn clone(&self) -> Bytes<SIZE>

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<const SIZE: usize> Debug for Bytes<SIZE>

Source§

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

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

impl<const SIZE: usize> Deref for Bytes<SIZE>

Source§

fn deref(&self) -> &Self::Target

Dereferences to the underlying byte array.

This allows Bytes to be used anywhere a [u8; SIZE] reference is expected.

§Examples
use osal_rs::utils::Bytes;
 
let bytes = Bytes::<8>::new_by_str("test");
assert_eq!(bytes[0], b't');
Source§

type Target = [u8; SIZE]

The resulting type after dereferencing.
Source§

impl<const SIZE: usize> DerefMut for Bytes<SIZE>

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Provides mutable access to the underlying byte array.

This allows Bytes to be mutably dereferenced, enabling direct modification of the internal byte array through the DerefMut trait.

§Examples
use osal_rs::utils::Bytes;
 
let mut bytes = Bytes::<8>::new();
bytes[0] = b'H';
bytes[1] = b'i';
assert_eq!(bytes[0], b'H');
Source§

impl<const SIZE: usize> Deserialize for Bytes<SIZE>

Available on non-crate feature serde only.

Deserialization implementation for Bytes<SIZE> when the serde feature is disabled.

This implementation provides basic deserialization by copying bytes from a slice into a fixed-size array. If the source slice is shorter than SIZE, the remaining bytes are zero-filled. If longer, it’s truncated to fit.

Source§

fn from_bytes(bytes: &[u8]) -> Result<Self>

Creates a Bytes instance from a byte slice.

§Parameters
  • bytes - The source byte slice to deserialize from
§Returns
  • Ok(Bytes<SIZE>) - A new Bytes instance with data copied from the slice
§Examples
use osal_rs::utils::Bytes;
use osal_rs::os::Deserialize;
 
let data = b"Hello";
let bytes = Bytes::<16>::from_bytes(data).unwrap();
// Result: [b'H', b'e', b'l', b'l', b'o', 0, 0, 0, ...]
Source§

impl<const SIZE: usize> Display for Bytes<SIZE>

Source§

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

Formats the byte array as a C-style null-terminated string.

This implementation treats the byte array as a C string and converts it to a Rust string for display. If the conversion fails, it displays “Conversion error”.

§Safety

This method assumes the byte array contains valid UTF-8 data and is null-terminated. Invalid data may result in the error message being displayed.

§Examples
use osal_rs::utils::Bytes;
 
let bytes = Bytes::<16>::new_by_str("Hello");
println!("{}", bytes); // Prints "Hello"
Source§

impl<const SIZE: usize> FromStr for Bytes<SIZE>

Source§

type Err = Error

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

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

Parses a string s to return a value of this type. Read more
Source§

impl<const SIZE: usize> Hash for Bytes<SIZE>

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<const SIZE: usize> Ord for Bytes<SIZE>

Source§

fn cmp(&self, other: &Bytes<SIZE>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<const SIZE: usize> PartialEq for Bytes<SIZE>

Source§

fn eq(&self, other: &Bytes<SIZE>) -> 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<const SIZE: usize> PartialOrd for Bytes<SIZE>

Source§

fn partial_cmp(&self, other: &Bytes<SIZE>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

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

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

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

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

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

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<const SIZE: usize> Serialize for Bytes<SIZE>

Available on non-crate feature serde only.

Serialization implementation for Bytes<SIZE> when the serde feature is disabled.

This implementation provides basic serialization by directly returning a reference to the underlying byte array. It’s used when the library is compiled without the serde feature, providing a lightweight alternative serialization mechanism.

Source§

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

Converts the Bytes instance to a byte slice.

§Returns

A reference to the internal byte array.

Source§

impl<const SIZE: usize> Copy for Bytes<SIZE>

Source§

impl<const SIZE: usize> Eq for Bytes<SIZE>

Source§

impl<const SIZE: usize> StructuralPartialEq for Bytes<SIZE>

Auto Trait Implementations§

§

impl<const SIZE: usize> Freeze for Bytes<SIZE>

§

impl<const SIZE: usize> RefUnwindSafe for Bytes<SIZE>

§

impl<const SIZE: usize> Send for Bytes<SIZE>

§

impl<const SIZE: usize> Sync for Bytes<SIZE>

§

impl<const SIZE: usize> Unpin for Bytes<SIZE>

§

impl<const SIZE: usize> UnwindSafe for Bytes<SIZE>

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<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
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.