You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@opendal.apache.org by "WenyXu (via GitHub)" <gi...@apache.org> on 2023/12/23 15:56:59 UTC
[PR] feat(oio::read): implement the async buffer reader [incubator-opendal]
WenyXu opened a new pull request, #3811:
URL: https://github.com/apache/incubator-opendal/pull/3811
Implement the async buffer reader.
It's a little more complex than I expected. Maybe I should list each case and write more tests.
### Related
#3735
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(oio::read): implement the async buffer reader [incubator-opendal]
Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on PR #3811:
URL: https://github.com/apache/incubator-opendal/pull/3811#issuecomment-1868335521
> It's a little more complex than I expected. Maybe I should list each case and write more tests.
I feel like we can learn from tokio's [BufReader](https://docs.rs/tokio/latest/src/tokio/io/util/buf_reader.rs.html).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(oio::read): implement the async buffer reader [incubator-opendal]
Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #3811:
URL: https://github.com/apache/incubator-opendal/pull/3811#discussion_r1438510099
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,464 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::Bytes;
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
+
+ buf: Vec<u8>,
+ filled: usize,
+ pos: usize,
+}
+
+impl<R> BufferReader<R> {
+ /// Create a new [`oio::Reader`] with a buffer.
+ pub fn new(r: R, cap: usize) -> BufferReader<R> {
+ BufferReader {
+ r,
+ cur: 0,
+
+ buf: Vec::with_capacity(cap),
+ filled: 0,
+ pos: 0,
+ }
+ }
+
+ /// Invalidates all data in the internal buffer.
+ #[inline]
+ fn discard_buffer(&mut self) {
+ self.buf.clear();
+ self.pos = 0;
+ self.filled = 0;
+ }
+
+ /// Returns the capacity of the internal buffer.
+ fn capacity(&self) -> usize {
+ self.buf.capacity()
+ }
+}
+
+impl<R> BufferReader<R>
+where
+ R: oio::Read,
+{
+ fn poll_fill_buf(&mut self, cx: &mut Context<'_>) -> Poll<Result<&[u8]>> {
+ // If we've reached the end of our internal buffer then we need to fetch
+ // some more data from the underlying reader.
+ // Branch using `>=` instead of the more correct `==`
+ // to tell the compiler that the pos..cap slice is always valid.
+ if self.pos >= self.filled {
+ debug_assert!(self.pos == self.filled);
+
+ let cap = self.capacity();
+ self.buf.clear();
+ let dst = self.buf.spare_capacity_mut();
+ let mut buf = ReadBuf::uninit(dst);
+ unsafe { buf.assume_init(cap) };
+
+ let n = ready!(self.r.poll_read(cx, buf.initialized_mut()))?;
+ unsafe { self.buf.set_len(n) }
+
+ self.pos = 0;
+ self.filled = n;
+ }
+
+ Poll::Ready(Ok(&self.buf[self.pos..self.filled]))
+ }
+
+ fn consume(&mut self, amt: usize) {
+ let new_pos = min(self.pos + amt, self.filled);
+ let amt = new_pos - self.pos;
+
+ self.pos = new_pos;
+ self.cur += amt as u64;
+ }
+
+ fn seek_relative(&mut self, offset: i64) -> Option<u64> {
+ let pos = self.pos as u64;
+
+ if let (Some(new_pos), Some(new_cur)) = (
+ pos.checked_add_signed(offset),
+ self.cur.checked_add_signed(offset),
+ ) {
+ if new_pos <= self.filled as u64 {
+ self.cur = new_cur;
+ self.pos = new_pos as usize;
+ return Some(self.cur);
+ }
+ }
+
+ None
+ }
+
+ fn poll_inner_seek(&mut self, cx: &mut Context<'_>, pos: SeekFrom) -> Poll<Result<u64>> {
+ let cur = ready!(self.r.poll_seek(cx, pos))?;
+ self.discard_buffer();
+ self.cur = cur;
+
+ Poll::Ready(Ok(cur))
+ }
+}
+
+impl<R> oio::Read for BufferReader<R>
+where
+ R: oio::Read,
+{
+ fn poll_read(&mut self, cx: &mut Context<'_>, mut dst: &mut [u8]) -> Poll<Result<usize>> {
+ // Sanity check for normal cases.
+ if dst.is_empty() {
+ return Poll::Ready(Ok(0));
+ }
+
+ // If we don't have any buffered data and we're doing a massive read
+ // (larger than our internal buffer), bypass our internal buffer
+ // entirely.
+ if self.pos == self.filled && dst.len() >= self.capacity() {
+ let res = ready!(self.r.poll_read(cx, dst));
+ self.discard_buffer();
+ return Poll::Ready(res);
+ }
+
+ let rem = ready!(self.poll_fill_buf(cx))?;
+ let amt = min(rem.len(), dst.len());
+ dst.put(&rem[..amt]);
+ self.consume(amt);
+ Poll::Ready(Ok(amt))
+ }
+
+ fn poll_seek(&mut self, cx: &mut Context<'_>, pos: SeekFrom) -> Poll<Result<u64>> {
+ let offset = match pos {
+ SeekFrom::Start(new_pos) => {
+ // TODO(weny): Check the overflowing.
+ match (new_pos as i64).checked_sub(self.cur as i64) {
+ Some(n) => n,
+ _ => return self.poll_inner_seek(cx, pos),
+ }
+ }
+ SeekFrom::Current(offset) => offset,
Review Comment:
So only limited cases will go to the `seek_relative` logic. How about refactor code like:
```
match pos {
SeekFrom::Start => { ... }
SeekFrom::Current => { ... }
SeekFrom::End => { ... }
}
```
Although we will repeat the same line, I feel they are much easier to read.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(oio::read): implement the async buffer reader [incubator-opendal]
Posted by "WenyXu (via GitHub)" <gi...@apache.org>.
WenyXu commented on code in PR #3811:
URL: https://github.com/apache/incubator-opendal/pull/3811#discussion_r1435639811
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,457 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::{Bytes, BytesMut};
+
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
+
+ buf: BytesMut,
+ cap: usize,
+ /// Indicate buffered data range start.
+ /// `None` stand for no buffered data.
+ buf_start: Option<usize>,
+}
+
+impl<R> BufferReader<R> {
+ /// Create a new [`oio::Reader`] with a buffer.
+ ///
+ /// # Input
+ ///
+ /// The input is an Accessor will may return a seekable reader.
Review Comment:
```suggestion
```
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,457 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::{Bytes, BytesMut};
+
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
+
+ buf: BytesMut,
Review Comment:
I changed my mind; I didn't use the `tokio::io::ReadBuf`. Maybe `Vec<u8>` is also suitable for this case.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(oio::read): implement the async buffer reader [incubator-opendal]
Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #3811:
URL: https://github.com/apache/incubator-opendal/pull/3811#discussion_r1435770758
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,457 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::{Bytes, BytesMut};
+
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
+
+ buf: BytesMut,
+ cap: usize,
+ /// Indicate buffered data range start.
+ /// `None` stand for no buffered data.
+ buf_start: Option<usize>,
+}
+
+impl<R> BufferReader<R> {
+ /// Create a new [`oio::Reader`] with a buffer.
+ ///
+ /// # Input
+ ///
+ /// The input is an Accessor will may return a seekable reader.
+ pub fn new(r: R, cap: usize) -> BufferReader<R> {
+ BufferReader {
+ r,
+ cur: 0,
+
+ // Lazy allocation.
+ buf: BytesMut::new(),
+ cap,
+ buf_start: None,
+ }
+ }
+
+ /// Returns the capability of buffer.
+ pub fn cap(&self) -> usize {
+ self.cap
+ }
+}
+
+impl<R> BufferReader<R>
+where
+ R: oio::Read,
+{
+ /// Fill the internal buffer.
+ fn poll_fill_buf(&mut self, cx: &mut Context<'_>) -> Poll<Result<usize>> {
+ self.clear_buffer();
+ self.buf.reserve(self.cap);
+
+ if let Err(err) = ready!(self.r.poll_seek(cx, SeekFrom::Start(self.cur))) {
+ return Poll::Ready(Err(err));
+ }
+
+ let mut nread = 0;
+
+ while self.buf.len() < self.buf.capacity() {
+ let dst = self.buf.spare_capacity_mut();
+ let length = dst.len();
+ let mut buf = ReadBuf::uninit(dst);
+
+ // Safety: must initialized.
+ unsafe {
+ buf.assume_init(length);
+ }
+
+ match ready!(self.r.poll_read(cx, buf.initialized_mut())) {
+ Ok(n) => {
+ if n == 0 {
+ break;
+ }
+ unsafe { self.buf.set_len(n) }
+ // Don't need to sync the underlying reader's `cur`.
+ nread += n
+ }
+ Err(err) => return Poll::Ready(Err(err)),
+ }
+ }
+ self.buf_start = Some(self.cur as usize);
+
+ Poll::Ready(Ok(nread))
+ }
+
+ /// Returns buffer data range.
+ fn buffer_range(&self) -> Option<(usize, usize)> {
+ self.buf_start.map(|start| {
+ let end = start + self.buf.len();
+
+ (start, end)
+ })
+ }
+
+ /// Clears the internal buffer and `buf_start`.
+ fn clear_buffer(&mut self) {
+ self.buf_start = None;
+ self.buf.clear();
+ }
+
+ /// Returns true if underlying reader is no more data.
+ fn has_reach_end(&self) -> bool {
+ self.buf_start
+ .map(|buf_start| buf_start == self.cur as usize)
+ .unwrap_or(false)
+ && self.buf.len() < self.buf.capacity()
+ }
+}
+
+impl<R> oio::Read for BufferReader<R>
+where
+ R: oio::Read,
+{
+ fn poll_read(&mut self, cx: &mut Context<'_>, mut dst: &mut [u8]) -> Poll<Result<usize>> {
+ // Sanity check for normal cases.
+ if dst.is_empty() {
+ return Poll::Ready(Ok(0));
+ }
+
+ // If we're doing a massive read (larger than our internal buffer),
+ // bypass our internal buffer entirely.
+ if dst.len() >= self.cap() {
+ // Ensures calling the `seek` before bypass internal buffer.
+ if let Err(err) = ready!(self.poll_seek(cx, SeekFrom::Start(self.cur))) {
+ return Poll::Ready(Err(err));
+ }
+ return match ready!(self.r.poll_read(cx, dst)) {
+ Ok(n) => {
+ self.cur += n as u64;
+ Poll::Ready(Ok(n))
+ }
+ Err(err) => Poll::Ready(Err(err)),
+ };
+ }
+
+ let (read_start, read_end) = (self.cur as usize, self.cur as usize + dst.len());
+
+ if let Some((buf_start, buf_end)) = self.buffer_range() {
+ if buf_start == buf_end && buf_start == self.cur as usize {
+ self.clear_buffer();
+ return Poll::Ready(Ok(0));
+ }
+ // Hit the buffer.
+ // +---------------+
+ // | Buffer Data |
+ // ----+^--------------^-----
+ // | |
+ // | |
+ // cur cur + dst.len()
+ if buf_start <= read_start && read_end <= buf_end {
+ // Invariant: buf.len() <= cap
+ let offset = self.cur as usize - buf_start;
+ let amt = min(buf_end - self.cur as usize, dst.len());
+
+ dst.put_slice(&self.buf[offset..offset + amt]);
+ self.cur = read_end as u64;
+ return Poll::Ready(Ok(amt));
+ } else if buf_start <= read_start && read_start < buf_end {
+ // Hit part of buffer.
+ // +---------------+
+ // | Buffer Data |
+ // ----+--------^----------^--
+ // | |
+ // | |
+ // cur cur + dst.len()
+
+ let offset = self.cur as usize - buf_start;
+ let rem = min(buf_end - self.cur as usize, dst.len());
+
+ dst.put_slice(&self.buf[offset..offset + rem]);
+
+ if let Err(err) = ready!(self.poll_seek(cx, SeekFrom::Start(buf_end as u64))) {
+ return Poll::Ready(Err(err));
+ }
+ if self.has_reach_end() {
+ return Poll::Ready(Ok(rem));
+ }
+ } else if let Err(err) = ready!(self.poll_seek(cx, SeekFrom::Start(self.cur))) {
+ return Poll::Ready(Err(err));
+ }
+ }
+
+ // Continue read
+ match ready!(self.poll_fill_buf(cx)) {
+ Ok(_) => self.poll_read(cx, dst),
+ Err(err) => Poll::Ready(Err(err)),
+ }
+ }
+
+ fn poll_seek(&mut self, cx: &mut Context<'_>, pos: SeekFrom) -> Poll<Result<u64>> {
+ match ready!(self.r.poll_seek(cx, pos)) {
+ Ok(cur) => {
+ self.cur = cur;
+
+ Poll::Ready(Ok(cur))
+ }
+ Err(err) => Poll::Ready(Err(err)),
+ }
+ }
+
+ fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<Bytes>>> {
Review Comment:
> Sorry, I didn't get this. Forwarding the buffer directly seems sensible.
For example, users called `read` and `next`. It's possible that we have buffered some data internally, we should return the buffered data first.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(oio::read): implement the async buffer reader [incubator-opendal]
Posted by "WenyXu (via GitHub)" <gi...@apache.org>.
WenyXu commented on PR #3811:
URL: https://github.com/apache/incubator-opendal/pull/3811#issuecomment-1872463598
Sorry for the delay. I spent quite a busy week🥲.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(oio::read): implement the async buffer reader [incubator-opendal]
Posted by "WenyXu (via GitHub)" <gi...@apache.org>.
WenyXu commented on code in PR #3811:
URL: https://github.com/apache/incubator-opendal/pull/3811#discussion_r1435757112
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,457 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::{Bytes, BytesMut};
+
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
+
+ buf: BytesMut,
+ cap: usize,
+ /// Indicate buffered data range start.
+ /// `None` stand for no buffered data.
+ buf_start: Option<usize>,
+}
+
+impl<R> BufferReader<R> {
+ /// Create a new [`oio::Reader`] with a buffer.
+ ///
+ /// # Input
+ ///
+ /// The input is an Accessor will may return a seekable reader.
+ pub fn new(r: R, cap: usize) -> BufferReader<R> {
+ BufferReader {
+ r,
+ cur: 0,
+
+ // Lazy allocation.
+ buf: BytesMut::new(),
+ cap,
+ buf_start: None,
+ }
+ }
+
+ /// Returns the capability of buffer.
+ pub fn cap(&self) -> usize {
+ self.cap
+ }
+}
+
+impl<R> BufferReader<R>
+where
+ R: oio::Read,
+{
+ /// Fill the internal buffer.
+ fn poll_fill_buf(&mut self, cx: &mut Context<'_>) -> Poll<Result<usize>> {
+ self.clear_buffer();
+ self.buf.reserve(self.cap);
+
+ if let Err(err) = ready!(self.r.poll_seek(cx, SeekFrom::Start(self.cur))) {
Review Comment:
Thanks, good point!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(oio::read): implement the async buffer reader [incubator-opendal]
Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo merged PR #3811:
URL: https://github.com/apache/incubator-opendal/pull/3811
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(oio::read): implement the async buffer reader [incubator-opendal]
Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #3811:
URL: https://github.com/apache/incubator-opendal/pull/3811#discussion_r1438488454
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,469 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::Bytes;
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
+
+ buf: Vec<u8>,
+ filled: usize,
+ pos: usize,
+}
+
+impl<R> BufferReader<R> {
+ /// Create a new [`oio::Reader`] with a buffer.
+ pub fn new(r: R, cap: usize) -> BufferReader<R> {
+ BufferReader {
+ r,
+ cur: 0,
+
+ buf: Vec::with_capacity(cap),
+ filled: 0,
+ pos: 0,
+ }
+ }
+
+ /// Invalidates all data in the internal buffer.
+ #[inline]
+ fn discard_buffer(&mut self) {
+ self.buf.clear();
+ self.pos = 0;
+ self.filled = 0;
+ }
+
+ /// Returns the capacity of the internal buffer.
+ fn capacity(&self) -> usize {
+ self.buf.capacity()
+ }
+}
+
+impl<R> BufferReader<R>
+where
+ R: oio::Read,
+{
+ fn poll_fill_buf(&mut self, cx: &mut Context<'_>) -> Poll<Result<&[u8]>> {
+ // If we've reached the end of our internal buffer then we need to fetch
+ // some more data from the underlying reader.
+ // Branch using `>=` instead of the more correct `==`
+ // to tell the compiler that the pos..cap slice is always valid.
+ if self.pos >= self.filled {
+ debug_assert!(self.pos == self.filled);
+
+ let cap = self.capacity();
+ self.buf.clear();
+ let dst = self.buf.spare_capacity_mut();
+ let mut buf = ReadBuf::uninit(dst);
+ unsafe { buf.assume_init(cap) };
+
+ let n = ready!(self.r.poll_read(cx, buf.initialized_mut()))?;
+ unsafe { self.buf.set_len(n) }
+
+ self.pos = 0;
+ self.filled = n;
+ }
+
+ Poll::Ready(Ok(&self.buf[self.pos..self.filled]))
+ }
+
+ fn consume(&mut self, amt: usize) {
+ self.pos = min(self.pos + amt, self.filled);
Review Comment:
When will `self.pos + amt > self.filled` happen? Do we need to handle the `self.cur` correctly?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(oio::read): implement the async buffer reader [incubator-opendal]
Posted by "WenyXu (via GitHub)" <gi...@apache.org>.
WenyXu commented on code in PR #3811:
URL: https://github.com/apache/incubator-opendal/pull/3811#discussion_r1435751951
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,457 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::{Bytes, BytesMut};
+
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
+
+ buf: BytesMut,
+ cap: usize,
+ /// Indicate buffered data range start.
+ /// `None` stand for no buffered data.
+ buf_start: Option<usize>,
+}
+
+impl<R> BufferReader<R> {
+ /// Create a new [`oio::Reader`] with a buffer.
+ ///
+ /// # Input
+ ///
+ /// The input is an Accessor will may return a seekable reader.
+ pub fn new(r: R, cap: usize) -> BufferReader<R> {
+ BufferReader {
+ r,
+ cur: 0,
+
+ // Lazy allocation.
+ buf: BytesMut::new(),
+ cap,
+ buf_start: None,
+ }
+ }
+
+ /// Returns the capability of buffer.
+ pub fn cap(&self) -> usize {
+ self.cap
+ }
+}
+
+impl<R> BufferReader<R>
+where
+ R: oio::Read,
+{
+ /// Fill the internal buffer.
+ fn poll_fill_buf(&mut self, cx: &mut Context<'_>) -> Poll<Result<usize>> {
+ self.clear_buffer();
+ self.buf.reserve(self.cap);
+
+ if let Err(err) = ready!(self.r.poll_seek(cx, SeekFrom::Start(self.cur))) {
+ return Poll::Ready(Err(err));
+ }
+
+ let mut nread = 0;
+
+ while self.buf.len() < self.buf.capacity() {
+ let dst = self.buf.spare_capacity_mut();
+ let length = dst.len();
+ let mut buf = ReadBuf::uninit(dst);
+
+ // Safety: must initialized.
+ unsafe {
+ buf.assume_init(length);
+ }
+
+ match ready!(self.r.poll_read(cx, buf.initialized_mut())) {
+ Ok(n) => {
+ if n == 0 {
+ break;
+ }
+ unsafe { self.buf.set_len(n) }
+ // Don't need to sync the underlying reader's `cur`.
+ nread += n
+ }
+ Err(err) => return Poll::Ready(Err(err)),
+ }
+ }
+ self.buf_start = Some(self.cur as usize);
+
+ Poll::Ready(Ok(nread))
+ }
+
+ /// Returns buffer data range.
+ fn buffer_range(&self) -> Option<(usize, usize)> {
+ self.buf_start.map(|start| {
+ let end = start + self.buf.len();
+
+ (start, end)
+ })
+ }
+
+ /// Clears the internal buffer and `buf_start`.
+ fn clear_buffer(&mut self) {
+ self.buf_start = None;
+ self.buf.clear();
+ }
+
+ /// Returns true if underlying reader is no more data.
+ fn has_reach_end(&self) -> bool {
+ self.buf_start
+ .map(|buf_start| buf_start == self.cur as usize)
+ .unwrap_or(false)
+ && self.buf.len() < self.buf.capacity()
+ }
+}
+
+impl<R> oio::Read for BufferReader<R>
+where
+ R: oio::Read,
+{
+ fn poll_read(&mut self, cx: &mut Context<'_>, mut dst: &mut [u8]) -> Poll<Result<usize>> {
+ // Sanity check for normal cases.
+ if dst.is_empty() {
+ return Poll::Ready(Ok(0));
+ }
+
+ // If we're doing a massive read (larger than our internal buffer),
+ // bypass our internal buffer entirely.
+ if dst.len() >= self.cap() {
+ // Ensures calling the `seek` before bypass internal buffer.
+ if let Err(err) = ready!(self.poll_seek(cx, SeekFrom::Start(self.cur))) {
+ return Poll::Ready(Err(err));
+ }
+ return match ready!(self.r.poll_read(cx, dst)) {
+ Ok(n) => {
+ self.cur += n as u64;
+ Poll::Ready(Ok(n))
+ }
+ Err(err) => Poll::Ready(Err(err)),
+ };
+ }
+
+ let (read_start, read_end) = (self.cur as usize, self.cur as usize + dst.len());
+
+ if let Some((buf_start, buf_end)) = self.buffer_range() {
+ if buf_start == buf_end && buf_start == self.cur as usize {
+ self.clear_buffer();
+ return Poll::Ready(Ok(0));
+ }
+ // Hit the buffer.
+ // +---------------+
+ // | Buffer Data |
+ // ----+^--------------^-----
+ // | |
+ // | |
+ // cur cur + dst.len()
+ if buf_start <= read_start && read_end <= buf_end {
+ // Invariant: buf.len() <= cap
+ let offset = self.cur as usize - buf_start;
+ let amt = min(buf_end - self.cur as usize, dst.len());
+
+ dst.put_slice(&self.buf[offset..offset + amt]);
+ self.cur = read_end as u64;
+ return Poll::Ready(Ok(amt));
+ } else if buf_start <= read_start && read_start < buf_end {
+ // Hit part of buffer.
+ // +---------------+
+ // | Buffer Data |
+ // ----+--------^----------^--
+ // | |
+ // | |
+ // cur cur + dst.len()
+
+ let offset = self.cur as usize - buf_start;
+ let rem = min(buf_end - self.cur as usize, dst.len());
+
+ dst.put_slice(&self.buf[offset..offset + rem]);
+
+ if let Err(err) = ready!(self.poll_seek(cx, SeekFrom::Start(buf_end as u64))) {
+ return Poll::Ready(Err(err));
+ }
+ if self.has_reach_end() {
+ return Poll::Ready(Ok(rem));
+ }
+ } else if let Err(err) = ready!(self.poll_seek(cx, SeekFrom::Start(self.cur))) {
+ return Poll::Ready(Err(err));
+ }
+ }
+
+ // Continue read
+ match ready!(self.poll_fill_buf(cx)) {
+ Ok(_) => self.poll_read(cx, dst),
+ Err(err) => Poll::Ready(Err(err)),
+ }
+ }
+
+ fn poll_seek(&mut self, cx: &mut Context<'_>, pos: SeekFrom) -> Poll<Result<u64>> {
+ match ready!(self.r.poll_seek(cx, pos)) {
+ Ok(cur) => {
+ self.cur = cur;
+
+ Poll::Ready(Ok(cur))
+ }
+ Err(err) => Poll::Ready(Err(err)),
+ }
+ }
+
+ fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<Bytes>>> {
Review Comment:
> poll_next should respect buffer.
Sorry, I didn't get this. Forwarding the buffer directly seems sensible.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(oio::read): implement the async buffer reader [incubator-opendal]
Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #3811:
URL: https://github.com/apache/incubator-opendal/pull/3811#discussion_r1438488454
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,469 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::Bytes;
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
+
+ buf: Vec<u8>,
+ filled: usize,
+ pos: usize,
+}
+
+impl<R> BufferReader<R> {
+ /// Create a new [`oio::Reader`] with a buffer.
+ pub fn new(r: R, cap: usize) -> BufferReader<R> {
+ BufferReader {
+ r,
+ cur: 0,
+
+ buf: Vec::with_capacity(cap),
+ filled: 0,
+ pos: 0,
+ }
+ }
+
+ /// Invalidates all data in the internal buffer.
+ #[inline]
+ fn discard_buffer(&mut self) {
+ self.buf.clear();
+ self.pos = 0;
+ self.filled = 0;
+ }
+
+ /// Returns the capacity of the internal buffer.
+ fn capacity(&self) -> usize {
+ self.buf.capacity()
+ }
+}
+
+impl<R> BufferReader<R>
+where
+ R: oio::Read,
+{
+ fn poll_fill_buf(&mut self, cx: &mut Context<'_>) -> Poll<Result<&[u8]>> {
+ // If we've reached the end of our internal buffer then we need to fetch
+ // some more data from the underlying reader.
+ // Branch using `>=` instead of the more correct `==`
+ // to tell the compiler that the pos..cap slice is always valid.
+ if self.pos >= self.filled {
+ debug_assert!(self.pos == self.filled);
+
+ let cap = self.capacity();
+ self.buf.clear();
+ let dst = self.buf.spare_capacity_mut();
+ let mut buf = ReadBuf::uninit(dst);
+ unsafe { buf.assume_init(cap) };
+
+ let n = ready!(self.r.poll_read(cx, buf.initialized_mut()))?;
+ unsafe { self.buf.set_len(n) }
+
+ self.pos = 0;
+ self.filled = n;
+ }
+
+ Poll::Ready(Ok(&self.buf[self.pos..self.filled]))
+ }
+
+ fn consume(&mut self, amt: usize) {
+ self.pos = min(self.pos + amt, self.filled);
Review Comment:
When will `self.pos + amt > self.filled` happen? Do we need to handle the `self.cur` correct?
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,469 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::Bytes;
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
+
+ buf: Vec<u8>,
+ filled: usize,
+ pos: usize,
+}
+
+impl<R> BufferReader<R> {
+ /// Create a new [`oio::Reader`] with a buffer.
+ pub fn new(r: R, cap: usize) -> BufferReader<R> {
+ BufferReader {
+ r,
+ cur: 0,
+
+ buf: Vec::with_capacity(cap),
+ filled: 0,
+ pos: 0,
+ }
+ }
+
+ /// Invalidates all data in the internal buffer.
+ #[inline]
+ fn discard_buffer(&mut self) {
+ self.buf.clear();
+ self.pos = 0;
+ self.filled = 0;
+ }
+
+ /// Returns the capacity of the internal buffer.
+ fn capacity(&self) -> usize {
+ self.buf.capacity()
+ }
+}
+
+impl<R> BufferReader<R>
+where
+ R: oio::Read,
+{
+ fn poll_fill_buf(&mut self, cx: &mut Context<'_>) -> Poll<Result<&[u8]>> {
+ // If we've reached the end of our internal buffer then we need to fetch
+ // some more data from the underlying reader.
+ // Branch using `>=` instead of the more correct `==`
+ // to tell the compiler that the pos..cap slice is always valid.
+ if self.pos >= self.filled {
+ debug_assert!(self.pos == self.filled);
+
+ let cap = self.capacity();
+ self.buf.clear();
+ let dst = self.buf.spare_capacity_mut();
+ let mut buf = ReadBuf::uninit(dst);
+ unsafe { buf.assume_init(cap) };
+
+ let n = ready!(self.r.poll_read(cx, buf.initialized_mut()))?;
+ unsafe { self.buf.set_len(n) }
+
+ self.pos = 0;
+ self.filled = n;
+ }
+
+ Poll::Ready(Ok(&self.buf[self.pos..self.filled]))
+ }
+
+ fn consume(&mut self, amt: usize) {
+ self.pos = min(self.pos + amt, self.filled);
+ self.cur += amt as u64;
+ }
+
+ fn seek_relative(&mut self, offset: i64) -> Option<u64> {
+ let pos = self.pos as u64;
+ if offset < 0 {
Review Comment:
How about using [checked_add_signed](https://doc.rust-lang.org/std/primitive.u64.html#method.checked_add_signed) so we don't need to handle signed offset by hand?
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,469 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::Bytes;
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
+
+ buf: Vec<u8>,
+ filled: usize,
+ pos: usize,
+}
+
+impl<R> BufferReader<R> {
+ /// Create a new [`oio::Reader`] with a buffer.
+ pub fn new(r: R, cap: usize) -> BufferReader<R> {
+ BufferReader {
+ r,
+ cur: 0,
+
+ buf: Vec::with_capacity(cap),
+ filled: 0,
+ pos: 0,
+ }
+ }
+
+ /// Invalidates all data in the internal buffer.
+ #[inline]
+ fn discard_buffer(&mut self) {
+ self.buf.clear();
+ self.pos = 0;
+ self.filled = 0;
+ }
+
+ /// Returns the capacity of the internal buffer.
+ fn capacity(&self) -> usize {
+ self.buf.capacity()
+ }
+}
+
+impl<R> BufferReader<R>
+where
+ R: oio::Read,
+{
+ fn poll_fill_buf(&mut self, cx: &mut Context<'_>) -> Poll<Result<&[u8]>> {
+ // If we've reached the end of our internal buffer then we need to fetch
+ // some more data from the underlying reader.
+ // Branch using `>=` instead of the more correct `==`
+ // to tell the compiler that the pos..cap slice is always valid.
+ if self.pos >= self.filled {
+ debug_assert!(self.pos == self.filled);
+
+ let cap = self.capacity();
+ self.buf.clear();
+ let dst = self.buf.spare_capacity_mut();
+ let mut buf = ReadBuf::uninit(dst);
+ unsafe { buf.assume_init(cap) };
+
+ let n = ready!(self.r.poll_read(cx, buf.initialized_mut()))?;
+ unsafe { self.buf.set_len(n) }
+
+ self.pos = 0;
+ self.filled = n;
+ }
+
+ Poll::Ready(Ok(&self.buf[self.pos..self.filled]))
+ }
+
+ fn consume(&mut self, amt: usize) {
+ self.pos = min(self.pos + amt, self.filled);
+ self.cur += amt as u64;
+ }
+
+ fn seek_relative(&mut self, offset: i64) -> Option<u64> {
+ let pos = self.pos as u64;
+ if offset < 0 {
+ if let Some(new_pos) = pos.checked_sub((-offset) as u64) {
+ self.cur -= (-offset) as u64;
+ self.pos = new_pos as usize;
+ return Some(self.cur);
+ }
+ } else if let Some(new_pos) = pos.checked_add(offset as u64) {
+ if new_pos <= self.filled as u64 {
+ self.cur += offset as u64;
+ self.pos = new_pos as usize;
+ return Some(self.cur);
+ }
+ }
+
+ None
+ }
+
+ fn poll_inner_seek(&mut self, cx: &mut Context<'_>, pos: SeekFrom) -> Poll<Result<u64>> {
+ let cur = ready!(self.r.poll_seek(cx, pos))?;
+ self.discard_buffer();
+ self.cur = cur;
+
+ Poll::Ready(Ok(cur))
+ }
+}
+
+impl<R> oio::Read for BufferReader<R>
+where
+ R: oio::Read,
+{
+ fn poll_read(&mut self, cx: &mut Context<'_>, mut dst: &mut [u8]) -> Poll<Result<usize>> {
+ // Sanity check for normal cases.
+ if dst.is_empty() {
+ return Poll::Ready(Ok(0));
+ }
+
+ // If we don't have any buffered data and we're doing a massive read
+ // (larger than our internal buffer), bypass our internal buffer
+ // entirely.
+ if self.pos == self.filled && dst.len() >= self.capacity() {
+ let res = ready!(self.r.poll_read(cx, dst));
+ self.discard_buffer();
+ return Poll::Ready(res);
+ }
+
+ let rem = ready!(self.poll_fill_buf(cx))?;
+
+ let amt = min(rem.len(), dst.len());
+ dst.put(&rem[..amt]);
+ self.consume(amt);
+ Poll::Ready(Ok(amt))
+ }
+
+ fn poll_seek(&mut self, cx: &mut Context<'_>, pos: SeekFrom) -> Poll<Result<u64>> {
+ let offset = match pos {
Review Comment:
Maybe we don't need to check offset? It should be safe to forward `poll_inner_seek` directly and let underlying reader to return the `InvalidInput` error. BufferReader doesn't change this behavior.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(oio::read): implement the async buffer reader [incubator-opendal]
Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #3811:
URL: https://github.com/apache/incubator-opendal/pull/3811#discussion_r1435653893
##########
core/src/raw/oio/read/test_util.rs:
##########
Review Comment:
I prefer not to add `test_util` in this way. How about just copying code that needed?
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,457 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::{Bytes, BytesMut};
+
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
+
+ buf: BytesMut,
+ cap: usize,
+ /// Indicate buffered data range start.
+ /// `None` stand for no buffered data.
+ buf_start: Option<usize>,
+}
+
+impl<R> BufferReader<R> {
+ /// Create a new [`oio::Reader`] with a buffer.
+ ///
+ /// # Input
+ ///
+ /// The input is an Accessor will may return a seekable reader.
+ pub fn new(r: R, cap: usize) -> BufferReader<R> {
+ BufferReader {
+ r,
+ cur: 0,
+
+ // Lazy allocation.
+ buf: BytesMut::new(),
+ cap,
+ buf_start: None,
+ }
+ }
+
+ /// Returns the capability of buffer.
+ pub fn cap(&self) -> usize {
+ self.cap
+ }
+}
+
+impl<R> BufferReader<R>
+where
+ R: oio::Read,
+{
+ /// Fill the internal buffer.
+ fn poll_fill_buf(&mut self, cx: &mut Context<'_>) -> Poll<Result<usize>> {
+ self.clear_buffer();
+ self.buf.reserve(self.cap);
Review Comment:
`reserve` will:
> Reserves capacity for at least additional more bytes to be inserted into the given BytesMut.
reserve `self.cap` every time calling `poll_fill_buf` is not expected. We should always reuse the same buffer.
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,457 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::{Bytes, BytesMut};
+
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
+
+ buf: BytesMut,
+ cap: usize,
+ /// Indicate buffered data range start.
+ /// `None` stand for no buffered data.
+ buf_start: Option<usize>,
+}
+
+impl<R> BufferReader<R> {
+ /// Create a new [`oio::Reader`] with a buffer.
+ ///
+ /// # Input
+ ///
+ /// The input is an Accessor will may return a seekable reader.
+ pub fn new(r: R, cap: usize) -> BufferReader<R> {
+ BufferReader {
+ r,
+ cur: 0,
+
+ // Lazy allocation.
Review Comment:
This lazy allocation doesn't make sure: the cap of this buf won't be changed during entire lifetime.
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,457 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::{Bytes, BytesMut};
+
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
+
+ buf: BytesMut,
+ cap: usize,
+ /// Indicate buffered data range start.
+ /// `None` stand for no buffered data.
+ buf_start: Option<usize>,
+}
+
+impl<R> BufferReader<R> {
+ /// Create a new [`oio::Reader`] with a buffer.
+ ///
+ /// # Input
+ ///
+ /// The input is an Accessor will may return a seekable reader.
+ pub fn new(r: R, cap: usize) -> BufferReader<R> {
+ BufferReader {
+ r,
+ cur: 0,
+
+ // Lazy allocation.
+ buf: BytesMut::new(),
+ cap,
+ buf_start: None,
+ }
+ }
+
+ /// Returns the capability of buffer.
+ pub fn cap(&self) -> usize {
+ self.cap
+ }
+}
+
+impl<R> BufferReader<R>
+where
+ R: oio::Read,
+{
+ /// Fill the internal buffer.
+ fn poll_fill_buf(&mut self, cx: &mut Context<'_>) -> Poll<Result<usize>> {
+ self.clear_buffer();
+ self.buf.reserve(self.cap);
+
+ if let Err(err) = ready!(self.r.poll_seek(cx, SeekFrom::Start(self.cur))) {
Review Comment:
Why we need to call `poll_seek` here?
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,457 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::{Bytes, BytesMut};
+
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
+
+ buf: BytesMut,
+ cap: usize,
+ /// Indicate buffered data range start.
+ /// `None` stand for no buffered data.
+ buf_start: Option<usize>,
+}
+
+impl<R> BufferReader<R> {
+ /// Create a new [`oio::Reader`] with a buffer.
+ ///
+ /// # Input
+ ///
+ /// The input is an Accessor will may return a seekable reader.
+ pub fn new(r: R, cap: usize) -> BufferReader<R> {
+ BufferReader {
+ r,
+ cur: 0,
+
+ // Lazy allocation.
+ buf: BytesMut::new(),
+ cap,
+ buf_start: None,
+ }
+ }
+
+ /// Returns the capability of buffer.
+ pub fn cap(&self) -> usize {
Review Comment:
Please don't expose this public API.
##########
core/src/types/operator/operator_futures.rs:
##########
@@ -409,6 +409,12 @@ impl FutureReader {
self.0 = self.0.map_args(|args| args.with_if_none_match(v));
self
}
+
+ /// Set the buffer capability to enable `BufferReader`.
+ pub fn buffer(mut self, v: usize) -> Self {
Review Comment:
We should support blocking API too. But it's ok to leave them in next PR.
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,457 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::{Bytes, BytesMut};
+
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
+
+ buf: BytesMut,
+ cap: usize,
+ /// Indicate buffered data range start.
+ /// `None` stand for no buffered data.
+ buf_start: Option<usize>,
+}
+
+impl<R> BufferReader<R> {
+ /// Create a new [`oio::Reader`] with a buffer.
+ ///
+ /// # Input
+ ///
+ /// The input is an Accessor will may return a seekable reader.
+ pub fn new(r: R, cap: usize) -> BufferReader<R> {
+ BufferReader {
+ r,
+ cur: 0,
+
+ // Lazy allocation.
+ buf: BytesMut::new(),
+ cap,
+ buf_start: None,
+ }
+ }
+
+ /// Returns the capability of buffer.
+ pub fn cap(&self) -> usize {
+ self.cap
+ }
+}
+
+impl<R> BufferReader<R>
+where
+ R: oio::Read,
+{
+ /// Fill the internal buffer.
+ fn poll_fill_buf(&mut self, cx: &mut Context<'_>) -> Poll<Result<usize>> {
+ self.clear_buffer();
+ self.buf.reserve(self.cap);
+
+ if let Err(err) = ready!(self.r.poll_seek(cx, SeekFrom::Start(self.cur))) {
+ return Poll::Ready(Err(err));
+ }
+
+ let mut nread = 0;
+
+ while self.buf.len() < self.buf.capacity() {
+ let dst = self.buf.spare_capacity_mut();
+ let length = dst.len();
+ let mut buf = ReadBuf::uninit(dst);
+
+ // Safety: must initialized.
+ unsafe {
+ buf.assume_init(length);
+ }
+
+ match ready!(self.r.poll_read(cx, buf.initialized_mut())) {
+ Ok(n) => {
+ if n == 0 {
+ break;
+ }
+ unsafe { self.buf.set_len(n) }
+ // Don't need to sync the underlying reader's `cur`.
+ nread += n
+ }
+ Err(err) => return Poll::Ready(Err(err)),
+ }
+ }
+ self.buf_start = Some(self.cur as usize);
+
+ Poll::Ready(Ok(nread))
+ }
+
+ /// Returns buffer data range.
+ fn buffer_range(&self) -> Option<(usize, usize)> {
+ self.buf_start.map(|start| {
+ let end = start + self.buf.len();
+
+ (start, end)
+ })
+ }
+
+ /// Clears the internal buffer and `buf_start`.
+ fn clear_buffer(&mut self) {
+ self.buf_start = None;
+ self.buf.clear();
+ }
+
+ /// Returns true if underlying reader is no more data.
+ fn has_reach_end(&self) -> bool {
+ self.buf_start
+ .map(|buf_start| buf_start == self.cur as usize)
+ .unwrap_or(false)
+ && self.buf.len() < self.buf.capacity()
+ }
+}
+
+impl<R> oio::Read for BufferReader<R>
+where
+ R: oio::Read,
+{
+ fn poll_read(&mut self, cx: &mut Context<'_>, mut dst: &mut [u8]) -> Poll<Result<usize>> {
+ // Sanity check for normal cases.
+ if dst.is_empty() {
+ return Poll::Ready(Ok(0));
+ }
+
+ // If we're doing a massive read (larger than our internal buffer),
+ // bypass our internal buffer entirely.
+ if dst.len() >= self.cap() {
+ // Ensures calling the `seek` before bypass internal buffer.
+ if let Err(err) = ready!(self.poll_seek(cx, SeekFrom::Start(self.cur))) {
+ return Poll::Ready(Err(err));
+ }
+ return match ready!(self.r.poll_read(cx, dst)) {
+ Ok(n) => {
+ self.cur += n as u64;
+ Poll::Ready(Ok(n))
+ }
+ Err(err) => Poll::Ready(Err(err)),
+ };
+ }
+
+ let (read_start, read_end) = (self.cur as usize, self.cur as usize + dst.len());
+
+ if let Some((buf_start, buf_end)) = self.buffer_range() {
+ if buf_start == buf_end && buf_start == self.cur as usize {
+ self.clear_buffer();
+ return Poll::Ready(Ok(0));
+ }
+ // Hit the buffer.
+ // +---------------+
+ // | Buffer Data |
+ // ----+^--------------^-----
+ // | |
+ // | |
+ // cur cur + dst.len()
+ if buf_start <= read_start && read_end <= buf_end {
+ // Invariant: buf.len() <= cap
+ let offset = self.cur as usize - buf_start;
+ let amt = min(buf_end - self.cur as usize, dst.len());
+
+ dst.put_slice(&self.buf[offset..offset + amt]);
+ self.cur = read_end as u64;
+ return Poll::Ready(Ok(amt));
+ } else if buf_start <= read_start && read_start < buf_end {
+ // Hit part of buffer.
+ // +---------------+
+ // | Buffer Data |
+ // ----+--------^----------^--
+ // | |
+ // | |
+ // cur cur + dst.len()
+
+ let offset = self.cur as usize - buf_start;
+ let rem = min(buf_end - self.cur as usize, dst.len());
+
+ dst.put_slice(&self.buf[offset..offset + rem]);
+
+ if let Err(err) = ready!(self.poll_seek(cx, SeekFrom::Start(buf_end as u64))) {
+ return Poll::Ready(Err(err));
+ }
+ if self.has_reach_end() {
+ return Poll::Ready(Ok(rem));
+ }
+ } else if let Err(err) = ready!(self.poll_seek(cx, SeekFrom::Start(self.cur))) {
+ return Poll::Ready(Err(err));
+ }
+ }
+
+ // Continue read
+ match ready!(self.poll_fill_buf(cx)) {
+ Ok(_) => self.poll_read(cx, dst),
+ Err(err) => Poll::Ready(Err(err)),
+ }
+ }
+
+ fn poll_seek(&mut self, cx: &mut Context<'_>, pos: SeekFrom) -> Poll<Result<u64>> {
+ match ready!(self.r.poll_seek(cx, pos)) {
+ Ok(cur) => {
+ self.cur = cur;
+
+ Poll::Ready(Ok(cur))
+ }
+ Err(err) => Poll::Ready(Err(err)),
+ }
+ }
+
+ fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<Bytes>>> {
Review Comment:
poll_next should respect buffer.
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,457 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::{Bytes, BytesMut};
+
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
+
+ buf: BytesMut,
+ cap: usize,
+ /// Indicate buffered data range start.
+ /// `None` stand for no buffered data.
+ buf_start: Option<usize>,
+}
+
+impl<R> BufferReader<R> {
+ /// Create a new [`oio::Reader`] with a buffer.
+ ///
+ /// # Input
+ ///
+ /// The input is an Accessor will may return a seekable reader.
+ pub fn new(r: R, cap: usize) -> BufferReader<R> {
+ BufferReader {
+ r,
+ cur: 0,
+
+ // Lazy allocation.
+ buf: BytesMut::new(),
+ cap,
+ buf_start: None,
+ }
+ }
+
+ /// Returns the capability of buffer.
+ pub fn cap(&self) -> usize {
+ self.cap
+ }
+}
+
+impl<R> BufferReader<R>
+where
+ R: oio::Read,
+{
+ /// Fill the internal buffer.
+ fn poll_fill_buf(&mut self, cx: &mut Context<'_>) -> Poll<Result<usize>> {
+ self.clear_buffer();
+ self.buf.reserve(self.cap);
+
+ if let Err(err) = ready!(self.r.poll_seek(cx, SeekFrom::Start(self.cur))) {
+ return Poll::Ready(Err(err));
+ }
+
+ let mut nread = 0;
+
+ while self.buf.len() < self.buf.capacity() {
+ let dst = self.buf.spare_capacity_mut();
+ let length = dst.len();
+ let mut buf = ReadBuf::uninit(dst);
+
+ // Safety: must initialized.
+ unsafe {
+ buf.assume_init(length);
+ }
+
+ match ready!(self.r.poll_read(cx, buf.initialized_mut())) {
Review Comment:
`poll_fill_buf` doesn't need make sure the buf is fully filled: how many data will be filled is decided by underlying services.
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,457 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::{Bytes, BytesMut};
+
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
Review Comment:
Maybe we don't need to track the `cur` of underlying read? We just need a `pos` like [BufReader](https://docs.rs/tokio/latest/src/tokio/io/util/buf_reader.rs.html).
- If `pos == 0`, we can forward the seek to underlying directly.
- If `pos > 0`, we can calculate the correct `SeekFrom` for seek.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(oio::read): implement the async buffer reader [incubator-opendal]
Posted by "WenyXu (via GitHub)" <gi...@apache.org>.
WenyXu commented on code in PR #3811:
URL: https://github.com/apache/incubator-opendal/pull/3811#discussion_r1435752269
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,457 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::{Bytes, BytesMut};
+
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
+
+ buf: BytesMut,
+ cap: usize,
+ /// Indicate buffered data range start.
+ /// `None` stand for no buffered data.
+ buf_start: Option<usize>,
+}
+
+impl<R> BufferReader<R> {
+ /// Create a new [`oio::Reader`] with a buffer.
+ ///
+ /// # Input
+ ///
+ /// The input is an Accessor will may return a seekable reader.
+ pub fn new(r: R, cap: usize) -> BufferReader<R> {
+ BufferReader {
+ r,
+ cur: 0,
+
+ // Lazy allocation.
+ buf: BytesMut::new(),
+ cap,
+ buf_start: None,
+ }
+ }
+
+ /// Returns the capability of buffer.
+ pub fn cap(&self) -> usize {
+ self.cap
+ }
+}
+
+impl<R> BufferReader<R>
+where
+ R: oio::Read,
+{
+ /// Fill the internal buffer.
+ fn poll_fill_buf(&mut self, cx: &mut Context<'_>) -> Poll<Result<usize>> {
+ self.clear_buffer();
+ self.buf.reserve(self.cap);
+
+ if let Err(err) = ready!(self.r.poll_seek(cx, SeekFrom::Start(self.cur))) {
+ return Poll::Ready(Err(err));
+ }
+
+ let mut nread = 0;
+
+ while self.buf.len() < self.buf.capacity() {
+ let dst = self.buf.spare_capacity_mut();
+ let length = dst.len();
+ let mut buf = ReadBuf::uninit(dst);
+
+ // Safety: must initialized.
+ unsafe {
+ buf.assume_init(length);
+ }
+
+ match ready!(self.r.poll_read(cx, buf.initialized_mut())) {
Review Comment:
Yes, it breaks the loop if the number of read bytes is equal to zero.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(oio::read): implement the async buffer reader [incubator-opendal]
Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #3811:
URL: https://github.com/apache/incubator-opendal/pull/3811#discussion_r1435945748
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,457 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::{Bytes, BytesMut};
+
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
+
+ buf: BytesMut,
+ cap: usize,
+ /// Indicate buffered data range start.
+ /// `None` stand for no buffered data.
+ buf_start: Option<usize>,
+}
+
+impl<R> BufferReader<R> {
+ /// Create a new [`oio::Reader`] with a buffer.
+ ///
+ /// # Input
+ ///
+ /// The input is an Accessor will may return a seekable reader.
+ pub fn new(r: R, cap: usize) -> BufferReader<R> {
+ BufferReader {
+ r,
+ cur: 0,
+
+ // Lazy allocation.
+ buf: BytesMut::new(),
+ cap,
+ buf_start: None,
+ }
+ }
+
+ /// Returns the capability of buffer.
+ pub fn cap(&self) -> usize {
+ self.cap
+ }
+}
+
+impl<R> BufferReader<R>
+where
+ R: oio::Read,
+{
+ /// Fill the internal buffer.
+ fn poll_fill_buf(&mut self, cx: &mut Context<'_>) -> Poll<Result<usize>> {
+ self.clear_buffer();
+ self.buf.reserve(self.cap);
+
+ if let Err(err) = ready!(self.r.poll_seek(cx, SeekFrom::Start(self.cur))) {
+ return Poll::Ready(Err(err));
+ }
+
+ let mut nread = 0;
+
+ while self.buf.len() < self.buf.capacity() {
+ let dst = self.buf.spare_capacity_mut();
+ let length = dst.len();
+ let mut buf = ReadBuf::uninit(dst);
+
+ // Safety: must initialized.
+ unsafe {
+ buf.assume_init(length);
+ }
+
+ match ready!(self.r.poll_read(cx, buf.initialized_mut())) {
Review Comment:
tokio buf reader implement in this way: https://docs.rs/tokio/latest/src/tokio/io/util/buf_reader.rs.html#122-139
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(oio::read): implement the async buffer reader [incubator-opendal]
Posted by "WenyXu (via GitHub)" <gi...@apache.org>.
WenyXu commented on code in PR #3811:
URL: https://github.com/apache/incubator-opendal/pull/3811#discussion_r1435751773
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,457 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::{Bytes, BytesMut};
+
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
Review Comment:
> Maybe we don't need to track the `cur` of underlying read? We just need a `pos` like [BufReader](https://docs.rs/tokio/latest/src/tokio/io/util/buf_reader.rs.html).
>
> * If `pos == 0`, we can forward the seek to underlying directly.
> * If `pos > 0`, we can calculate the correct `SeekFrom` for seek.
I’m going to check this.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(oio::read): implement the async buffer reader [incubator-opendal]
Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #3811:
URL: https://github.com/apache/incubator-opendal/pull/3811#discussion_r1435770708
##########
core/src/raw/oio/read/buffer_reader.rs:
##########
@@ -0,0 +1,457 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::BufMut;
+use bytes::{Bytes, BytesMut};
+
+use tokio::io::ReadBuf;
+
+use std::cmp::min;
+use std::io::SeekFrom;
+
+use std::task::ready;
+use std::task::Context;
+use std::task::Poll;
+
+use crate::raw::*;
+use crate::*;
+
+/// [BufferReader] allows the underlying reader to fetch data at the buffer's size
+/// and is used to amortize the IO's overhead.
+pub struct BufferReader<R> {
+ r: R,
+ cur: u64,
+
+ buf: BytesMut,
+ cap: usize,
+ /// Indicate buffered data range start.
+ /// `None` stand for no buffered data.
+ buf_start: Option<usize>,
+}
+
+impl<R> BufferReader<R> {
+ /// Create a new [`oio::Reader`] with a buffer.
+ ///
+ /// # Input
+ ///
+ /// The input is an Accessor will may return a seekable reader.
+ pub fn new(r: R, cap: usize) -> BufferReader<R> {
+ BufferReader {
+ r,
+ cur: 0,
+
+ // Lazy allocation.
+ buf: BytesMut::new(),
+ cap,
+ buf_start: None,
+ }
+ }
+
+ /// Returns the capability of buffer.
+ pub fn cap(&self) -> usize {
+ self.cap
+ }
+}
+
+impl<R> BufferReader<R>
+where
+ R: oio::Read,
+{
+ /// Fill the internal buffer.
+ fn poll_fill_buf(&mut self, cx: &mut Context<'_>) -> Poll<Result<usize>> {
+ self.clear_buffer();
+ self.buf.reserve(self.cap);
+
+ if let Err(err) = ready!(self.r.poll_seek(cx, SeekFrom::Start(self.cur))) {
+ return Poll::Ready(Err(err));
+ }
+
+ let mut nread = 0;
+
+ while self.buf.len() < self.buf.capacity() {
+ let dst = self.buf.spare_capacity_mut();
+ let length = dst.len();
+ let mut buf = ReadBuf::uninit(dst);
+
+ // Safety: must initialized.
+ unsafe {
+ buf.assume_init(length);
+ }
+
+ match ready!(self.r.poll_read(cx, buf.initialized_mut())) {
Review Comment:
> Yes, it breaks the loop if the number of read bytes is equal to zero.
I mean that we should return as soon as possible once `poll_read` indicates there's data available instead of trying to fill the buffer entirely.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org