diff --git a/fusio/src/impls/buffered.rs b/fusio/src/impls/buffered.rs index b2c451b..6f8d7fd 100644 --- a/fusio/src/impls/buffered.rs +++ b/fusio/src/impls/buffered.rs @@ -92,8 +92,6 @@ impl BufReader { pub struct BufWriter { inner: F, buf: Option>, - capacity: usize, - pos: usize, } impl BufWriter { @@ -101,16 +99,19 @@ impl BufWriter { Self { inner: file, buf: Some(Vec::with_capacity(capacity)), - capacity, - pos: 0, } } } impl Write for BufWriter { async fn write_all(&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); @@ -121,12 +122,11 @@ impl Write for BufWriter { // 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) } } @@ -137,9 +137,8 @@ impl Write for BufWriter { 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(())