pub struct Bytes<const SIZE: usize>(pub [u8; SIZE]);Expand description
Fixed-size byte array wrapper with string conversion utilities.
Bytes is a generic wrapper around a fixed-size byte array that provides
convenient methods for converting between strings and byte arrays. It’s
particularly useful for interfacing with C APIs that expect fixed-size
character buffers, or for storing strings in embedded systems with
constrained memory.
§Type Parameters
SIZE- The size of the internal byte array (default: 0)
§Examples
use osal_rs::utils::Bytes;
// Create an empty 32-byte buffer
let mut buffer = Bytes::<32>::new();
// Create a buffer from a string
let name = Bytes::<16>::new_by_str("TaskName");
println!("{}", name); // Prints "TaskName"
// Create from any type that implements ToString
let number = 42;
let num_bytes = Bytes::<8>::new_by_string(&number);Tuple Fields§
§0: [u8; SIZE]Implementations§
Source§impl<const SIZE: usize> Bytes<SIZE>
impl<const SIZE: usize> Bytes<SIZE>
Sourcepub const fn new() -> Self
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);Sourcepub fn from_str(str: &str) -> Self
pub fn from_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)Sourcepub fn from_char_ptr(ptr: *const c_char) -> Self
pub fn from_char_ptr(ptr: *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
ptr- 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 copiedSourcepub fn from_uchar_ptr(ptr: *const c_uchar) -> Self
pub fn from_uchar_ptr(ptr: *const c_uchar) -> Self
Creates a new Bytes instance from a C unsigned char pointer.
Safely converts a pointer to an array of unsigned chars into a Bytes instance. If the pointer is null, returns a zero-initialized Bytes. The function copies bytes from the source pointer into the fixed-size array, truncating if the source is longer than SIZE.
§Parameters
ptr- A pointer to an array of unsigned chars (*const c_uchar)
§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 array of unsigned chars with at least
SIZEbytes - The memory the pointer references remains valid for the duration of the call
§Returns
A Bytes instance containing the data from the source pointer, or zero-initialized if the pointer is null.
§Examples
use osal_rs::utils::Bytes;
use core::ffi::c_uchar;
use alloc::ffi::CString;
// From a C unsigned char pointer
let data = [b'H', b'e', b'l', b'l', b'o', 0];
let bytes = Bytes::<16>::from_uchar_ptr(data.as_ptr());
// From a null pointer
let null_bytes = Bytes::<16>::from_uchar_ptr(core::ptr::null());
// Returns zero-initialized Bytes
// Truncation example
let long_data = [b'T', b'h', b'i', b's', b' ', b'i', b's', b' ', b'v', b'e', b'r', b'y', b' ', b'l', b'o', b'n', b'g', 0];
let short_bytes = Bytes::<8>::from_uchar_ptr(long_data.as_ptr());
// Only first 8 bytes are copiedSourcepub fn from_as_sync_str(str: &impl ToString) -> Self
pub fn from_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 implementsToString
§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));Sourcepub fn from_bytes(bytes: &[u8]) -> Self
pub fn from_bytes(bytes: &[u8]) -> Self
Creates a new Bytes instance from a byte slice.
This function copies bytes from the input slice into the fixed-size array. If the slice is shorter than SIZE, the remaining bytes are zero-filled. If the slice is longer, it is truncated to fit.
§Parameters
bytes- The source byte slice to convert
§Returns
A Bytes instance containing the data from the byte slice.
§Examples
use osal_rs::utils::Bytes;
let data = b"Hello";
let bytes = Bytes::<16>::from_bytes(data);
// Result: [b'H', b'e', b'l', b'l', b'o', 0, 0, 0, ...]Sourcepub fn fill_str(&mut self, dest: &mut str) -> Result<()>
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");Sourcepub fn from_cstr(str: *const c_char) -> Self
pub fn from_cstr(str: *const c_char) -> Self
Creates a new Bytes instance from a C string pointer.
This is a convenience wrapper around new_by_ptr that directly converts a C string pointer to a Bytes instance.
If the pointer is null, it 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
This method 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
-
The byte array can be safely interpreted as UTF-8 if the conversion is expected to succeed. If the byte array contains invalid UTF-8, the resulting
Bytesinstance will contain the raw bytes, and theDisplayimplementation will show “Conversion error” when attempting to display it as a string.
§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>::from_cstr(c_string.as_ptr());
// From a null pointer
let null_bytes = Bytes::<16>::from_cstr(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>::from_cstr(long_string.as_ptr());
// Only first 8 bytes are copiedSourcepub fn as_cstr(&self) -> &CStr
pub fn as_cstr(&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 assumes the byte array is already null-terminated. All
constructors (new(), from_str(), from_char_ptr(), etc.) guarantee
this property by initializing with [0u8; SIZE].
However, if you’ve manually modified the array via DerefMut,
you must ensure the last byte remains 0.
§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_cstr();
extern "C" {
fn print_string(s: *const core::ffi::c_char);
}
unsafe {
print_string(c_str.as_ptr());
}Sourcepub fn as_cstr_mut(&mut self) -> &CStr
pub fn as_cstr_mut(&mut self) -> &CStr
Converts the byte array to a C string reference, ensuring null-termination.
This is a safer version of as_cstr() that explicitly guarantees
null-termination by modifying the last byte. Use this if you’ve
manually modified the array and want to ensure it’s null-terminated.
§Returns
A reference to a CStr with lifetime tied to self.
§Examples
use osal_rs::utils::Bytes;
let mut bytes = Bytes::<16>::new();
bytes[0] = b'H';
bytes[1] = b'i';
// After manual modification, ensure null-termination
let c_str = bytes.as_cstr_mut();Sourcepub fn append_str(&mut self, str: &str)
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");Sourcepub fn append_as_sync_str(&mut self, c_str: &impl AsSyncStr)
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 implementingAsSyncStr
§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");Sourcepub fn append_bytes(&mut self, bytes: &[u8])
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");Sourcepub fn append<const OTHER_SIZE: usize>(&mut self, other: &Bytes<OTHER_SIZE>)
pub fn append<const OTHER_SIZE: usize>(&mut self, other: &Bytes<OTHER_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
OTHER_SIZE- The size of the sourceBytesbuffer (can be different fromSIZE)
§Parameters
other- A reference to theBytesinstance 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");Sourcepub fn clear(&mut self)
pub fn clear(&mut self)
Clears all content from the buffer, filling it with zeros.
This method resets the entire internal byte array to zeros, effectively clearing any stored data. After calling this method, the buffer will be empty and ready for new content.
§Examples
use osal_rs::utils::Bytes;
let mut bytes = Bytes::<16>::new_by_str("Hello");
assert!(!bytes.is_empty());
bytes.clear();
assert!(bytes.is_empty());
assert_eq!(bytes.len(), 0);Sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the length of the content in the buffer.
The length is determined by finding the position of the first null byte (0).
If no null byte is found, returns SIZE, indicating the buffer is completely
filled with non-zero data.
§Returns
The number of bytes before the first null terminator, or SIZE if the
buffer is completely filled.
§Examples
use osal_rs::utils::Bytes;
let bytes = Bytes::<16>::new_by_str("Hello");
assert_eq!(bytes.len(), 5);
let empty = Bytes::<16>::new();
assert_eq!(empty.len(), 0);
// Buffer completely filled (no null terminator)
let mut full = Bytes::<4>::new();
full[0] = b'A';
full[1] = b'B';
full[2] = b'C';
full[3] = b'D';
assert_eq!(full.len(), 4);Sourcepub fn as_raw_bytes(&self) -> &[u8]
pub fn as_raw_bytes(&self) -> &[u8]
Returns a byte slice of the content in the buffer.
This method returns a slice of the internal byte array up to the first null byte (0). If no null byte is found, it returns a slice of the entire array. This allows you to access the valid content stored in the buffer without including any trailing zeros.
§Returns
A byte slice containing the content of the buffer up to the first null terminator.
§Examples
use osal_rs::utils::Bytes;
let bytes = Bytes::<16>::new_by_str("Hello");
assert_eq!(bytes.as_raw_bytes(), b"Hello");
let empty = Bytes::<16>::new();
assert_eq!(empty.as_raw_bytes(), b"");
let full = Bytes::<4>::new_by_str("ABCD");
assert_eq!(full.as_raw_bytes(), b"ABCD");Sourcepub const fn size(&self) -> usize
pub const fn size(&self) -> usize
Returns the fixed size of the buffer.
This method returns the compile-time constant SIZE, which represents the total capacity of the internal byte array. The size is determined by the generic parameter SIZE specified when creating the Bytes instance. This value is fixed and does not change during the lifetime of the instance.
§Returns
The fixed size of the buffer in bytes (SIZE).
§Examples
use osal_rs::utils::Bytes;
let bytes = Bytes::<32>::new();
assert_eq!(bytes.size(), 32);
let other = Bytes::<128>::new_by_str("Hello");
assert_eq!(other.size(), 128);Sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Checks if the buffer is empty.
A buffer is considered empty if all bytes are zero. This method searches for the first non-zero byte to determine emptiness.
§Returns
true if all bytes are zero, false otherwise.
§Examples
use osal_rs::utils::Bytes;
let empty = Bytes::<16>::new();
assert!(empty.is_empty());
let bytes = Bytes::<16>::new_by_str("Hello");
assert!(!bytes.is_empty());
let mut cleared = Bytes::<16>::new_by_str("Test");
cleared.clear();
assert!(cleared.is_empty());Sourcepub fn capacity(&self) -> usize
pub fn capacity(&self) -> usize
Returns the total capacity of the buffer.
This is the fixed size of the internal byte array, determined at compile
time by the generic SIZE parameter. The capacity never changes during
the lifetime of the Bytes instance.
§Returns
The total capacity in bytes (SIZE).
§Examples
use osal_rs::utils::Bytes;
let bytes = Bytes::<32>::new();
assert_eq!(bytes.capacity(), 32);
let other = Bytes::<128>::new_by_str("Hello");
assert_eq!(other.capacity(), 128);Sourcepub fn replace(&mut self, find: &[u8], replace: &[u8]) -> Result<()>
pub fn replace(&mut self, find: &[u8], replace: &[u8]) -> Result<()>
Replaces all occurrences of a byte pattern with another pattern.
This method searches for all occurrences of the find byte sequence within
the buffer and replaces them with the replace byte sequence. The replacement
is performed in a single pass, and the method handles cases where the replacement
is larger, smaller, or equal in size to the pattern being searched for.
§Parameters
find- The byte pattern to search forreplace- The byte pattern to replace with
§Returns
Ok(())- If all replacements were successfulErr(Error::StringConversionError)- If the replacement would exceed the buffer capacity
§Behavior
- Empty
findpatterns are ignored (returnsOk(())immediately) - Multiple occurrences are replaced in a single pass
- Content is properly shifted when replacement size differs from find size
- Null terminators and trailing bytes are correctly maintained
- Overlapping patterns are not re-matched (avoids infinite loops)
§Examples
use osal_rs::utils::Bytes;
// Same length replacement
let mut bytes = Bytes::<16>::new_by_str("Hello World");
bytes.replace(b"World", b"Rust!").unwrap();
assert_eq!(bytes.as_str(), "Hello Rust!");
// Shorter replacement
let mut bytes2 = Bytes::<16>::new_by_str("aabbcc");
bytes2.replace(b"bb", b"X").unwrap();
assert_eq!(bytes2.as_str(), "aaXcc");
// Longer replacement
let mut bytes3 = Bytes::<16>::new_by_str("Hi");
bytes3.replace(b"Hi", b"Hello").unwrap();
assert_eq!(bytes3.as_str(), "Hello");
// Multiple occurrences
let mut bytes4 = Bytes::<32>::new_by_str("foo bar foo");
bytes4.replace(b"foo", b"baz").unwrap();
assert_eq!(bytes4.as_str(), "baz bar baz");
// Buffer overflow error
let mut small = Bytes::<8>::new_by_str("Hello");
assert!(small.replace(b"Hello", b"Hello World").is_err());Sourcepub fn to_bytes(&self) -> &[u8]
pub fn to_bytes(&self) -> &[u8]
Converts the Bytes instance to a byte slice.
This method provides a convenient way to access the internal byte array as a slice, which can be useful for C FFI or other operations that require byte slices.
§Examples
use osal_rs::utils::{Bytes, ToBytes};
let bytes = Bytes::<8>::new_by_str("example");
let byte_slice = bytes.to_bytes();
assert_eq!(byte_slice, b"example\0\0");Sourcepub fn pop(&mut self) -> Option<u8>
pub fn pop(&mut self) -> Option<u8>
Pops the last byte from the buffer and returns it.
This method removes the last byte of content (before the first null terminator)
and returns it. If the buffer is empty, it returns None. After popping, the last byte is set to zero to maintain the null-terminated property.
§Returns
Some(u8)- The last byte of content if the buffer is not emptyNone- If the buffer is empty
§Examples
use osal_rs::utils::Bytes;
let mut bytes = Bytes::<16>::new_by_str(“Hello”); assert_eq!(bytes.pop(), Some(b’o’)); assert_eq!(bytes.as_str(), “Hell”);
// Pop until empty assert_eq!(bytes.pop(), Some(b’l’)); assert_eq!(bytes.pop(), Some(b’l’)); assert_eq!(bytes.pop(), Some(b’e’)); assert_eq!(bytes.pop(), Some(b’H’)); assert_eq!(bytes.pop(), None);
Sourcepub fn push(&mut self, byte: u8) -> Result<()>
pub fn push(&mut self, byte: u8) -> Result<()>
Pushes a byte to the end of the content in the buffer.
§Parameters
byte- The byte to push into the buffer
§Returns
Ok(())- If the byte was successfully pushedErr(Error::StringConversionError)- If the buffer is full
§Examples
use osal_rs::utils::Bytes;
let mut bytes = Bytes::<16>::new_by_str("Hello");
assert_eq!(bytes.push(b'!'), Ok(()));
assert_eq!(bytes.as_str(), "Hello!");Sourcepub fn pop_char(&mut self) -> Option<char>
pub fn pop_char(&mut self) -> Option<char>
Pops the last byte from the buffer and returns it as a character.
This method removes the last byte of content (before the first null terminator)
and attempts to convert it to a char. If the buffer is empty or if the byte cannot be converted to a valid char, it returns None. After popping, the last byte is set to zero to maintain the null-terminated property.
§Returns
Some(char)- The last byte of content as a character if the buffer is not empty and the byte is a valid characterNone- If the buffer is empty or if the byte cannot be converted to a valid character
§Examples
use osal_rs::utils::Bytes;
let mut bytes = Bytes::<16>::new_by_str(“Hello”); assert_eq!(bytes.pop_char(), Some(‘o’)); assert_eq!(bytes.as_str(), “Hell”);
// Pop until empty assert_eq!(bytes.pop_char(), Some(‘l’)); assert_eq!(bytes.pop_char(), Some(‘l’)); assert_eq!(bytes.pop_char(), Some(‘e’)); assert_eq!(bytes.pop_char(), Some(‘H’)); assert_eq!(bytes.pop_char(), None);
Sourcepub fn push_char(&mut self, ch: char) -> Result<()>
pub fn push_char(&mut self, ch: char) -> Result<()>
Pushes a character to the end of the content in the buffer.
This method attempts to convert the provided char to a byte and push it into the buffer. If the character is not a valid ASCII character (i.e., its code point is greater than 127), it returns an error since it cannot be represented as a single byte. If the buffer is full, it also returns an error.
§Parameters
ch- The character to push into the buffer
§Returns
Ok(())- If the character was successfully pushedErr(Error::StringConversionError)- If the character is not a valid ASCII character or if the buffer is full
§Examples
use osal_rs::utils::Bytes;
let mut bytes = Bytes::<16>::new_by_str(“Hello”); assert_eq!(bytes.push_char(‘!’), Ok(())); assert_eq!(bytes.as_str(), “Hello!”);
// Attempt to push a non-ASCII character assert!(bytes.push_char(‘é’).is_err());
Sourcepub fn is_string(&self) -> bool
pub fn is_string(&self) -> bool
Checks if the content of the buffer can be interpreted as a valid UTF-8 string.
This method attempts to convert the internal byte array to a UTF-8 string. If the conversion is successful, it returns true, indicating that the content can be treated as a valid string. If the conversion fails due to invalid UTF-8 sequences, it returns false.
§Returns
true- If the content can be interpreted as a valid UTF-8 stringfalse- If the content contains invalid UTF-8 sequences
§Examples
use osal_rs::utils::Bytes;
let valid_bytes = Bytes::<16>::new_by_str(“Hello”); assert!(valid_bytes.is_string());
let mut invalid_bytes = Bytes::<16>::new(); invalid_bytes[0] = 0xFF; // Invalid UTF-8 byte assert!(!invalid_bytes.is_string());
Trait Implementations§
Source§impl<const SIZE: usize> Default for Bytes<SIZE>
Default implementation for Bytes<SIZE>.
This provides a default value for Bytes<SIZE>, which is a zero-initialized byte array. This allows Bytes to be used in contexts that require a default value, such as when using the Default trait or when initializing variables without explicit values.
impl<const SIZE: usize> Default for Bytes<SIZE>
Default implementation for Bytes<SIZE>.
This provides a default value for Bytes<SIZE>, which is a zero-initialized byte array. This allows Bytes to be used in contexts that require a default value, such as when using the Default trait or when initializing variables without explicit values.
§Examples
use osal_rs::utils::Bytes;
let default_bytes: Bytes<16> = Default::default();
assert_eq!(default_bytes[0], 0);The default implementation initializes the internal byte array to all zeros, which is a common default state for byte buffers in embedded systems and C APIs. This ensures that any uninitialized Bytes instance will contain predictable data (zeros) rather than random memory content.
This is particularly useful when Bytes is used as a buffer for C string operations, as it ensures that the buffer starts in a known state. Additionally, it allows for easy creation of empty buffers that can be filled later without needing to manually initialize the array each time.
Overall, this default implementation enhances the usability of the Bytes type by providing a sensible default state that is commonly needed in embedded and systems programming contexts.
Source§fn default() -> Self
fn default() -> Self
Provides a default value for Bytes<SIZE>, which is a zero-initialized byte array.
This implementation allows Bytes to be used in contexts that require a default value,
such as when using the Default trait or when initializing variables without explicit values.
§Examples
use osal_rs::utils::Bytes;
let default_bytes: Bytes<16> = Default::default();
assert_eq!(default_bytes[0], 0);Source§impl<const SIZE: usize> DerefMut for Bytes<SIZE>
impl<const SIZE: usize> DerefMut for Bytes<SIZE>
Source§fn deref_mut(&mut self) -> &mut Self::Target
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.
impl<const SIZE: usize> Deserialize for Bytes<SIZE>
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>
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 newBytesinstance 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>
impl<const SIZE: usize> Display for Bytes<SIZE>
Source§fn fmt(&self, f: &mut Formatter<'_>) -> Result
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> From<&str> for Bytes<SIZE>
impl<const SIZE: usize> From<&str> for Bytes<SIZE>
Source§fn from(s: &str) -> Self
fn from(s: &str) -> Self
Creates a Bytes instance from a string slice.
This implementation allows for easy conversion from string literals or
string slices to the Bytes type, filling the internal byte array
with the string data and padding with spaces if necessary.
§Examples
use osal_rs::utils::Bytes;
let bytes: Bytes<16> = "Hello".into();
println!("{}", bytes); // Prints "Hello"Source§impl<const SIZE: usize> FromStr for Bytes<SIZE>
impl<const SIZE: usize> FromStr for Bytes<SIZE>
Source§fn from_str(s: &str) -> Result<Self, Self::Err>
fn from_str(s: &str) -> Result<Self, Self::Err>
Creates a Bytes instance from a string slice.
This implementation allows for easy conversion from string literals or
string slices to the Bytes type, filling the internal byte array
with the string data and padding with spaces if necessary.
§Examples
use osal_rs::utils::Bytes;
let bytes: Bytes<16> = “Hello”.parse().unwrap(); println!(“{}”, bytes); // Prints “Hello”
Source§impl<const SIZE: usize> Ord for Bytes<SIZE>
impl<const SIZE: usize> Ord for Bytes<SIZE>
1.21.0 · Source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
Source§impl<const SIZE: usize> PartialOrd for Bytes<SIZE>
impl<const SIZE: usize> PartialOrd for Bytes<SIZE>
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.
impl<const SIZE: usize> Serialize for Bytes<SIZE>
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.