Skip to content

Commit

Permalink
refactor: use len and cap of vec in buf writer instead
Browse files Browse the repository at this point in the history
  • Loading branch information
ethe committed Nov 10, 2024
1 parent 6663f26 commit 82ddc43
Showing 1 changed file with 8 additions and 9 deletions.
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

0 comments on commit 82ddc43

Please sign in to comment.