Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@ edition = "2021"

[features]
default = ["all"]
all = ["io", "os"]
all = ["io", "os", "bytes"]
io = []
os = []
bytes = ["dep:bytes"]

[dependencies]
system_error = "0.2"
bytes = { version = "1", optional = true }

[target.'cfg(unix)'.dependencies]
libc = "0.2"
Expand Down
69 changes: 69 additions & 0 deletions src/io/bytes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
//! Implementations of bytes::BufMut and bytes::Buf for Ring

use std::io::BufRead;

use bytes::{buf::UninitSlice, Buf, BufMut};

use super::{Ring, SeqRead, SeqWrite};

impl Buf for Ring {
fn remaining(&self) -> usize {
self.read_len()
}

fn chunk(&self) -> &[u8] {
self.as_read_slice(usize::MAX)
}

fn advance(&mut self, cnt: usize) {
self.consume(cnt)
}
}

unsafe impl BufMut for Ring {
fn remaining_mut(&self) -> usize {
self.write_len()
}

unsafe fn advance_mut(&mut self, cnt: usize) {
self.feed(cnt)
}

fn chunk_mut(&mut self) -> &mut UninitSlice {
UninitSlice::new(self.as_write_slice(usize::MAX))
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is probably the weirdest part of the BufMut API, but as documented here ::new is used for initialized memory. https://docs.rs/bytes/latest/bytes/buf/struct.UninitSlice.html#method.new

}
}

#[cfg(test)]
mod tests {
use crate::page_size;

use super::super::Ring;
use bytes::{Buf, BufMut};

#[test]
fn test_bytes_sanity() {
let size = page_size();
let mut buf = Ring::new(size).expect("failed to create buffer");

// empty case
assert_eq!(buf.remaining(), 0);
assert_eq!(buf.chunk().len(), 0);
assert_eq!(buf.remaining_mut(), size);
assert_eq!(buf.chunk_mut().len(), size);

// write something
buf.put_slice(b"hello world");
assert_eq!(buf.remaining(), 11);
assert_eq!(buf.chunk(), b"hello world");
assert_eq!(buf.remaining_mut(), size - 11);
assert_eq!(buf.chunk_mut().len(), size - 11);

// consume some
buf.advance(6);
assert_eq!(buf.remaining(), 5);
assert_eq!(buf.chunk(), b"world");
assert_eq!(buf.remaining_mut(), size - 5);
assert_eq!(buf.chunk_mut().len(), size - 5);
}
}
4 changes: 4 additions & 0 deletions src/io/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,15 @@
//! space as needed.

mod ring;

pub use self::ring::*;

mod buffer;
pub use self::buffer::*;

#[cfg(feature = "bytes")]
pub mod bytes;

use std::cmp;
use std::io::{self, BufRead};
use std::slice;
Expand Down