Skip to main content

opendal_core/blocking/read/
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 bytes::BufMut;
19
20use super::BufferIterator;
21use super::StdBytesIterator;
22use super::StdReader;
23use crate::Reader as AsyncReader;
24use crate::*;
25
26/// BlockingReader is designed to read data from given path in an blocking
27/// manner.
28#[derive(Clone)]
29pub struct Reader {
30    handle: tokio::runtime::Handle,
31    inner: Option<AsyncReader>,
32}
33
34impl Reader {
35    /// Create a new blocking reader.
36    ///
37    /// We don't want to expose those details to users so keep this function
38    /// in crate only.
39    pub(crate) fn new(handle: tokio::runtime::Handle, inner: AsyncReader) -> Self {
40        Reader {
41            handle,
42            inner: Some(inner),
43        }
44    }
45
46    /// Read give range from reader into [`Buffer`].
47    ///
48    /// This operation is zero-copy, which means it keeps the [`bytes::Bytes`] returned by underlying
49    /// storage services without any extra copy or intensive memory allocations.
50    ///
51    /// # Notes
52    ///
53    /// - Buffer length smaller than range means we have reached the end of file.
54    pub fn read(&self, range: impl Into<BytesRange>) -> Result<Buffer> {
55        let inner = self
56            .inner
57            .as_ref()
58            .ok_or_else(|| Error::new(ErrorKind::Unexpected, "reader has been dropped"))?;
59        self.handle.block_on(inner.read(range))
60    }
61
62    ///
63    /// This operation will copy and write bytes into given [`BufMut`]. Allocation happens while
64    /// [`BufMut`] doesn't have enough space.
65    ///
66    /// # Notes
67    ///
68    /// - Returning length smaller than range means we have reached the end of file.
69    pub fn read_into(&self, buf: &mut impl BufMut, range: impl Into<BytesRange>) -> Result<usize> {
70        let inner = self
71            .inner
72            .as_ref()
73            .ok_or_else(|| Error::new(ErrorKind::Unexpected, "reader has been dropped"))?;
74        self.handle.block_on(inner.read_into(buf, range))
75    }
76
77    /// Create a buffer iterator to read specific range from given reader.
78    pub fn into_iterator(mut self, range: impl Into<BytesRange>) -> Result<BufferIterator> {
79        let inner = self
80            .inner
81            .take()
82            .ok_or_else(|| Error::new(ErrorKind::Unexpected, "reader has been dropped"))?;
83        let iter = self.handle.block_on(inner.into_stream(range))?;
84
85        Ok(BufferIterator::new(self.handle.clone(), iter))
86    }
87
88    /// Convert reader into [`StdReader`] which implements [`futures::AsyncRead`],
89    /// [`futures::AsyncSeek`] and [`futures::AsyncBufRead`].
90    #[inline]
91    pub fn into_std_read(mut self, range: impl Into<BytesRange>) -> Result<StdReader> {
92        let inner = self
93            .inner
94            .take()
95            .ok_or_else(|| Error::new(ErrorKind::Unexpected, "reader has been dropped"))?;
96
97        let r = self.handle.block_on(inner.into_futures_async_read(range))?;
98
99        Ok(StdReader::new(self.handle.clone(), r))
100    }
101
102    /// Convert reader into [`StdBytesIterator`] which implements [`Iterator`].
103    #[inline]
104    pub fn into_bytes_iterator(mut self, range: impl Into<BytesRange>) -> Result<StdBytesIterator> {
105        let inner = self
106            .inner
107            .take()
108            .ok_or_else(|| Error::new(ErrorKind::Unexpected, "reader has been dropped"))?;
109
110        let iter = self.handle.block_on(inner.into_bytes_stream(range))?;
111        Ok(StdBytesIterator::new(self.handle.clone(), iter))
112    }
113}
114
115/// Make sure the inner reader is dropped in async context.
116impl Drop for Reader {
117    fn drop(&mut self) {
118        if let Some(v) = self.inner.take() {
119            self.handle.block_on(async move { drop(v) });
120        }
121    }
122}