agentic_codebase/format/mmap.rs
1//! Memory-mapped file access for `.acb` files.
2//!
3//! Provides zero-copy access to `.acb` data using OS-level memory mapping.
4//! This is the preferred access method for large files.
5
6use std::path::Path;
7
8use crate::graph::CodeGraph;
9use crate::types::{AcbError, AcbResult};
10
11use super::reader::AcbReader;
12
13/// A memory-mapped view of an `.acb` file.
14///
15/// This wraps the mmap and provides access to the graph data
16/// without loading the entire file into heap memory.
17pub struct MappedCodeGraph {
18 _mmap: memmap2::Mmap,
19 graph: CodeGraph,
20}
21
22impl MappedCodeGraph {
23 /// Open and memory-map an `.acb` file.
24 ///
25 /// The file is mapped read-only. The graph is parsed from the mapped data.
26 ///
27 /// # Safety
28 ///
29 /// This uses `unsafe` internally for mmap. The file must not be modified
30 /// while the mapping is active.
31 pub fn open(path: &Path) -> AcbResult<Self> {
32 if !path.exists() {
33 return Err(AcbError::PathNotFound(path.to_path_buf()));
34 }
35
36 let file = std::fs::File::open(path)?;
37 // SAFETY: We only map read-only, and we don't expose the raw mapping.
38 // The caller must ensure the file is not modified while mapped.
39 let mmap = unsafe { memmap2::Mmap::map(&file)? };
40
41 let graph = AcbReader::read_from_data(&mmap)?;
42
43 Ok(Self { _mmap: mmap, graph })
44 }
45
46 /// Get a reference to the parsed code graph.
47 pub fn graph(&self) -> &CodeGraph {
48 &self.graph
49 }
50
51 /// Consume and return the parsed graph (drops the mmap).
52 pub fn into_graph(self) -> CodeGraph {
53 self.graph
54 }
55}