commonware_utils/
stable_buf_mut.rs

1//! # Acknowledgements
2//!
3//! This code is inspired by [tokio-uring](https://github.com/tokio-rs/tokio-uring>) at commit 7761222.
4
5use crate::stable_buf::StableBuf;
6
7/// A mutable buffer with a stable memory address.
8/// # Safety
9/// The implementor must guarantee that the pointer remains valid
10/// and unchanged while the buffer is being used.
11pub unsafe trait StableBufMut: StableBuf {
12    /// Returns a raw pointer to this buffer.
13    fn stable_mut_ptr(&mut self) -> *mut u8;
14
15    /// Copies the given byte slice into this buffer.
16    /// `src` must not overlap with this buffer.
17    /// Panics if `src` exceeds this buffer's length.
18    fn put_slice(&mut self, src: &[u8]) {
19        let dst = self.stable_mut_ptr();
20        unsafe {
21            std::ptr::copy_nonoverlapping(src.as_ptr(), dst, src.len());
22        }
23    }
24
25    /// Returns the buffer as a mutable slice.
26    fn deref_mut(&mut self) -> &mut [u8] {
27        unsafe { std::slice::from_raw_parts_mut(self.stable_mut_ptr(), self.len()) }
28    }
29}
30
31unsafe impl StableBufMut for Vec<u8> {
32    fn stable_mut_ptr(&mut self) -> *mut u8 {
33        self.as_mut_ptr()
34    }
35}
36
37unsafe impl StableBufMut for bytes::BytesMut {
38    fn stable_mut_ptr(&mut self) -> *mut u8 {
39        self.as_mut_ptr()
40    }
41}