Skip to content

Commit

Permalink
fix: compat Buf not remember offset after read&write (#225)
Browse files Browse the repository at this point in the history
  • Loading branch information
hxzhao527 authored Jan 24, 2024
1 parent f684db1 commit b8f70d0
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 7 deletions.
2 changes: 1 addition & 1 deletion monoio-compat/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ license = "MIT/Apache-2.0"
name = "monoio-compat"
readme = "README.md"
repository = "https://github.com/bytedance/monoio"
version = "0.2.0"
version = "0.2.1"

[dependencies]
monoio = {version = "0.2.0", path = "../monoio", default-features = false}
Expand Down
52 changes: 48 additions & 4 deletions monoio-compat/src/buf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,8 @@ impl Buf {

/// Return slice for copying data from Buf to user space.
pub(crate) fn buf_to_read(&self, max: usize) -> &[u8] {
let ptr = self.data.as_ptr() as *const u8;
let len = max.min(self.init - self.offset);
unsafe { std::slice::from_raw_parts(ptr, len) }
unsafe { std::slice::from_raw_parts(self.read_ptr(), len) }
}

/// Advance offset.
Expand All @@ -132,7 +131,52 @@ impl Buf {
/// Return slice for copying data from user space to Buf.
#[allow(clippy::mut_from_ref)]
pub(crate) fn buf_to_write(&mut self) -> &mut [u8] {
let ptr = self.data.as_ptr() as *mut u8;
unsafe { std::slice::from_raw_parts_mut(ptr, self.capacity) }
unsafe { std::slice::from_raw_parts_mut(self.write_ptr(), self.bytes_total()) }
}
}

#[cfg(test)]
mod tests {
use monoio::buf::IoBufMut;

use super::Buf;

#[test]
fn test_buf_to_rw() {
let mut buf = Buf::new(20);
// write 0..10
{
let filled = buf.buf_to_write();
for i in 0..10u8 {
filled[i as usize] = i;
}
unsafe {
buf.set_init(10);
}
}

// read 0..5
{
let part = buf.buf_to_read(5);
for i in 0..5u8 {
assert_eq!(part[i as usize], i);
}
unsafe {
buf.advance_offset(5);
}
}

// read 5..10
{
let part = buf.buf_to_read(5);
for i in 5..10u8 {
assert_eq!(part[i as usize - 5], i);
}
unsafe {
buf.advance_offset(5);
}
}

assert!(buf.is_empty());
}
}
8 changes: 6 additions & 2 deletions monoio-compat/src/tcp_unsafe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,12 @@ impl tokio::io::AsyncRead for TcpStreamCompat {
}
};
this.read_dst.reset();
buf.advance(ret?);
std::task::Poll::Ready(Ok(()))
std::task::Poll::Ready(ret.map(|n| {
unsafe {
buf.assume_init(n);
}
buf.advance(n);
}))
}
}

Expand Down

0 comments on commit b8f70d0

Please sign in to comment.