taubyte_sdk/storage/
cid.rs

1use cid::Cid;
2
3use super::{imports, Storage};
4use crate::{errno::Error, utils::codec};
5
6impl Storage {
7    fn cid_unsafe(&self, name_ptr: *const u8, name_size: usize, cid: *mut u8) -> Error {
8        #[allow(unused_unsafe)]
9        unsafe {
10            imports::storageCid(self.id, name_ptr, name_size, cid)
11        }
12    }
13
14    pub fn cid(&self, name: &str) -> Result<Cid, Box<dyn std::error::Error>> {
15        let mut reader = codec::cid::Reader::new();
16
17        let err = self.cid_unsafe(name.as_ptr(), name.len(), reader.ptr());
18        if err.is_err() {
19            Err(format!("Getting storage cid failed with: {}", err).into())
20        } else {
21            Ok(reader.parse()?)
22        }
23    }
24}
25
26#[cfg(test)]
27pub mod test {
28    use crate::storage::new::test as new_test;
29    use crate::storage::Storage;
30
31    pub static FILE_NAME: &str = "someFile";
32    pub static MOCK_CID: &str = "QmQUXYRNqU2U351aE8mrPFAyqXtKupF9bDspXKLsdkTLGn";
33
34    #[test]
35    fn test_cid() {
36        let storage = Storage::new(new_test::STORAGE_NAME).unwrap_or_else(|err| {
37            panic!("{}", err);
38        });
39
40        let cid = storage.cid(FILE_NAME).unwrap_or_else(|err| {
41            panic!("{}", err);
42        });
43
44        assert_eq!(cid.to_string(), MOCK_CID);
45    }
46}
47
48#[cfg(test)]
49#[allow(non_snake_case)]
50pub mod mock {
51    use crate::{
52        errno::{Errno, Error},
53        storage::new::test as new_test,
54        utils::test as utils,
55    };
56
57    pub fn storageCid(id: u32, name_ptr: *const u8, name_size: usize, cid_ptr: *mut u8) -> Error {
58        use super::test;
59
60        let name = utils::read_string(name_ptr, name_size);
61
62        if id != new_test::STORAGE_ID {
63            Errno::ErrorCap.error()
64        } else if name != test::FILE_NAME {
65            Errno::ErrorCap.error()
66        } else {
67            utils::write_cid_string(test::MOCK_CID, cid_ptr);
68            Errno::ErrorNone.error()
69        }
70    }
71}