Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use len and cap of vec in buf writer instead #95

Merged
merged 1 commit into from
Nov 10, 2024
Merged
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
17 changes: 8 additions & 9 deletions fusio/src/impls/buffered.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,25 +92,26 @@ impl<F: Read> BufReader<F> {
pub struct BufWriter<F> {
inner: F,
buf: Option<Vec<u8>>,
capacity: usize,
pos: usize,
}

impl<F> BufWriter<F> {
pub fn new(file: F, capacity: usize) -> Self {
Self {
inner: file,
buf: Some(Vec::with_capacity(capacity)),
capacity,
pos: 0,
}
}
}

impl<F: Write> Write for BufWriter<F> {
async fn write_all<B: IoBuf>(&mut self, buf: B) -> (Result<(), Error>, B) {
let (len, capacity) = {
let buf = self.buf.as_ref().expect("no buffer available");
(buf.len(), buf.capacity())
};

let written_size = buf.bytes_init();
if self.pos + written_size > self.capacity {
if len + written_size > capacity {
let result = self.flush().await;
if result.is_err() {
return (result, buf);
Expand All @@ -121,12 +122,11 @@ impl<F: Write> Write for BufWriter<F> {
// 1. There is no enough space to hold data, which means buffer is empty and written size >
// capacity
// 2. Data can be written to buffer
if self.pos + written_size > self.capacity {
if len + written_size > capacity {
self.inner.write_all(buf).await
} else {
let owned_buf = self.buf.as_mut().unwrap();
owned_buf.extend_from_slice(buf.as_slice());
self.pos += written_size;
(Ok(()), buf)
}
}
Expand All @@ -137,9 +137,8 @@ impl<F: Write> Write for BufWriter<F> {
let (result, mut data) = self.inner.write_all(data).await;
result?;

data.drain(..self.pos);
data.clear();
self.buf = Some(data);
self.pos = 0;
self.inner.flush().await?;

Ok(())
Expand Down
Loading