tokio_uring/buf/io_buf.rs
1/// An `io-uring` compatible buffer.
2///
3/// The `IoBuf` trait is implemented by buffer types that can be used with
4/// io-uring operations. Users will not need to use this trait directly.
5/// The [`BoundedBuf`] trait provides some useful methods including `slice`.
6///
7/// # Safety
8///
9/// Buffers passed to `io-uring` operations must reference a stable memory
10/// region. While the runtime holds ownership to a buffer, the pointer returned
11/// by `stable_ptr` must remain valid even if the `IoBuf` value is moved.
12///
13/// [`BoundedBuf`]: crate::buf::BoundedBuf
14pub unsafe trait IoBuf: Unpin + 'static {
15 /// Returns a raw pointer to the vector’s buffer.
16 ///
17 /// This method is to be used by the `tokio-uring` runtime and it is not
18 /// expected for users to call it directly.
19 ///
20 /// The implementation must ensure that, while the `tokio-uring` runtime
21 /// owns the value, the pointer returned by `stable_ptr` **does not**
22 /// change.
23 fn stable_ptr(&self) -> *const u8;
24
25 /// Number of initialized bytes.
26 ///
27 /// This method is to be used by the `tokio-uring` runtime and it is not
28 /// expected for users to call it directly.
29 ///
30 /// For `Vec`, this is identical to `len()`.
31 fn bytes_init(&self) -> usize;
32
33 /// Total size of the buffer, including uninitialized memory, if any.
34 ///
35 /// This method is to be used by the `tokio-uring` runtime and it is not
36 /// expected for users to call it directly.
37 ///
38 /// For `Vec`, this is identical to `capacity()`.
39 fn bytes_total(&self) -> usize;
40}
41
42unsafe impl IoBuf for Vec<u8> {
43 fn stable_ptr(&self) -> *const u8 {
44 self.as_ptr()
45 }
46
47 fn bytes_init(&self) -> usize {
48 self.len()
49 }
50
51 fn bytes_total(&self) -> usize {
52 self.capacity()
53 }
54}
55
56unsafe impl IoBuf for &'static [u8] {
57 fn stable_ptr(&self) -> *const u8 {
58 self.as_ptr()
59 }
60
61 fn bytes_init(&self) -> usize {
62 <[u8]>::len(self)
63 }
64
65 fn bytes_total(&self) -> usize {
66 self.bytes_init()
67 }
68}
69
70unsafe impl IoBuf for &'static str {
71 fn stable_ptr(&self) -> *const u8 {
72 self.as_ptr()
73 }
74
75 fn bytes_init(&self) -> usize {
76 <str>::len(self)
77 }
78
79 fn bytes_total(&self) -> usize {
80 self.bytes_init()
81 }
82}
83
84#[cfg(feature = "bytes")]
85unsafe impl IoBuf for bytes::Bytes {
86 fn stable_ptr(&self) -> *const u8 {
87 self.as_ptr()
88 }
89
90 fn bytes_init(&self) -> usize {
91 self.len()
92 }
93
94 fn bytes_total(&self) -> usize {
95 self.len()
96 }
97}
98
99#[cfg(feature = "bytes")]
100unsafe impl IoBuf for bytes::BytesMut {
101 fn stable_ptr(&self) -> *const u8 {
102 self.as_ptr()
103 }
104
105 fn bytes_init(&self) -> usize {
106 self.len()
107 }
108
109 fn bytes_total(&self) -> usize {
110 self.capacity()
111 }
112}