kvarn_tokio_uring/buf/io_buf_mut.rs
1use crate::buf::IoBuf;
2
3/// A mutable`io-uring` compatible buffer.
4///
5/// The `IoBufMut` trait is implemented by buffer types that can be used with
6/// io-uring operations. Users will not need to use this trait directly.
7///
8/// # Safety
9///
10/// Buffers passed to `io-uring` operations must reference a stable memory
11/// region. While the runtime holds ownership to a buffer, the pointer returned
12/// by `stable_mut_ptr` must remain valid even if the `IoBufMut` value is moved.
13pub unsafe trait IoBufMut: IoBuf {
14 /// Returns a raw mutable pointer to the vector’s buffer.
15 ///
16 /// This method is to be used by the `tokio-uring` runtime and it is not
17 /// expected for users to call it directly.
18 ///
19 /// The implementation must ensure that, while the `tokio-uring` runtime
20 /// owns the value, the pointer returned by `stable_mut_ptr` **does not**
21 /// change.
22 fn stable_mut_ptr(&mut self) -> *mut u8;
23
24 /// Updates the number of initialized bytes.
25 ///
26 /// If the specified `pos` is greater than the value returned by
27 /// [`IoBuf::bytes_init`], it becomes the new water mark as returned by
28 /// `IoBuf::bytes_init`.
29 ///
30 /// # Safety
31 ///
32 /// The caller must ensure that all bytes starting at `stable_mut_ptr()` up
33 /// to `pos` are initialized and owned by the buffer.
34 unsafe fn set_init(&mut self, pos: usize);
35}
36
37unsafe impl IoBufMut for Vec<u8> {
38 fn stable_mut_ptr(&mut self) -> *mut u8 {
39 self.as_mut_ptr()
40 }
41
42 unsafe fn set_init(&mut self, init_len: usize) {
43 if self.len() < init_len {
44 self.set_len(init_len);
45 }
46 }
47}
48
49#[cfg(feature = "bytes")]
50unsafe impl IoBufMut for bytes::BytesMut {
51 fn stable_mut_ptr(&mut self) -> *mut u8 {
52 self.as_mut_ptr()
53 }
54
55 unsafe fn set_init(&mut self, init_len: usize) {
56 if self.len() < init_len {
57 self.set_len(init_len);
58 }
59 }
60}