taubyte_sdk/storage/content/
read.rs

1use std::io::Read;
2
3use crate::{errno::Errno, storage::Content};
4
5use super::{imports, ReadOnlyContent, ReadWriteContent};
6
7impl Read for Content {
8    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
9        if self.consumed {
10            self.consumed = false;
11            return Ok(0);
12        }
13
14        let mut count: usize = 0;
15        let err0 =
16            unsafe { imports::contentReadFile(self.id, buf.as_mut_ptr(), buf.len(), &mut count) };
17        if err0.is_errno(Errno::ErrorEOF) {
18            self.consumed = true;
19            // TODO, should we close here?
20            Ok(count)
21        } else if err0.is_err() {
22            Err(std::io::Error::new(
23                std::io::ErrorKind::Other,
24                format!("Reading content failed with: {}", err0),
25            ))
26        } else {
27            Ok(count)
28        }
29    }
30}
31
32impl Read for ReadWriteContent {
33    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
34        self.content.read(buf)
35    }
36}
37
38impl Read for ReadOnlyContent {
39    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
40        self.content.read(buf)
41    }
42}
43
44#[cfg(test)]
45pub mod test {
46    use std::io::Read;
47
48    use crate::storage::Content;
49
50    pub static EXPECTED_READ: &str = "Hello, world!";
51
52    #[test]
53    fn read() {
54        let mut content = Content::new().unwrap_or_else(|err| {
55            panic!("{}", err);
56        });
57
58        let mut buffer = String::new();
59        content.read_to_string(&mut buffer).unwrap_or_else(|err| {
60            panic!("{}", err);
61        });
62
63        assert_eq!(buffer, EXPECTED_READ);
64    }
65}
66
67#[cfg(test)]
68#[allow(non_snake_case)]
69pub mod mock {
70    use super::test;
71    use crate::{
72        errno::{Errno, Error},
73        storage::content::new::test as new_test,
74    };
75
76    #[cfg(test)]
77    pub unsafe fn contentReadFile(
78        id: u32,
79        buf_ptr: *const u8,
80        buf_len: usize,
81        count_ptr: *mut usize,
82    ) -> Error {
83        if id != new_test::ID {
84            Errno::ErrorCap.error()
85        } else {
86            let body = test::EXPECTED_READ.as_bytes();
87
88            let buf = std::slice::from_raw_parts_mut(buf_ptr as *mut u8, body.len() as usize);
89            buf.copy_from_slice(body);
90            *count_ptr = body.len();
91
92            if buf_len >= body.len() {
93                Errno::ErrorEOF.error()
94            } else {
95                Errno::ErrorNone.error()
96            }
97        }
98    }
99}