On 2/11/25 22:43, Kevin Wolf wrote:
+/// Implementing `SizedIoBuffer` provides an implementation for [`IoBuffer`] 
without having to
+/// implement any functions manually.
+///
+/// # Safety
+///
+/// Types implementing `SizedIoBuffer` guarantee that the whole object can be 
accessed as an I/O
+/// buffer that is safe to contain any byte patterns.
+pub unsafe trait SizedIoBuffer: Sized {

This is similar to the ByteValued trait in rust-vmm. Can you name it the same so that we can later consider replacing it?

+    fn from_byte_slice(buf: &[u8]) -> Option<&Self> {
+        if buf.len() < std::mem::size_of::<Self>() {
+            return None;
+        }
+
+        let ptr = buf.as_ptr() as *const Self;
+
+        // TODO Use ptr.is_aligned() when MSRV is updated to at least 1.79.0
+        if (ptr as usize) % std::mem::align_of::<Self>() != 0 {
+            return None;
+        }
+
+        // SAFETY: This function checked that the byte slice is large enough 
and aligned.
+        // Implementing SizedIoBuffer promises that any byte pattern is valid 
for the type.
+        Some(unsafe { &*ptr })

If you want, the function can be written also

    // SAFETY: implementing SizedIoBuffer promises that any byte pattern
    // is valid for the type
    match unsafe { buf.align_to::<Self>() } {
        ([], mid, _) => mid.get(0),
        _ => None
    }

(trick stolen from rust-vmm, in fact).

Paolo


Reply via email to