ifc_lite_core/
source_bundle.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Immutable bytes and their canonically scanned index. No caller-provided
3//! identity or independently installed index can manufacture a bundle decoder.
4use crate::source_index::{SourceIndex, SourceIndexBuilder};
5use crate::{EntityDecoder, EntityScanner};
6use std::sync::Arc;
7
8/// One immutable source load. Construction scans original bytes, never a UTF-8
9/// rewrite. Cloning the Arc or making a decoder does not rescan or copy inputs.
10pub struct SourceBundle {
11    bytes: Arc<Vec<u8>>,
12    pub(crate) uniform_precision: crate::decoder::UniformContextPrecisionCache,
13    index: SourceIndex,
14    grid_axes: Arc<crate::GridAxisIndex>,
15    pub(crate) styled_items: std::sync::OnceLock<crate::decoder::StyledItemIndexResult>,
16}
17impl SourceBundle {
18    fn paired(bytes: Arc<Vec<u8>>, index: SourceIndex) -> Arc<Self> {
19        Arc::new(Self {
20            bytes,
21            uniform_precision: Default::default(),
22            index,
23            grid_axes: Arc::default(),
24            styled_items: Default::default(),
25        })
26    }
27
28    pub fn new(bytes: Vec<u8>) -> Arc<Self> {
29        Self::scan_with(Arc::new(bytes), |_, _, _, _| {})
30    }
31
32    /// Fuse index construction with an existing canonical classification pass.
33    /// The visitor sees canonical scanner records; it cannot supply index rows.
34    pub fn scan_with(
35        bytes: Arc<Vec<u8>>,
36        mut visit: impl FnMut(u32, &str, usize, usize),
37    ) -> Arc<Self> {
38        let mut index = SourceIndexBuilder::new(bytes.len());
39        let mut scanner = EntityScanner::new(bytes.as_slice());
40        while let Some((id, name, start, end)) = scanner.next_entity() {
41            index.insert(id, (start, end));
42            visit(id, name, start, end);
43        }
44        crate::report_scan_diagnostics(
45            scanner.skipped_oversized_ids(),
46            scanner.malformed_record_start().is_some(),
47        );
48        Self::paired(bytes, index.finish())
49    }
50
51    /// Build the compact browser representation directly with the existing
52    /// canonical index builder, without building or validating a second index.
53    pub fn columnar(bytes: Arc<Vec<u8>>) -> Result<Arc<Self>, crate::SpanBeyondU32> {
54        let index = crate::ColumnarEntityIndex::from_scan(bytes.as_slice())?;
55        Ok(Self::paired(bytes, SourceIndex::Columnar(Arc::new(index))))
56    }
57
58    #[cfg(test)]
59    pub(crate) fn dense_for_certificate_test(bytes: Arc<Vec<u8>>) -> Arc<Self> {
60        let columns = crate::ColumnarEntityIndex::from_scan(bytes.as_slice()).unwrap();
61        let dense = crate::DenseEntityIndex::try_from_columns(
62            columns.ids(),
63            columns.starts(),
64            columns.lengths(),
65        )
66        .unwrap();
67        Self::paired(bytes, SourceIndex::Dense(Arc::new(dense)))
68    }
69
70    /// Validate a delivered compact index against the canonical byte scanner
71    /// once at load. Exact spans and completeness are checked, including the
72    /// canonical last-occurrence rule. Equal IDs or lengths alone prove nothing.
73    pub fn with_columnar_index(
74        bytes: Arc<Vec<u8>>,
75        index: Arc<crate::ColumnarEntityIndex>,
76    ) -> Result<Arc<Self>, SourceIndexMismatch> {
77        let mut scanner = EntityScanner::new(bytes.as_slice());
78        let mut matched = 0;
79        while let Some((id, _, start, end)) = scanner.next_entity() {
80            match index.lookup(id) {
81                Some(span) if span == (start, end) => matched += 1,
82                Some((later, _)) if later > start => {}
83                _ => return Err(SourceIndexMismatch),
84            }
85        }
86        crate::report_scan_diagnostics(
87            scanner.skipped_oversized_ids(),
88            scanner.malformed_record_start().is_some(),
89        );
90        if matched != index.len() {
91            return Err(SourceIndexMismatch);
92        }
93        Ok(Self::paired(bytes, SourceIndex::Columnar(index)))
94    }
95
96    /// Adopt a pristine decoder over the exact owned allocation. Populated or
97    /// externally seeded decoders cannot acquire factory authority. Prewarm a
98    /// factory decoder instead, then move its opaque source caches.
99    pub fn bind_decoder(self: &Arc<Self>, decoder: &mut EntityDecoder<'_>) -> bool {
100        if decoder.entity_index.is_some() || !decoder.can_bind_source() {
101            return false;
102        }
103        if decoder.content.as_ptr() != self.bytes.as_ptr()
104            || decoder.content.len() != self.bytes.len()
105        {
106            return false;
107        }
108        self.index.install(decoder);
109        decoder.set_grid_axis_index(Arc::clone(&self.grid_axes));
110        decoder.source_bundle = Some(Arc::clone(self));
111        decoder.cache_revision = 0;
112        decoder.execution_owner.publish_cache_source(Some(self));
113        true
114    }
115
116    /// Install this bundle's existing index under the borrowed compatibility
117    /// contract: the caller must pair the decoder with these source bytes.
118    /// Retains populated decoded caches and refusal state, without granting
119    /// factory provenance. Use `decoder()` for fresh authenticated workers.
120    pub fn install_compatibility_index(&self, decoder: &mut EntityDecoder<'_>) {
121        self.index.install(decoder);
122    }
123
124    pub fn bytes(&self) -> &[u8] {
125        &self.bytes
126    }
127
128    /// A fresh mutable decoder retains the actual paired allocation. It can
129    /// move to a scoped worker. The context retains the bundle after its caller
130    /// drops the original handle; borrowing that snapshot needs no input copy.
131    pub fn decoder(self: &Arc<Self>) -> EntityDecoder<'_> {
132        let mut decoder = EntityDecoder::new(self.bytes.as_slice());
133        self.index.install(&mut decoder);
134        decoder.set_grid_axis_index(Arc::clone(&self.grid_axes));
135        decoder.source_bundle = Some(Arc::clone(self));
136        decoder.cache_revision = 0;
137        decoder.execution_owner.publish_cache_source(Some(self));
138        decoder
139    }
140
141    /// This compares private factory provenance, not caller-asserted identity,
142    /// length, IDs or an arbitrary prebuilt index's allocation address.
143    pub fn owns_decoder(self: &Arc<Self>, decoder: &EntityDecoder<'_>) -> bool {
144        decoder.cache_revision == 0
145            && decoder
146                .source_bundle
147                .as_ref()
148                .is_some_and(|source| Arc::ptr_eq(self, source))
149    }
150}
151
152/// Delivered spans do not describe the original bytes' complete canonical scan.
153#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub struct SourceIndexMismatch;
155impl std::fmt::Display for SourceIndexMismatch {
156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157        f.write_str("entity index does not match source bytes")
158    }
159}
160impl std::error::Error for SourceIndexMismatch {}
161
162#[cfg(test)]
163#[path = "source_bundle_tests.rs"]
164mod tests;