blockless_car/
section.rs

1#![allow(unused)]
2use std::io::{Read, Seek, SeekFrom};
3
4use cid::Cid;
5use ipld::Block;
6
7use crate::{error::CarError, Ipld};
8
9#[derive(Debug, Clone)]
10pub struct Section {
11    cid: Cid,
12    pos: u64,
13    len: usize,
14}
15
16impl Section {
17    pub fn new(cid: Cid, pos: u64, len: usize) -> Self {
18        Self { cid, pos, len }
19    }
20
21    #[inline]
22    pub fn read_data<T>(&self, mut seeker: T) -> Result<Vec<u8>, CarError>
23    where
24        T: Seek + Read,
25    {
26        seeker.seek(SeekFrom::Start(self.pos))?;
27        let mut buf = vec![0u8; self.len];
28        seeker.read_exact(&mut buf)?;
29        Ok(buf)
30    }
31
32    #[inline]
33    pub fn ipld<T>(&mut self, mut seeker: T) -> Result<Ipld, CarError>
34    where
35        T: Seek + Read,
36    {
37        let data = self.read_data(&mut seeker)?;
38        let block = Block::<ipld::DefaultParams>::new(self.cid, data).unwrap();
39        block.ipld().map_err(|e| CarError::Parsing(e.to_string()))
40    }
41
42    #[inline(always)]
43    pub fn cid(&self) -> Cid {
44        self.cid
45    }
46
47    #[inline(always)]
48    pub fn pos(&self) -> u64 {
49        self.pos
50    }
51
52    #[allow(clippy::len_without_is_empty)]
53    #[inline(always)]
54    pub fn len(&self) -> usize {
55        self.len
56    }
57}