Skip to main content

meta_language/
link_network_binary.rs

1//! Complete network-state binary archives under the shared interoperable profile.
2//! The generated JavaScript algorithm owns framing, bounds and byte decisions;
3//! this adapter supplies native UTF-8 strings and link-network objects.
4
5use std::error::Error;
6use std::fmt;
7use std::sync::{Arc, OnceLock};
8
9use serde_json::Value;
10
11use crate::link_network::Link;
12use crate::link_network_binary_rules::accept_link_network_binary_integer;
13use crate::translation::link_network_binary_buffer_rules::transcode_link_network_binary;
14use crate::{
15    ByteRange, LinkFlags, LinkId, LinkMetadata, LinkNetwork, LinkType, Point, SourceSpan,
16    read_structured_data_lino,
17};
18
19/// Failure to preserve a network under the selected binary profile.
20#[derive(Clone, Debug, PartialEq, Eq)]
21pub struct BinaryLinksError(String);
22
23impl fmt::Display for BinaryLinksError {
24    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
25        write!(formatter, "binary links snapshot: {}", self.0)
26    }
27}
28impl Error for BinaryLinksError {}
29
30/// Resource bounds for complete binary network reconstruction.
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub struct BinaryLinksOptions {
33    /// Maximum link records and entries in each exact cache section.
34    pub record_limit: usize,
35    /// Maximum archive bytes and intermediate flat-field entries.
36    pub byte_limit: usize,
37}
38
39fn schema() -> &'static Value {
40    static SCHEMA: OnceLock<Value> = OnceLock::new();
41    SCHEMA.get_or_init(|| {
42        read_structured_data_lino(include_str!("data/link-network-binary-schema.lino"))
43            .expect("the packaged binary network schema is valid")
44    })
45}
46
47impl Default for BinaryLinksOptions {
48    fn default() -> Self {
49        Self {
50            record_limit: usize::try_from(
51                schema()["recordLimit"]
52                    .as_u64()
53                    .expect("record limit is an integer"),
54            )
55            .expect("record limit fits usize"),
56            byte_limit: usize::try_from(
57                schema()["byteLimit"]
58                    .as_u64()
59                    .expect("byte limit is an integer"),
60            )
61            .expect("byte limit fits usize"),
62        }
63    }
64}
65
66fn fail(message: impl Into<String>) -> BinaryLinksError {
67    BinaryLinksError(message.into())
68}
69
70// Only integers in the exact Number domain cross the portable numeric boundary.
71#[allow(clippy::cast_precision_loss)]
72fn number(value: u64) -> Result<f64, BinaryLinksError> {
73    if value > 9_007_199_254_740_991 {
74        return Err(fail(
75            "unsafe integer is outside the interoperable Number profile",
76        ));
77    }
78    Ok(value as f64)
79}
80
81fn length(value: usize) -> Result<f64, BinaryLinksError> {
82    number(u64::try_from(value).map_err(|_| fail("length does not fit the interoperable profile"))?)
83}
84
85fn append_text(fields: &mut Vec<f64>, value: &str) -> Result<(), BinaryLinksError> {
86    fields.push(length(value.len())?);
87    fields.extend(value.bytes().map(f64::from));
88    Ok(())
89}
90
91fn append_optional_text(
92    fields: &mut Vec<f64>,
93    value: Option<&str>,
94) -> Result<(), BinaryLinksError> {
95    fields.push(f64::from(u8::from(value.is_some())));
96    if let Some(value) = value {
97        append_text(fields, value)?;
98    }
99    Ok(())
100}
101
102const fn type_code(value: Option<LinkType>) -> u8 {
103    match value {
104        None => 0,
105        Some(LinkType::Link) => 1,
106        Some(LinkType::Reference) => 2,
107        Some(LinkType::Relation) => 3,
108        Some(LinkType::Language) => 4,
109        Some(LinkType::Grammar) => 5,
110        Some(LinkType::Type) => 6,
111        Some(LinkType::Concept) => 7,
112        Some(LinkType::Syntax) => 8,
113        Some(LinkType::Field) => 9,
114        Some(LinkType::Trivia) => 10,
115        Some(LinkType::Token) => 11,
116        Some(LinkType::Document) => 12,
117        Some(LinkType::Semantic) => 13,
118        Some(LinkType::Region) => 14,
119        Some(LinkType::Object) => 15,
120    }
121}
122
123const fn types() -> [Option<LinkType>; 16] {
124    [
125        None,
126        Some(LinkType::Link),
127        Some(LinkType::Reference),
128        Some(LinkType::Relation),
129        Some(LinkType::Language),
130        Some(LinkType::Grammar),
131        Some(LinkType::Type),
132        Some(LinkType::Concept),
133        Some(LinkType::Syntax),
134        Some(LinkType::Field),
135        Some(LinkType::Trivia),
136        Some(LinkType::Token),
137        Some(LinkType::Document),
138        Some(LinkType::Semantic),
139        Some(LinkType::Region),
140        Some(LinkType::Object),
141    ]
142}
143
144fn transcode(
145    fields: &[f64],
146    binary: bool,
147    options: BinaryLinksOptions,
148) -> Result<String, BinaryLinksError> {
149    let record_limit = length(options.record_limit)?;
150    let byte_limit = length(options.byte_limit)?;
151    if !accept_link_network_binary_integer(record_limit)
152        || !accept_link_network_binary_integer(byte_limit)
153    {
154        return Err(fail("invalid resource limits"));
155    }
156    let result =
157        transcode_link_network_binary(fields, binary, record_limit, byte_limit).to_string();
158    if result.starts_with('-') {
159        let mut pieces = result.split(',');
160        let code = pieces.next().unwrap_or("-1").trim_start_matches('-');
161        let offset = pieces.next().unwrap_or("0");
162        let message = schema()["errors"][code]
163            .as_str()
164            .unwrap_or("unknown profile failure");
165        return Err(fail(format!(
166            "{message} at {} {offset}",
167            if binary { "byte" } else { "field" }
168        )));
169    }
170    Ok(result)
171}
172
173/// Encode every graph link and exact lookup/selection/allocation state.
174///
175/// # Errors
176/// Returns a precise error for unsafe integers, resource bounds or unsupported
177/// states in the shared safe-integer and scalar-Unicode profile.
178pub fn encode_link_network_binary(
179    network: &LinkNetwork,
180    options: BinaryLinksOptions,
181) -> Result<Vec<u8>, BinaryLinksError> {
182    let mut fields = vec![2.0, number(network.next_id)?, length(network.links.len())?];
183    if network.links.len() > options.record_limit {
184        return Err(fail("record resource limit exceeded"));
185    }
186    for link in network.links() {
187        fields.push(number(link.id().as_u64())?);
188        fields.push(length(link.references().len())?);
189        for reference in link.references() {
190            fields.push(number(reference.as_u64())?);
191        }
192        let value = link.metadata();
193        let flags = value.flags();
194        let bits = u8::from(flags.is_error())
195            | (u8::from(flags.has_error()) << 1)
196            | (u8::from(flags.is_missing()) << 2)
197            | (u8::from(flags.is_extra()) << 3);
198        fields.extend([
199            1.0,
200            f64::from(type_code(value.link_type())),
201            f64::from(u8::from(value.is_named())),
202            f64::from(bits),
203            f64::from(u8::from(
204                value
205                    .term()
206                    .is_some_and(|term| network.find_term(term) == Some(link.id())),
207            )),
208            0.0,
209        ]);
210        for text in [value.term(), value.definition(), value.language()] {
211            append_optional_text(&mut fields, text)?;
212        }
213        fields.push(f64::from(u8::from(value.span().is_some())));
214        if let Some(span) = value.span() {
215            for component in [
216                span.byte_range().start(),
217                span.byte_range().end(),
218                span.start_point().row(),
219                span.start_point().column(),
220                span.end_point().row(),
221                span.end_point().column(),
222            ] {
223                fields.push(length(component)?);
224            }
225        }
226        if fields.len() > options.byte_limit {
227            return Err(fail("byte resource limit exceeded"));
228        }
229    }
230    fields.push(length(network.terms.len())?);
231    for (term, identity) in &network.terms {
232        append_text(&mut fields, term)?;
233        fields.push(number(identity.as_u64())?);
234    }
235    fields.push(length(network.concept_syntax.len())?);
236    for ((concept, language), syntax) in &network.concept_syntax {
237        if concept.contains('\0') || language.contains('\0') {
238            return Err(fail(
239                "ambiguous concept-syntax cache key is outside the interoperable profile",
240            ));
241        }
242        for text in [concept.as_ref(), language.as_ref(), syntax.as_ref()] {
243            append_text(&mut fields, text)?;
244        }
245    }
246    let encoded = transcode(&fields, false, options)?;
247    (0..encoded.len())
248        .step_by(2)
249        .map(|offset| {
250            u8::from_str_radix(&encoded[offset..offset + 2], 16)
251                .map_err(|_| fail("generated byte framing is not hexadecimal"))
252        })
253        .collect()
254}
255
256struct Fields {
257    values: Vec<u64>,
258    cursor: usize,
259}
260impl Fields {
261    fn number(&mut self) -> u64 {
262        let value = self.values[self.cursor];
263        self.cursor += 1;
264        value
265    }
266    fn size(&mut self) -> Result<usize, BinaryLinksError> {
267        usize::try_from(self.number()).map_err(|_| fail("value does not fit usize"))
268    }
269    fn text(&mut self) -> Result<String, BinaryLinksError> {
270        let length = self.size()?;
271        let bytes = self.values[self.cursor..self.cursor + length]
272            .iter()
273            .map(|value| u8::try_from(*value).map_err(|_| fail("invalid string byte")))
274            .collect::<Result<Vec<_>, _>>()?;
275        self.cursor += length;
276        String::from_utf8(bytes).map_err(|_| fail("metadata or cache string is not valid UTF-8"))
277    }
278    fn optional_text(&mut self) -> Result<Option<String>, BinaryLinksError> {
279        if self.number() == 0 {
280            Ok(None)
281        } else {
282            self.text().map(Some)
283        }
284    }
285}
286
287/// Reload exact network state without source parsing or token reconstruction.
288/// Legacy version 1 restores its graph and recorded term registrations only.
289///
290/// # Errors
291/// Returns a precise error for malformed framing, unsupported profile values,
292/// invalid UTF-8, duplicate state keys or exceeded resource limits.
293pub fn decode_link_network_binary(
294    bytes: &[u8],
295    options: BinaryLinksOptions,
296) -> Result<LinkNetwork, BinaryLinksError> {
297    if bytes.len() > options.byte_limit {
298        return Err(fail("byte resource limit exceeded"));
299    }
300    let input = bytes
301        .iter()
302        .map(|byte| f64::from(*byte))
303        .collect::<Vec<_>>();
304    let decoded = transcode(&input, true, options)?;
305    let values = decoded
306        .trim_end_matches(',')
307        .split(',')
308        .map(|value| {
309            value
310                .parse::<u64>()
311                .map_err(|_| fail("generated numeric framing is invalid"))
312        })
313        .collect::<Result<Vec<_>, _>>()?;
314    let mut fields = Fields { values, cursor: 0 };
315    let version = fields.number();
316    let next_identity = if version == 2 { fields.number() } else { 1 };
317    let count = fields.size()?;
318    let mut network = LinkNetwork::new();
319    for _ in 0..count {
320        let identity = LinkId::from_u64(fields.number());
321        let arity = fields.size()?;
322        let references = (0..arity)
323            .map(|_| LinkId::from_u64(fields.number()))
324            .collect::<Vec<_>>();
325        fields.number(); // Shared scanner checked the metadata version.
326        let link_type = types()[fields.size()?];
327        let named = fields.number() == 1;
328        let bits = fields.number();
329        let registered = fields.number() == 1;
330        fields.number(); // Shared scanner rejected tombstones.
331        let term = fields.optional_text()?;
332        let definition = fields.optional_text()?;
333        let language = fields.optional_text()?;
334        let span = if fields.number() == 1 {
335            Some(SourceSpan::new(
336                ByteRange::new(fields.size()?, fields.size()?),
337                Point::new(fields.size()?, fields.size()?),
338                Point::new(fields.size()?, fields.size()?),
339            ))
340        } else {
341            None
342        };
343        let mut metadata = LinkMetadata::new().with_named(named);
344        if let Some(value) = link_type {
345            metadata = metadata.with_link_type(value);
346        }
347        if let Some(value) = term {
348            metadata = metadata.with_term(value);
349        }
350        if let Some(value) = definition {
351            metadata = metadata.with_definition(value);
352        }
353        if let Some(value) = language {
354            metadata = metadata.with_language(value);
355        }
356        if let Some(value) = span {
357            metadata = metadata.with_span(value);
358        }
359        let mut flags = LinkFlags::clean();
360        if bits & 1 != 0 {
361            flags = flags.with_error();
362        }
363        if bits & 2 != 0 {
364            flags = flags.with_containing_error();
365        }
366        if bits & 4 != 0 {
367            flags = flags.with_missing();
368        }
369        if bits & 8 != 0 {
370            flags = flags.with_extra();
371        }
372        metadata = metadata.with_flags(flags);
373        if version == 1
374            && registered
375            && let Some(term) = metadata.term()
376        {
377            network.terms.insert(Arc::from(term), identity);
378        }
379        network.next_id = network.next_id.max(identity.as_u64() + 1);
380        network.links.insert(
381            identity,
382            Arc::new(Link {
383                id: identity,
384                references: Arc::from(references),
385                metadata,
386            }),
387        );
388    }
389    if version == 2 {
390        let terms = fields.size()?;
391        for _ in 0..terms {
392            let key: Arc<str> = Arc::from(fields.text()?);
393            let identity = LinkId::from_u64(fields.number());
394            if network.terms.insert(key, identity).is_some() {
395                return Err(fail("duplicate term-cache key"));
396            }
397        }
398        let syntax = fields.size()?;
399        for _ in 0..syntax {
400            let concept: Arc<str> = Arc::from(fields.text()?);
401            let language: Arc<str> = Arc::from(fields.text()?);
402            let value: Arc<str> = Arc::from(fields.text()?);
403            if concept.contains('\0') || language.contains('\0') {
404                return Err(fail(
405                    "ambiguous concept-syntax cache key is outside the interoperable profile",
406                ));
407            }
408            if network
409                .concept_syntax
410                .insert((concept, language), value)
411                .is_some()
412            {
413                return Err(fail("duplicate selected-syntax key"));
414            }
415        }
416        network.next_id = next_identity;
417    }
418    Ok(network)
419}