Skip to main content

heddle_pack/store/pack/
inventory.rs

1// SPDX-License-Identifier: Apache-2.0
2use std::{fs::File, path::Path};
3
4use bytes::Bytes;
5use tempfile::NamedTempFile;
6
7use super::{PackIndex, PackObjectId};
8use crate::store::Result;
9
10/// Owned disk-backed installed identities. The retained index survives removal
11/// of the transfer's staging directory and is deleted when this value drops.
12#[derive(Debug)]
13pub struct PackInventory {
14    index: PackIndex,
15    _file: NamedTempFile,
16    _scratch: super::ScratchDir,
17}
18impl PackInventory {
19    pub fn copy_from_index(index_path: &Path, scratch_root: &Path) -> Result<Self> {
20        let scratch = super::ScratchDir::new(scratch_root, "pack-inventory-")?;
21        let mut file = NamedTempFile::new_in(scratch.path())?;
22        std::io::copy(&mut File::open(index_path)?, file.as_file_mut())?;
23        let bytes = Bytes::from_owner(unsafe { memmap2::MmapOptions::new().map(file.as_file())? });
24        Ok(Self {
25            index: PackIndex::from_owned_bytes(bytes)?,
26            _file: file,
27            _scratch: scratch,
28        })
29    }
30    pub fn len(&self) -> usize {
31        self.index.len()
32    }
33    pub fn is_empty(&self) -> bool {
34        self.index.is_empty()
35    }
36    pub fn contains(&self, id: &PackObjectId) -> Result<bool> {
37        Ok(self.index.find(id)?.is_some())
38    }
39    pub fn ids(&self) -> impl Iterator<Item = Result<PackObjectId>> + '_ {
40        self.index.iter().map(|entry| entry.map(|entry| entry.id))
41    }
42}