Skip to main content

meta_language/
structured_data_links.rs

1//! Inspectable structured values with ordered entries and exact UTF-16 strings.
2//!
3//! The generated shared rules select node kinds and structural shapes; this
4//! adapter supplies native graph identities and JSON interoperability.
5
6use std::collections::{BTreeSet, HashMap, HashSet};
7
8use links_notation::{LiNo, ParserConfig, parse_lino_to_links_with_config};
9use serde_json::{Map, Number, Value};
10
11use crate::structured_data_link_rules::{accept_structured_data_shape, read_structured_data_kind};
12use crate::{LinkFlags, LinkId, LinkMetadata, LinkNetwork, LinkType};
13
14const LANGUAGE: &str = "meta-language structured data";
15const BINARY_DIGIT: &str = "binary digit";
16
17/// Lossless structured data, including ordered keys and unpaired code units.
18#[derive(Clone, Debug, PartialEq)]
19pub enum StructuredDataValue {
20    /// An absent scalar value.
21    Null,
22    /// A logical value.
23    Boolean(bool),
24    /// A finite IEEE 754 binary64 value, including negative zero.
25    Number(f64),
26    /// An exact sequence of UTF-16 code units.
27    String(Vec<u16>),
28    /// Ordered values.
29    Array(Vec<Self>),
30    /// Ordered, distinct keys and their values.
31    Object(Vec<(Vec<u16>, Self)>),
32}
33
34/// A structured value encoded as an explicit rooted Links network.
35#[derive(Clone, Debug, PartialEq, Eq)]
36pub struct StructuredDataLinks {
37    /// Inspectable containers, keys and scalar values.
38    pub network: LinkNetwork,
39    /// The schema root.
40    pub root: LinkId,
41}
42
43/// Bounds on decoding and the size of its resulting value.
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub struct StructuredDataLinksLimits {
46    /// Maximum visited occurrences, including repeated references.
47    pub node_limit: usize,
48    /// Maximum graph traversal depth.
49    pub depth_limit: usize,
50    /// Maximum serialized input and decoded scalar bytes.
51    pub byte_limit: usize,
52}
53
54impl Default for StructuredDataLinksLimits {
55    fn default() -> Self {
56        Self {
57            node_limit: 1_000_000,
58            depth_limit: 256,
59            byte_limit: 128 * 1024 * 1024,
60        }
61    }
62}
63
64fn metadata(term: &str, definition: Option<&str>) -> LinkMetadata {
65    let metadata = LinkMetadata::new()
66        .with_link_type(LinkType::Semantic)
67        .with_named(true)
68        .with_language(LANGUAGE)
69        .with_term(term);
70    if let Some(text) = definition {
71        metadata.with_definition(text)
72    } else {
73        metadata
74    }
75}
76
77fn fail(message: &str) -> String {
78    format!("structured data: {message}")
79}
80
81fn write_number(value: f64) -> Result<String, String> {
82    if !value.is_finite() {
83        return Err(fail("a number must be finite binary64"));
84    }
85    if value.to_bits().trailing_zeros() >= 63 {
86        return Ok(if value.is_sign_negative() { "-0" } else { "0" }.to_owned());
87    }
88    let shortest = value.abs().to_string();
89    let (coefficient, exponent) = shortest.split_once(['e', 'E']).map_or(
90        Ok((shortest.as_str(), 0_i32)),
91        |(coefficient, exponent)| {
92            exponent
93                .parse::<i32>()
94                .map(|exponent| (coefficient, exponent))
95                .map_err(|_| fail("a number exponent is invalid"))
96        },
97    )?;
98    let point = coefficient.find('.').unwrap_or(coefficient.len());
99    let mut digits: String = coefficient
100        .chars()
101        .filter(|character| *character != '.')
102        .collect();
103    let leading = digits
104        .chars()
105        .take_while(|character| *character == '0')
106        .count();
107    digits.drain(..leading);
108    while digits.ends_with('0') {
109        digits.pop();
110    }
111    let magnitude = i32::try_from(point).map_err(|_| fail("a number is too long"))?
112        - i32::try_from(leading).map_err(|_| fail("a number is too long"))?
113        + exponent
114        - 1;
115    let mut output = if (-6..21).contains(&magnitude) {
116        let position = magnitude + 1;
117        if position <= 0 {
118            format!(
119                "0.{}{digits}",
120                "0".repeat(usize::try_from(-position).unwrap())
121            )
122        } else {
123            let position = usize::try_from(position).unwrap();
124            if position >= digits.len() {
125                format!("{digits}{}", "0".repeat(position - digits.len()))
126            } else {
127                format!("{}.{}", &digits[..position], &digits[position..])
128            }
129        }
130    } else {
131        let coefficient = if digits.len() == 1 {
132            digits
133        } else {
134            format!("{}.{}", &digits[..1], &digits[1..])
135        };
136        format!(
137            "{coefficient}e{}{magnitude}",
138            if magnitude >= 0 { "+" } else { "" }
139        )
140    };
141    if value.is_sign_negative() {
142        output.insert(0, '-');
143    }
144    Ok(output)
145}
146
147fn read_number(text: &str) -> Result<f64, String> {
148    let number = text
149        .parse::<f64>()
150        .map_err(|_| fail("a number is invalid"))?;
151    if write_number(number)? != text {
152        return Err(fail("a number is not canonical binary64"));
153    }
154    Ok(number)
155}
156
157struct Encoder {
158    network: LinkNetwork,
159    structural_scalars: bool,
160    limits: StructuredDataLinksLimits,
161    bytes: usize,
162    scalars: HashMap<(String, Option<String>), LinkId>,
163    container_aliases: HashMap<*const StructuredDataValue, *const StructuredDataValue>,
164    containers: HashMap<*const StructuredDataValue, LinkId>,
165    consumed_aliases: HashSet<*const StructuredDataValue>,
166    heights: HashMap<LinkId, usize>,
167}
168
169impl Encoder {
170    fn node(
171        &mut self,
172        term: &str,
173        definition: Option<&str>,
174        references: &[LinkId],
175        depth: usize,
176    ) -> Result<LinkId, String> {
177        if self.network.len() >= self.limits.node_limit || depth > self.limits.depth_limit {
178            return Err(fail("the value exceeds its structural resource limit"));
179        }
180        self.bytes = self.bytes.saturating_add(definition.map_or(0, str::len));
181        if self.bytes > self.limits.byte_limit {
182            return Err(fail("the value exceeds its scalar byte resource limit"));
183        }
184        let id = self.network.insert_link([], metadata(term, definition));
185        self.network.set_references(id, references);
186        if self.structural_scalars || !self.container_aliases.is_empty() {
187            self.heights.insert(id, self.reference_height(references));
188        }
189        Ok(id)
190    }
191
192    fn reference_height(&self, references: &[LinkId]) -> usize {
193        references
194            .iter()
195            .filter_map(|reference| self.heights.get(reference))
196            .max()
197            .map_or(0, |height| height + 1)
198    }
199
200    fn complete_container(
201        &mut self,
202        value: &StructuredDataValue,
203        id: LinkId,
204        references: &[LinkId],
205    ) {
206        self.network.set_references(id, references);
207        if !self.container_aliases.is_empty() {
208            self.containers.insert(std::ptr::from_ref(value), id);
209            self.heights.insert(id, self.reference_height(references));
210        }
211    }
212
213    fn scalar(
214        &mut self,
215        term: &str,
216        definition: Option<&str>,
217        depth: usize,
218    ) -> Result<LinkId, String> {
219        if depth > self.limits.depth_limit {
220            return Err(fail("the value exceeds its structural resource limit"));
221        }
222        let key = (term.to_owned(), definition.map(str::to_owned));
223        if let Some(id) = self.scalars.get(&key) {
224            return Ok(*id);
225        }
226        let id = self.node(term, definition, &[], depth)?;
227        self.scalars.insert(key, id);
228        Ok(id)
229    }
230
231    fn structural_scalar(
232        &mut self,
233        term: &str,
234        value: u64,
235        width: u32,
236        depth: usize,
237    ) -> Result<LinkId, String> {
238        let mut references = Vec::with_capacity(width as usize);
239        let zero = self.structural_scalar_link(BINARY_DIGIT, 0, &[], depth + 1)?;
240        for shift in (0..width).rev() {
241            let bit = if value >> shift & 1 == 0 {
242                zero
243            } else {
244                self.structural_scalar_link(BINARY_DIGIT, 1, &[zero], depth + 1)?
245            };
246            references.push(bit);
247        }
248        self.structural_scalar_link(term, value, &references, depth)
249    }
250
251    fn structural_scalar_link(
252        &mut self,
253        term: &str,
254        value: u64,
255        references: &[LinkId],
256        depth: usize,
257    ) -> Result<LinkId, String> {
258        if depth.saturating_add(self.reference_height(references)) > self.limits.depth_limit {
259            return Err(fail("the value exceeds its structural resource limit"));
260        }
261        let key = (term.to_owned(), Some(value.to_string()));
262        if let Some(id) = self.scalars.get(&key) {
263            return Ok(*id);
264        }
265        let id = self.node(term, None, references, depth)?;
266        self.scalars.insert(key, id);
267        Ok(id)
268    }
269
270    fn string(&mut self, text: &[u16], depth: usize) -> Result<LinkId, String> {
271        if depth > self.limits.depth_limit {
272            return Err(fail("the value exceeds its structural resource limit"));
273        }
274        if !self.structural_scalars
275            && let Ok(scalar) = String::from_utf16(text)
276        {
277            return self.scalar("string value", Some(&scalar), depth);
278        }
279        {
280            // A nonempty string has a child level even when it is already interned.
281            if !text.is_empty() && depth == self.limits.depth_limit {
282                return Err(fail("the value exceeds its structural resource limit"));
283            }
284            let key = (
285                "Unicode code unit string".to_owned(),
286                Some(format!("{text:?}")),
287            );
288            if let Some(id) = self.scalars.get(&key) {
289                if self.structural_scalars && depth + self.heights[id] > self.limits.depth_limit {
290                    return Err(fail("the value exceeds its structural resource limit"));
291                }
292                return Ok(*id);
293            }
294            let units = text
295                .iter()
296                .map(|unit| {
297                    if self.structural_scalars {
298                        self.structural_scalar("Unicode code unit", u64::from(*unit), 16, depth + 1)
299                    } else {
300                        self.scalar("Unicode code unit", Some(&unit.to_string()), depth + 1)
301                    }
302                })
303                .collect::<Result<Vec<_>, _>>()?;
304            let id = self.node("Unicode code unit string", None, &units, depth)?;
305            self.scalars.insert(key, id);
306            Ok(id)
307        }
308    }
309
310    fn value(&mut self, value: &StructuredDataValue, depth: usize) -> Result<LinkId, String> {
311        if depth > self.limits.depth_limit {
312            return Err(fail("the value exceeds its structural resource limit"));
313        }
314        let address = std::ptr::from_ref(value);
315        if let Some(target) = self.container_aliases.get(&address) {
316            let id = *self.containers.get(target).ok_or_else(|| {
317                fail("a container alias must reference an earlier completed owned container")
318            })?;
319            if depth.saturating_add(self.heights[&id]) > self.limits.depth_limit {
320                return Err(fail("the value exceeds its structural resource limit"));
321            }
322            self.consumed_aliases.insert(address);
323            return Ok(id);
324        }
325        match value {
326            StructuredDataValue::Null => self.scalar("null value", None, depth),
327            StructuredDataValue::Boolean(value) if self.structural_scalars => {
328                self.structural_scalar("boolean value", u64::from(*value), 1, depth)
329            }
330            StructuredDataValue::Number(value) if self.structural_scalars => {
331                if !value.is_finite() {
332                    return Err(fail("a number must be finite binary64"));
333                }
334                self.structural_scalar("number value", value.to_bits(), 64, depth)
335            }
336            StructuredDataValue::Boolean(value) => self.scalar(
337                "boolean value",
338                Some(if *value { "true" } else { "false" }),
339                depth,
340            ),
341            StructuredDataValue::Number(value) => {
342                self.scalar("number value", Some(&write_number(*value)?), depth)
343            }
344            StructuredDataValue::String(text) => self.string(text, depth),
345            StructuredDataValue::Array(values) => {
346                let id = self.node("array value", None, &[], depth)?;
347                let children = values
348                    .iter()
349                    .map(|value| self.value(value, depth + 1))
350                    .collect::<Result<Vec<_>, _>>()?;
351                self.complete_container(value, id, &children);
352                Ok(id)
353            }
354            StructuredDataValue::Object(entries) => {
355                let id = self.node("object value", None, &[], depth)?;
356                let mut keys = BTreeSet::new();
357                let mut children = Vec::with_capacity(entries.len());
358                for (key, value) in entries {
359                    if !keys.insert(key) {
360                        return Err(fail("an object contains a duplicate key"));
361                    }
362                    let key = self.string(key, depth + 2)?;
363                    let value = self.value(value, depth + 2)?;
364                    children.push(self.node("key value pair", None, &[key, value], depth + 1)?);
365                }
366                self.complete_container(value, id, &children);
367                Ok(id)
368            }
369        }
370    }
371}
372
373/// Encode ordered data without replacing any scalar or key.
374pub fn encode_structured_data_links_ordered(
375    value: &StructuredDataValue,
376) -> Result<StructuredDataLinks, String> {
377    encode_structured_data_links_ordered_with_container_aliases(value, &[])
378}
379
380/// Preserve explicitly owned container identities supplied by a host adapter.
381/// Equal independent containers remain independent without a declared alias.
382pub(crate) fn encode_structured_data_links_ordered_with_container_aliases(
383    value: &StructuredDataValue,
384    aliases: &[(&StructuredDataValue, &StructuredDataValue)],
385) -> Result<StructuredDataLinks, String> {
386    encode_ordered(value, aliases, false)
387}
388
389/// Encode Unicode code units, finite binary64 values and booleans as references.
390pub fn encode_structured_data_links_ordered_with_structural_scalars(
391    value: &StructuredDataValue,
392) -> Result<StructuredDataLinks, String> {
393    encode_ordered(value, &[], true)
394}
395
396fn encode_ordered(
397    value: &StructuredDataValue,
398    aliases: &[(&StructuredDataValue, &StructuredDataValue)],
399    structural_scalars: bool,
400) -> Result<StructuredDataLinks, String> {
401    let mut container_aliases = HashMap::new();
402    for (alias, target) in aliases {
403        if !matches!(
404            alias,
405            StructuredDataValue::Array(_) | StructuredDataValue::Object(_)
406        ) || !matches!(
407            target,
408            StructuredDataValue::Array(_) | StructuredDataValue::Object(_)
409        ) || std::ptr::eq(*alias, *target)
410            || container_aliases
411                .insert(std::ptr::from_ref(*alias), std::ptr::from_ref(*target))
412                .is_some()
413        {
414            return Err(fail("invalid or duplicate container alias"));
415        }
416        // Canonical encoding authenticates ordered keys, UTF-16 units, finite
417        // Numbers and negative zero. Equality never nominates an alias.
418        if encode_structured_data_links_ordered(alias)?
419            .network
420            .to_lino()
421            != encode_structured_data_links_ordered(target)?
422                .network
423                .to_lino()
424        {
425            return Err(fail("a container alias differs from its declared target"));
426        }
427    }
428    let mut encoder = Encoder {
429        network: LinkNetwork::new(),
430        structural_scalars,
431        limits: StructuredDataLinksLimits::default(),
432        bytes: 0,
433        scalars: HashMap::new(),
434        container_aliases,
435        containers: HashMap::new(),
436        consumed_aliases: HashSet::new(),
437        heights: HashMap::new(),
438    };
439    let body = encoder.value(value, 1)?;
440    if encoder.consumed_aliases.len() != aliases.len() {
441        return Err(fail("a container alias is outside the encoded value"));
442    }
443    let root = encoder.node(
444        "structured data",
445        (!structural_scalars).then_some("1"),
446        &[body],
447        0,
448    )?;
449    Ok(StructuredDataLinks {
450        network: encoder.network,
451        root,
452    })
453}
454
455struct Decoder<'a> {
456    network: &'a LinkNetwork,
457    structural_scalars: bool,
458    limits: StructuredDataLinksLimits,
459    visits: usize,
460    bytes: usize,
461    seen: HashSet<LinkId>,
462    active: HashSet<LinkId>,
463}
464
465impl Decoder<'_> {
466    fn enter(
467        &mut self,
468        id: LinkId,
469        depth: usize,
470    ) -> Result<(String, Option<String>, Vec<LinkId>), String> {
471        self.visits = self.visits.saturating_add(1);
472        if self.visits > self.limits.node_limit || depth > self.limits.depth_limit {
473            return Err(fail("the value exceeds its structural resource limit"));
474        }
475        if !self.active.insert(id) {
476            return Err(fail("the value contains a structural cycle"));
477        }
478        if id.as_u64() == 0 || id.as_u64() > 9_007_199_254_740_991 {
479            return Err(fail("a link identity is not canonical"));
480        }
481        let link = self
482            .network
483            .link(id)
484            .ok_or_else(|| fail("a reference is dangling"))?;
485        let metadata = link.metadata();
486        if metadata.link_type() != Some(LinkType::Semantic)
487            || !metadata.is_named()
488            || metadata.language() != Some(LANGUAGE)
489            || metadata.span().is_some()
490            || metadata.flags() != LinkFlags::clean()
491        {
492            return Err(fail("a node has foreign or malformed metadata"));
493        }
494        let term = metadata.term().unwrap_or_default();
495        let kind = if self.structural_scalars && term == BINARY_DIGIT {
496            "bit".to_owned()
497        } else {
498            read_structured_data_kind(term)
499        };
500        let definition = metadata.definition().map(str::to_owned);
501        let references = link.references().to_vec();
502        self.seen.insert(id);
503        self.bytes = self
504            .bytes
505            .saturating_add(definition.as_ref().map_or(0, String::len));
506        if self.bytes > self.limits.byte_limit {
507            return Err(fail("the value exceeds its scalar byte resource limit"));
508        }
509        let arity = references.len();
510        let valid_shape = if self.structural_scalars {
511            definition.is_none()
512                && match kind.as_str() {
513                    "bit" => arity <= 1,
514                    "boolean" | "root" => arity == 1,
515                    "number" => arity == 64,
516                    "unit" => arity == 16,
517                    "string" => false,
518                    _ => accept_structured_data_shape(&kind, &arity.to_string(), false),
519                }
520        } else {
521            accept_structured_data_shape(&kind, &arity.to_string(), definition.is_some())
522        };
523        if !valid_shape {
524            return Err(fail("a node has an unknown kind or invalid shape"));
525        }
526        Ok((kind, definition, references))
527    }
528
529    fn bits(&mut self, references: &[LinkId], depth: usize) -> Result<u64, String> {
530        let mut value = 0;
531        for &reference in references {
532            let (kind, _, digits) = self.enter(reference, depth)?;
533            if kind != "bit" {
534                return Err(fail("a structural scalar contains a foreign role"));
535            }
536            value <<= 1;
537            if let Some(&zero) = digits.first() {
538                let (kind, _, zero_digits) = self.enter(zero, depth + 1)?;
539                if kind != "bit" || !zero_digits.is_empty() {
540                    return Err(fail("a one digit must reference zero"));
541                }
542                self.active.remove(&zero);
543                value |= 1;
544            }
545            self.active.remove(&reference);
546        }
547        Ok(value)
548    }
549
550    fn string(&mut self, id: LinkId, depth: usize) -> Result<Vec<u16>, String> {
551        let value = self.value(id, depth)?;
552        if let StructuredDataValue::String(text) = value {
553            Ok(text)
554        } else {
555            Err(fail("an object key must be a string"))
556        }
557    }
558
559    fn pair(
560        &mut self,
561        id: LinkId,
562        depth: usize,
563    ) -> Result<(Vec<u16>, StructuredDataValue), String> {
564        let (kind, _, references) = self.enter(id, depth)?;
565        if kind != "pair" {
566            return Err(fail("an object child must be a key value pair"));
567        }
568        let key = self.string(references[0], depth + 1)?;
569        let value = self.value(references[1], depth + 1)?;
570        self.active.remove(&id);
571        Ok((key, value))
572    }
573
574    fn value(&mut self, id: LinkId, depth: usize) -> Result<StructuredDataValue, String> {
575        let (kind, definition, references) = self.enter(id, depth)?;
576        let value = match kind.as_str() {
577            "null" => StructuredDataValue::Null,
578            "boolean" if self.structural_scalars => {
579                StructuredDataValue::Boolean(self.bits(&references, depth + 1)? != 0)
580            }
581            "number" if self.structural_scalars => {
582                let number = f64::from_bits(self.bits(&references, depth + 1)?);
583                if !number.is_finite() {
584                    return Err(fail("a number must be finite binary64"));
585                }
586                StructuredDataValue::Number(number)
587            }
588            "boolean" => StructuredDataValue::Boolean(match definition.as_deref() {
589                Some("true") => true,
590                Some("false") => false,
591                _ => return Err(fail("a boolean definition is invalid")),
592            }),
593            "number" => {
594                StructuredDataValue::Number(read_number(definition.as_deref().unwrap_or_default())?)
595            }
596            "string" => {
597                StructuredDataValue::String(definition.unwrap_or_default().encode_utf16().collect())
598            }
599            "units" => {
600                let mut units = Vec::with_capacity(references.len());
601                for unit in references {
602                    let (kind, definition, digits) = self.enter(unit, depth + 1)?;
603                    if kind != "unit" {
604                        return Err(fail("a code unit string contains a foreign node"));
605                    }
606                    if self.structural_scalars {
607                        let value = u16::try_from(self.bits(&digits, depth + 2)?)
608                            .map_err(|_| fail("a code unit is invalid"))?;
609                        units.push(value);
610                        self.active.remove(&unit);
611                        continue;
612                    }
613                    let text = definition.ok_or_else(|| fail("a code unit lacks a definition"))?;
614                    let value = text
615                        .parse::<u16>()
616                        .map_err(|_| fail("a code unit is invalid"))?;
617                    if value.to_string() != text {
618                        return Err(fail("a code unit is not canonical"));
619                    }
620                    units.push(value);
621                    self.active.remove(&unit);
622                }
623                StructuredDataValue::String(units)
624            }
625            "array" => StructuredDataValue::Array(
626                references
627                    .iter()
628                    .map(|child| self.value(*child, depth + 1))
629                    .collect::<Result<_, _>>()?,
630            ),
631            "object" => {
632                let mut keys = BTreeSet::new();
633                let mut entries = Vec::with_capacity(references.len());
634                for child in references {
635                    let (key, value) = self.pair(child, depth + 1)?;
636                    if !keys.insert(key.clone()) {
637                        return Err(fail("an object contains a duplicate key"));
638                    }
639                    entries.push((key, value));
640                }
641                StructuredDataValue::Object(entries)
642            }
643            _ => {
644                return Err(fail(
645                    "a schema root, key pair or code unit occurs as a value",
646                ));
647            }
648        };
649        self.active.remove(&id);
650        Ok(value)
651    }
652}
653
654/// Decode ordered values with default resource bounds.
655pub fn decode_structured_data_links_ordered(
656    network: &LinkNetwork,
657    root: LinkId,
658) -> Result<StructuredDataValue, String> {
659    decode_structured_data_links_ordered_with_limits(
660        network,
661        root,
662        StructuredDataLinksLimits::default(),
663    )
664}
665
666/// Decode ordered values, rejecting cycles, foreign nodes and excessive output.
667pub fn decode_structured_data_links_ordered_with_limits(
668    network: &LinkNetwork,
669    root: LinkId,
670    limits: StructuredDataLinksLimits,
671) -> Result<StructuredDataValue, String> {
672    if limits.node_limit == 0 || limits.depth_limit == 0 || limits.byte_limit == 0 {
673        return Err(fail("resource limits must be positive"));
674    }
675    if network.len() > limits.node_limit {
676        return Err(fail("the network exceeds its resource limit"));
677    }
678    let mut decoder = Decoder {
679        network,
680        structural_scalars: network
681            .link(root)
682            .is_some_and(|link| link.metadata().definition().is_none()),
683        limits,
684        visits: 0,
685        bytes: 0,
686        active: HashSet::new(),
687        seen: HashSet::new(),
688    };
689    let (kind, definition, references) = decoder.enter(root, 0)?;
690    if kind != "root" || (!decoder.structural_scalars && definition.as_deref() != Some("1")) {
691        return Err(fail("the root has an unsupported schema"));
692    }
693    let value = decoder.value(references[0], 1)?;
694    if decoder.seen.len() != network.len() {
695        return Err(fail("the network contains unreachable nodes"));
696    }
697    Ok(value)
698}
699
700pub(crate) fn from_json(value: &Value, depth: usize) -> Result<StructuredDataValue, String> {
701    if depth > StructuredDataLinksLimits::default().depth_limit {
702        return Err(fail("the value exceeds its structural resource limit"));
703    }
704    Ok(match value {
705        Value::Null => StructuredDataValue::Null,
706        Value::Bool(value) => StructuredDataValue::Boolean(*value),
707        Value::Number(number) => {
708            let value = number
709                .as_f64()
710                .ok_or_else(|| fail("a JSON number is not binary64"))?;
711            if let Some(integer) = number.as_i64() {
712                // i128 has sufficient range for all JSON integer inputs, so
713                // this comparison detects binary64 rounding without saturation.
714                #[allow(clippy::cast_possible_truncation)]
715                let represented = value as i128;
716                if represented != i128::from(integer) {
717                    return Err(fail(
718                        "a JSON integer is not exactly representable as binary64",
719                    ));
720                }
721            } else if let Some(integer) = number.as_u64() {
722                #[allow(clippy::cast_possible_truncation)]
723                let represented = value as i128;
724                if represented != i128::from(integer) {
725                    return Err(fail(
726                        "a JSON integer is not exactly representable as binary64",
727                    ));
728                }
729            }
730            StructuredDataValue::Number(value)
731        }
732        Value::String(text) => StructuredDataValue::String(text.encode_utf16().collect()),
733        Value::Array(values) => StructuredDataValue::Array(
734            values
735                .iter()
736                .map(|value| from_json(value, depth + 1))
737                .collect::<Result<_, _>>()?,
738        ),
739        Value::Object(entries) => StructuredDataValue::Object(
740            entries
741                .iter()
742                .map(|(key, value)| {
743                    Ok((key.encode_utf16().collect(), from_json(value, depth + 2)?))
744                })
745                .collect::<Result<_, String>>()?,
746        ),
747    })
748}
749
750fn into_json(value: StructuredDataValue) -> Result<Value, String> {
751    Ok(match value {
752        StructuredDataValue::Null => Value::Null,
753        StructuredDataValue::Boolean(value) => Value::Bool(value),
754        StructuredDataValue::Number(value) => Value::Number(into_json_number(value)?),
755        StructuredDataValue::String(units) => Value::String(String::from_utf16(&units).map_err(|_| fail("a JSON string cannot preserve an unpaired UTF-16 code unit; use the ordered value API"))?),
756        StructuredDataValue::Array(values) => Value::Array(values.into_iter().map(into_json).collect::<Result<_, _>>()?),
757        StructuredDataValue::Object(entries) => {
758            let mut result = Map::new();
759            for (key, value) in entries {
760                let key = String::from_utf16(&key).map_err(|_| fail("a JSON key cannot preserve an unpaired UTF-16 code unit; use the ordered value API"))?;
761                result.insert(key, into_json(value)?);
762            }
763            Value::Object(result)
764        }
765    })
766}
767
768pub(crate) fn into_json_number(value: f64) -> Result<Number, String> {
769    let text = write_number(value)?;
770    if text != "-0" {
771        if let Ok(integer) = text.parse::<i64>() {
772            return Ok(Number::from(integer));
773        }
774        if let Ok(integer) = text.parse::<u64>() {
775            return Ok(Number::from(integer));
776        }
777    }
778    Number::from_f64(value).ok_or_else(|| fail("a number is not finite"))
779}
780
781/// Encode a JSON-compatible value; ordered encoding retains insertion order.
782pub fn encode_structured_data_links(value: &Value) -> Result<StructuredDataLinks, String> {
783    encode_structured_data_links_ordered(&from_json(value, 1)?)
784}
785
786/// Decode a JSON-compatible value; use the ordered API to retain key order.
787pub fn decode_structured_data_links(network: &LinkNetwork, root: LinkId) -> Result<Value, String> {
788    into_json(decode_structured_data_links_ordered(network, root)?)
789}
790
791/// Decode JSON-compatible data with explicit structural limits.
792pub fn decode_structured_data_links_with_limits(
793    network: &LinkNetwork,
794    root: LinkId,
795    limits: StructuredDataLinksLimits,
796) -> Result<Value, String> {
797    into_json(decode_structured_data_links_ordered_with_limits(
798        network, root, limits,
799    )?)
800}
801
802/// Serialize a JSON-compatible value as inspectable, rooted Links Notation.
803pub fn structured_data_to_lino(value: &Value) -> Result<String, String> {
804    structured_data_to_lino_ordered(&from_json(value, 1)?)
805}
806
807/// Serialize an ordered value, including exact UTF-16 code unit strings.
808pub fn structured_data_to_lino_ordered(value: &StructuredDataValue) -> Result<String, String> {
809    let graph = encode_structured_data_links_ordered(value)?;
810    Ok(graph.network.to_lino())
811}
812
813fn word(node: &LiNo<String>) -> Result<&str, String> {
814    if let LiNo::Ref(word) = node {
815        Ok(word)
816    } else {
817        Err(fail("an expected word is a nested link"))
818    }
819}
820
821fn link_id(node: &LiNo<String>) -> Result<LinkId, String> {
822    let word = word(node)?;
823    let value = word
824        .parse::<u64>()
825        .map_err(|_| fail("a link identity is invalid"))?;
826    if value == 0 || value > 9_007_199_254_740_991 || value.to_string() != word {
827        return Err(fail("a link identity is not canonical"));
828    }
829    Ok(LinkId::from_u64(value))
830}
831
832fn preflight_statement(node: &LiNo<String>) -> Result<LinkId, String> {
833    let LiNo::Link {
834        id: Some(identity),
835        values,
836    } = node
837    else {
838        return Err(fail("a network statement lacks a numeric identity"));
839    };
840    let id = link_id(&LiNo::Ref(identity.clone()))?;
841    let mut metadata = None;
842    for child in values {
843        match child {
844            LiNo::Ref(_) => {
845                link_id(child)?;
846            }
847            LiNo::Link {
848                id: Some(label),
849                values,
850            } if label == "meta" && metadata.is_none() => {
851                metadata = Some(values);
852            }
853            LiNo::Link { .. } => {
854                return Err(fail(
855                    "a network statement has malformed metadata or references",
856                ));
857            }
858        }
859    }
860    let mut fields = BTreeSet::new();
861    for field in metadata.ok_or_else(|| fail("a network statement lacks metadata"))? {
862        let LiNo::Link {
863            id: Some(label),
864            values,
865        } = field
866        else {
867            return Err(fail("a metadata field has an invalid shape"));
868        };
869        if !matches!(label.as_str(), "t" | "n" | "term" | "def" | "lang") || !fields.insert(label) {
870            return Err(fail("a metadata field is unknown or duplicated"));
871        }
872        if values.len() != 1 {
873            return Err(fail("a metadata field must contain exactly one word"));
874        }
875        if label == "n" && word(&values[0])? != "1" {
876            return Err(fail("the named flag is invalid"));
877        }
878        word(&values[0])?;
879    }
880    if !["t", "n", "term", "lang"]
881        .iter()
882        .all(|required| fields.iter().any(|field| field.as_str() == *required))
883    {
884        return Err(fail("a network statement lacks required metadata"));
885    }
886    Ok(id)
887}
888
889/// Read ordered structured data from self-describing Links Notation.
890pub fn read_structured_data_lino_ordered(text: &str) -> Result<StructuredDataValue, String> {
891    read_structured_data_lino_ordered_with_limits(text, StructuredDataLinksLimits::default())
892}
893
894/// Read ordered data with bounded parsing and expansion.
895pub fn read_structured_data_lino_ordered_with_limits(
896    text: &str,
897    limits: StructuredDataLinksLimits,
898) -> Result<StructuredDataValue, String> {
899    if text.len() > limits.byte_limit {
900        return Err(fail("the text exceeds its resource limit"));
901    }
902    let nodes =
903        parse_lino_to_links_with_config(text, &ParserConfig::without_comments().with_max_depth(8))
904            .map_err(|error| fail(&error.to_string()))?;
905    if nodes.len() > limits.node_limit {
906        return Err(fail("the network exceeds its resource limit"));
907    }
908    let mut identities = BTreeSet::new();
909    for node in &nodes {
910        if !identities.insert(preflight_statement(node)?) {
911            return Err(fail("a network contains a duplicate identity"));
912        }
913    }
914    drop(nodes);
915    let network = LinkNetwork::from_lino(text).map_err(|error| fail(&error.to_string()))?;
916    let roots: Vec<_> = network
917        .links()
918        .filter(|link| link.metadata().term() == Some("structured data"))
919        .map(crate::link_network::Link::id)
920        .collect();
921    if roots.len() != 1 {
922        return Err(fail(
923            "a serialized value must contain exactly one schema root",
924        ));
925    }
926    decode_structured_data_links_ordered_with_limits(&network, roots[0], limits)
927}
928
929/// Read JSON-compatible data from self-describing Links Notation.
930pub fn read_structured_data_lino(text: &str) -> Result<Value, String> {
931    into_json(read_structured_data_lino_ordered(text)?)
932}
933
934/// Read JSON-compatible data with explicit parsing and expansion limits.
935pub fn read_structured_data_lino_with_limits(
936    text: &str,
937    limits: StructuredDataLinksLimits,
938) -> Result<Value, String> {
939    into_json(read_structured_data_lino_ordered_with_limits(text, limits)?)
940}