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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to