commonware_utils/
stable_buf.rs

1//! # Acknowledgements
2//!
3//! This code is inspired by [tokio-uring](https://github.com/tokio-rs/tokio-uring>) at commit 7761222.
4
5/// A buffer with a stable memory address.
6/// # Safety
7/// The implementor must guarantee that the pointer remains valid
8/// and unchanged while the buffer is being used.
9#[allow(clippy::len_without_is_empty)]
10pub unsafe trait StableBuf: Unpin + Send + 'static {
11    /// Returns a raw pointer to this buffer.
12    fn stable_ptr(&self) -> *const u8;
13
14    /// Length of the buffer.
15    fn len(&self) -> usize;
16
17    /// Returns the buffer as a slice.
18    fn as_ref(&self) -> &[u8] {
19        unsafe { std::slice::from_raw_parts(self.stable_ptr(), self.len()) }
20    }
21}
22
23unsafe impl StableBuf for Vec<u8> {
24    fn stable_ptr(&self) -> *const u8 {
25        self.as_ptr()
26    }
27
28    fn len(&self) -> usize {
29        self.len()
30    }
31}
32
33unsafe impl StableBuf for &'static [u8] {
34    fn stable_ptr(&self) -> *const u8 {
35        self.as_ptr()
36    }
37
38    fn len(&self) -> usize {
39        <[u8]>::len(self)
40    }
41}
42
43unsafe impl StableBuf for &'static str {
44    fn stable_ptr(&self) -> *const u8 {
45        self.as_ptr()
46    }
47
48    fn len(&self) -> usize {
49        <str>::len(self)
50    }
51}
52
53unsafe impl StableBuf for bytes::Bytes {
54    fn stable_ptr(&self) -> *const u8 {
55        self.as_ptr()
56    }
57
58    fn len(&self) -> usize {
59        self.len()
60    }
61}
62
63unsafe impl StableBuf for bytes::BytesMut {
64    fn stable_ptr(&self) -> *const u8 {
65        self.as_ptr()
66    }
67
68    fn len(&self) -> usize {
69        self.len()
70    }
71}