Skip to content

Commit cdc4f52

Browse files
authored
Implement IoBuf for Rc and Arc of IoBuf types. (#239)
This allows a client to submit a buffer for writing and keep it around to submit again later or for other use.
1 parent 5784885 commit cdc4f52

File tree

1 file changed

+70
-1
lines changed

1 file changed

+70
-1
lines changed

monoio/src/buf/io_buf.rs

+70-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::ops;
1+
use std::{ops, rc::Rc, sync::Arc};
22

33
use super::Slice;
44
use crate::buf::slice::SliceMut;
@@ -174,6 +174,36 @@ unsafe impl IoBuf for bytes::BytesMut {
174174
}
175175
}
176176

177+
unsafe impl<T> IoBuf for Rc<T>
178+
where
179+
T: IoBuf,
180+
{
181+
#[inline]
182+
fn read_ptr(&self) -> *const u8 {
183+
<T as IoBuf>::read_ptr(self)
184+
}
185+
186+
#[inline]
187+
fn bytes_init(&self) -> usize {
188+
<T as IoBuf>::bytes_init(self)
189+
}
190+
}
191+
192+
unsafe impl<T> IoBuf for Arc<T>
193+
where
194+
T: IoBuf,
195+
{
196+
#[inline]
197+
fn read_ptr(&self) -> *const u8 {
198+
<T as IoBuf>::read_ptr(self)
199+
}
200+
201+
#[inline]
202+
fn bytes_init(&self) -> usize {
203+
<T as IoBuf>::bytes_init(self)
204+
}
205+
}
206+
177207
/// A mutable `io_uring` compatible buffer.
178208
///
179209
/// The `IoBufMut` trait is implemented by buffer types that can be passed to
@@ -418,6 +448,24 @@ mod tests {
418448
assert_eq!(buf.bytes_total(), 5);
419449
}
420450

451+
#[test]
452+
fn io_buf_rc_str() {
453+
let s = Rc::new("hello world");
454+
let ptr = s.as_ptr();
455+
456+
assert_eq!(s.read_ptr(), ptr);
457+
assert_eq!(s.bytes_init(), 11);
458+
}
459+
460+
#[test]
461+
fn io_buf_arc_str() {
462+
let s = Arc::new("hello world");
463+
let ptr = s.as_ptr();
464+
465+
assert_eq!(s.read_ptr(), ptr);
466+
assert_eq!(s.bytes_init(), 11);
467+
}
468+
421469
#[test]
422470
fn io_buf_slice_ref() {
423471
let s: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
@@ -447,4 +495,25 @@ mod tests {
447495
assert_eq!(slice.bytes_init(), 5);
448496
assert_eq!(slice.into_inner().len(), 6);
449497
}
498+
499+
#[test]
500+
fn io_buf_arc_slice() {
501+
let mut buf = Vec::with_capacity(10);
502+
buf.extend_from_slice(b"0123");
503+
let buf = Arc::new(buf);
504+
let ptr = buf.as_ptr();
505+
506+
let slice = buf.slice(1..3);
507+
assert_eq!((slice.begin(), slice.end()), (1, 3));
508+
assert_eq!(slice.read_ptr(), unsafe { ptr.add(1) });
509+
assert_eq!(slice.bytes_init(), 2);
510+
let buf = Arc::into_inner(slice.into_inner()).unwrap();
511+
512+
let mut slice = buf.slice_mut(1..8);
513+
assert_eq!((slice.begin(), slice.end()), (1, 8));
514+
assert_eq!(slice.bytes_total(), 7);
515+
unsafe { slice.set_init(5) };
516+
assert_eq!(slice.bytes_init(), 5);
517+
assert_eq!(slice.into_inner().len(), 6);
518+
}
450519
}

0 commit comments

Comments
 (0)