puffin/
partial_reader.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15mod r#async;
16
17use pin_project::pin_project;
18
19/// `PartialReader` to perform synchronous or asynchronous reads on a portion of a resource.
20#[pin_project]
21pub struct PartialReader<R> {
22    /// offset of the portion in the resource
23    offset: u64,
24
25    /// size of the portion in the resource
26    size: u64,
27
28    /// Resource for the portion.
29    /// The `offset` and `size` fields are used to determine the slice of `source` to read.
30    #[pin]
31    source: R,
32}
33
34impl<R> PartialReader<R> {
35    /// Creates a new `PartialReader` for the given resource.
36    pub fn new(source: R, offset: u64, size: u64) -> Self {
37        Self {
38            offset,
39            size,
40            source,
41        }
42    }
43
44    /// Returns the size of the portion in portion.
45    pub fn size(&self) -> u64 {
46        self.size
47    }
48
49    /// Returns whether the portion is empty.
50    pub fn is_empty(&self) -> bool {
51        self.size == 0
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use std::io::Cursor;
58
59    use super::*;
60
61    #[test]
62    fn is_empty_returns_true_for_zero_length_blob() {
63        let data: Vec<u8> = (0..100).collect();
64        let reader = PartialReader::new(Cursor::new(data), 10, 0);
65        assert!(reader.is_empty());
66    }
67
68    #[test]
69    fn is_empty_returns_false_for_non_zero_length_blob() {
70        let data: Vec<u8> = (0..100).collect();
71        let reader = PartialReader::new(Cursor::new(data), 10, 30);
72        assert!(!reader.is_empty());
73    }
74}