opendal/services/fs/reader.rs
1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::sync::Arc;
19
20use tokio::io::AsyncReadExt;
21use tokio::io::ReadBuf;
22
23use super::core::*;
24use crate::raw::*;
25use crate::*;
26
27pub struct FsReader<F> {
28 core: Arc<FsCore>,
29 f: F,
30 read: usize,
31 size: usize,
32 buf_size: usize,
33}
34
35impl<F> FsReader<F> {
36 pub fn new(core: Arc<FsCore>, f: F, size: usize) -> Self {
37 Self {
38 core,
39 f,
40 read: 0,
41 size,
42 // Use 2 MiB as default value.
43 buf_size: 2 * 1024 * 1024,
44 }
45 }
46}
47
48impl oio::Read for FsReader<tokio::fs::File> {
49 async fn read(&mut self) -> Result<Buffer> {
50 if self.read >= self.size {
51 return Ok(Buffer::new());
52 }
53
54 let mut bs = self.core.buf_pool.get();
55 bs.reserve(self.buf_size);
56
57 let size = (self.size - self.read).min(self.buf_size);
58 let buf = &mut bs.spare_capacity_mut()[..size];
59 let mut read_buf: ReadBuf = ReadBuf::uninit(buf);
60
61 // SAFETY: Read at most `limit` bytes into `read_buf`.
62 unsafe {
63 read_buf.assume_init(size);
64 }
65
66 let n = self
67 .f
68 .read_buf(&mut read_buf)
69 .await
70 .map_err(new_std_io_error)?;
71 self.read += n;
72
73 // Safety: We make sure that bs contains `n` more bytes.
74 let filled = read_buf.filled().len();
75 unsafe { bs.set_len(filled) }
76
77 let frozen = bs.split().freeze();
78 // Return the buffer to the pool.
79 self.core.buf_pool.put(bs);
80
81 Ok(Buffer::from(frozen))
82 }
83}