Skip to main content

links_notation/binary/
mapping.rs

1//! Lossless mapping between LiNo documents and [`LinksPacket`]s.
2//!
3//! The mapping only uses links, the way linksplatform represents data:
4//!
5//! - `()` is the null link `0`.
6//! - A numeric reference `n` is `(Number unary(n))`, where `unary(0)` is null,
7//!   `2^0` is the marker `One`, `2^k` is `(2^(k-1) 2^(k-1))` and other numbers
8//!   are right-nested sums of powers of two from the highest bit down. With
9//!   external references enabled, `n` is sent as an external reference instead.
10//! - Any other reference is `(String code points…)`; every code point is a
11//!   unary number, or an external reference when those are enabled.
12//! - A link without an id and with exactly two values is a plain doublet.
13//! - A link without an id and any other number of values is a list.
14//! - A link with an id is `(Identified id values…)`.
15//! - The document is a list of its top-level links, stored last (the root).
16//!
17//! A link with two values is always a doublet. A list or typed value with
18//! any other number of values is a single link of that many references when
19//! [`BinaryLinoOptions::arity`] allows it (`[marker, elements…]` for typed
20//! values, the bare elements for lists), and otherwise the doublet
21//! `(marker chain)`, where `chain` is the nil-terminated cons list
22//! `(e1 (e2 (… (en 0))))`. Identical sub-links are emitted once and shared,
23//! because links are content-addressed.
24//!
25//! Links are numbered so that every link only refers to earlier ones:
26//! doublets of plain doublets first, then the rest in creation order.
27
28use super::error::{BinaryError, BinaryResult};
29use super::packet::{
30    ArityRange, DecodeLimits, FIRST_LINK_ADDRESS, IDENTIFIED, LIST, LinksPacket, NULL, NUMBER, ONE,
31    Reference, STRING, external_capacity,
32};
33use crate::LiNo;
34use std::cell::Cell;
35use std::collections::HashMap;
36
37/// A LiNo document: the list of top-level links of a message.
38pub type LinoDocument = Vec<LiNo<String>>;
39
40/// Optional features of the binary LiNo protocol.
41///
42/// Every feature is off by default; each one can be switched on
43/// independently, like stacking a decorator.
44#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
45pub struct BinaryLinoOptions {
46    /// Send numbers and code points as Hybrid external references instead of
47    /// in-band unary links. Halves the internal address range of each width.
48    pub external_references: bool,
49    /// The link lengths the encoder may use. The default, exactly 2, sends
50    /// only doublets; `2..3` adds triplets and `1..` any length. The range
51    /// must include 2.
52    pub arity: ArityRange,
53    /// Give every section of the packet the narrowest width its links need
54    /// instead of one width for the whole packet.
55    pub packed_widths: bool,
56}
57
58impl BinaryLinoOptions {
59    /// Enables or disables external references.
60    pub fn with_external_references(mut self, enabled: bool) -> Self {
61        self.external_references = enabled;
62        self
63    }
64
65    /// Sets the link lengths the encoder may use.
66    pub fn with_arity(mut self, arity: ArityRange) -> Self {
67        self.arity = arity;
68        self
69    }
70
71    /// Enables or disables packed widths.
72    pub fn with_packed_widths(mut self, enabled: bool) -> Self {
73        self.packed_widths = enabled;
74        self
75    }
76
77    /// The options a peer most likely used to write `packet`, so a reply can
78    /// be written in the same style.
79    pub fn of_packet(packet: &LinksPacket) -> Self {
80        let (shortest, longest) = packet
81            .links()
82            .map(|(_, link)| link.len() as u64)
83            .fold((2, 2), |(shortest, longest), length| {
84                (shortest.min(length), longest.max(length))
85            });
86        let mut widths = packet.sections.iter().map(|section| section.width);
87        let first_width = widths.next();
88        Self {
89            external_references: packet.external_references,
90            arity: ArityRange::between(shortest, longest),
91            packed_widths: widths.any(|width| Some(width) != first_width),
92        }
93    }
94}
95
96/// Converts a document into a packet.
97pub fn encode_document(
98    document: &[LiNo<String>],
99    options: BinaryLinoOptions,
100) -> BinaryResult<LinksPacket> {
101    encode_document_with_limits(document, options, &DecodeLimits::default())
102}
103
104/// Converts a native model into a packet using caller-selected work budgets.
105pub fn encode_document_with_limits(
106    document: &[LiNo<String>],
107    options: BinaryLinoOptions,
108    limits: &DecodeLimits,
109) -> BinaryResult<LinksPacket> {
110    options.arity.validate().map_err(BinaryError::Unencodable)?;
111    if !options.arity.contains(2) {
112        return Err(BinaryError::Unencodable(format!(
113            "arity {} does not include doublets (2)",
114            options.arity
115        )));
116    }
117    // Check the model iteratively before entering the recursive encoder.
118    let mut pending: Vec<_> = document.iter().map(|link| (link, 0)).collect();
119    let mut budget = limits.max_nodes;
120    let mut strings_left = limits.max_string_bytes;
121    while let Some((link, depth)) = pending.pop() {
122        if depth >= limits.max_depth {
123            return Err(BinaryError::Unencodable(format!(
124                "nesting deeper than {}",
125                limits.max_depth
126            )));
127        }
128        budget = budget
129            .checked_sub(1)
130            .ok_or_else(|| BinaryError::Unencodable("too many LiNo nodes".into()))?;
131        let text = match link {
132            LiNo::Ref(text) => Some(text),
133            LiNo::Link { id, values } => {
134                pending.extend(values.iter().map(|value| (value, depth + 1)));
135                if id.is_some() {
136                    budget = budget
137                        .checked_sub(1)
138                        .ok_or_else(|| BinaryError::Unencodable("too many LiNo nodes".into()))?;
139                }
140                id.as_ref()
141            }
142        };
143        if let Some(text) = text {
144            strings_left = strings_left
145                .checked_sub(text.len())
146                .ok_or_else(|| BinaryError::Unencodable("too many string bytes".into()))?;
147        }
148    }
149    let mut encoder = Encoder::new(options);
150    if !document.is_empty() {
151        let items = document
152            .iter()
153            .map(|link| encoder.encode(link))
154            .collect::<Vec<_>>();
155        encoder.list(items);
156    }
157    let packet = encoder.finish()?;
158    if packet.sections.len() as u64 > limits.max_links || packet.link_count() > limits.max_links {
159        return Err(BinaryError::Unencodable("too many packet links".into()));
160    }
161    let mut references_left = limits.max_references;
162    for (_, link) in packet.links() {
163        references_left = references_left
164            .checked_sub(link.len() as u64)
165            .ok_or_else(|| BinaryError::Unencodable("too many packet references".into()))?;
166    }
167    Ok(packet)
168}
169
170/// Converts a packet back into a document.
171pub fn decode_document(packet: &LinksPacket, limits: &DecodeLimits) -> BinaryResult<LinoDocument> {
172    let decoder = Decoder::new(packet, limits)?;
173    let Some(root) = decoder.links.len().checked_sub(1) else {
174        return Ok(Vec::new());
175    };
176    let root = Reference::Internal(FIRST_LINK_ADDRESS + root as u64);
177    let items = match decoder.view(root) {
178        View::Link(&[Reference::Internal(LIST), chain]) => decoder.chain(chain)?,
179        View::Link(items) if !starts_with_marker(items) => items.to_vec(),
180        _ => return Err(BinaryError::malformed("the root link is not a list")),
181    };
182    let mut budget = limits.max_nodes;
183    items
184        .into_iter()
185        .map(|item| decoder.decode(item, 0, &mut budget))
186        .collect()
187}
188
189/// Parses a canonical unsigned decimal number (no sign, no leading zeros).
190pub(crate) fn canonical_number(text: &str) -> Option<u64> {
191    let canonical = !text.is_empty()
192        && text.bytes().all(|byte| byte.is_ascii_digit())
193        && (text == "0" || !text.starts_with('0'));
194    canonical.then(|| text.parse().ok()).flatten()
195}
196
197#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
198enum Node {
199    Internal(u64),
200    External(u64),
201    /// A doublet of plain doublets, markers and externals.
202    Doublet(usize),
203    /// Any other link; numbered after every [`Node::Doublet`].
204    Tuple(usize),
205}
206
207struct Encoder {
208    options: BinaryLinoOptions,
209    doublets: Vec<Vec<Node>>,
210    tuples: Vec<Vec<Node>>,
211    created: HashMap<Vec<Node>, Node>,
212    powers: Vec<Node>,
213}
214
215impl Encoder {
216    fn new(options: BinaryLinoOptions) -> Self {
217        Self {
218            options,
219            doublets: Vec::new(),
220            tuples: Vec::new(),
221            created: HashMap::new(),
222            powers: vec![Node::Internal(ONE)],
223        }
224    }
225
226    fn link(&mut self, items: Vec<Node>) -> Node {
227        if let Some(&node) = self.created.get(&items) {
228            return node;
229        }
230        let refers_to_tuple = items.iter().any(|item| matches!(item, Node::Tuple(_)));
231        let node = if items.len() == 2 && !refers_to_tuple {
232            self.doublets.push(items.clone());
233            Node::Doublet(self.doublets.len() - 1)
234        } else {
235            self.tuples.push(items.clone());
236            Node::Tuple(self.tuples.len() - 1)
237        };
238        self.created.insert(items, node);
239        node
240    }
241
242    fn pair(&mut self, first: Node, second: Node) -> Node {
243        self.link(vec![first, second])
244    }
245
246    fn chain(&mut self, items: &[Node]) -> Node {
247        items
248            .iter()
249            .rev()
250            .fold(Node::Internal(NULL), |tail, &head| self.pair(head, tail))
251    }
252
253    /// One link of `items` when the arity allows it, except that two items
254    /// are always a doublet.
255    fn fits_one_link(&self, items: usize) -> bool {
256        items != 2 && self.options.arity.contains(items as u64)
257    }
258
259    fn typed(&mut self, marker: u64, elements: Vec<Node>) -> Node {
260        if self.fits_one_link(elements.len() + 1) {
261            let mut items = Vec::with_capacity(elements.len() + 1);
262            items.push(Node::Internal(marker));
263            items.extend(elements);
264            self.link(items)
265        } else {
266            let chain = self.chain(&elements);
267            self.pair(Node::Internal(marker), chain)
268        }
269    }
270
271    fn list(&mut self, elements: Vec<Node>) -> Node {
272        match elements.as_slice() {
273            [] => Node::Internal(NULL),
274            &[first, second] => self.pair(first, second),
275            _ if self.fits_one_link(elements.len()) => self.link(elements),
276            _ => self.typed(LIST, elements),
277        }
278    }
279
280    fn power(&mut self, exponent: usize) -> Node {
281        while self.powers.len() <= exponent {
282            let previous = *self.powers.last().expect("powers start with One");
283            let next = self.pair(previous, previous);
284            self.powers.push(next);
285        }
286        self.powers[exponent]
287    }
288
289    fn unary(&mut self, value: u64) -> Node {
290        let bit_count = (u64::BITS - value.leading_zeros()) as usize;
291        let bits = (0..bit_count)
292            .rev()
293            .filter(|bit| value & (1u64 << bit) != 0);
294        let powers = bits.map(|bit| self.power(bit)).collect::<Vec<_>>();
295        let Some((&last, rest)) = powers.split_last() else {
296            return Node::Internal(NULL);
297        };
298        rest.iter()
299            .rev()
300            .fold(last, |sum, &power| self.pair(power, sum))
301    }
302
303    fn scalar(&mut self, value: u64) -> Node {
304        if self.options.external_references && value <= external_capacity(8) {
305            Node::External(value)
306        } else {
307            self.unary(value)
308        }
309    }
310
311    fn reference(&mut self, text: &str) -> Node {
312        if let Some(value) = canonical_number(text) {
313            if self.options.external_references && value <= external_capacity(8) {
314                return Node::External(value);
315            }
316            let unary = self.unary(value);
317            return self.pair(Node::Internal(NUMBER), unary);
318        }
319        let code_points = text
320            .chars()
321            .map(|character| self.scalar(u64::from(u32::from(character))))
322            .collect();
323        self.typed(STRING, code_points)
324    }
325
326    fn encode(&mut self, link: &LiNo<String>) -> Node {
327        match link {
328            LiNo::Ref(text) => self.reference(text),
329            LiNo::Link { id: None, values } => {
330                let elements = values.iter().map(|value| self.encode(value)).collect();
331                self.list(elements)
332            }
333            LiNo::Link {
334                id: Some(id),
335                values,
336            } => {
337                let mut elements = Vec::with_capacity(values.len() + 1);
338                elements.push(self.reference(id));
339                elements.extend(values.iter().map(|value| self.encode(value)));
340                self.typed(IDENTIFIED, elements)
341            }
342        }
343    }
344
345    fn finish(self) -> BinaryResult<LinksPacket> {
346        let doublet_count = self.doublets.len() as u64;
347        let resolve = |node: &Node| match *node {
348            Node::Internal(address) => Reference::Internal(address),
349            Node::External(value) => Reference::External(value),
350            Node::Doublet(index) => Reference::Internal(FIRST_LINK_ADDRESS + index as u64),
351            Node::Tuple(index) => {
352                Reference::Internal(FIRST_LINK_ADDRESS + doublet_count + index as u64)
353            }
354        };
355        let links: Vec<(u64, Vec<Reference>)> = self
356            .doublets
357            .iter()
358            .chain(&self.tuples)
359            .enumerate()
360            .map(|(index, items)| {
361                (
362                    FIRST_LINK_ADDRESS + index as u64,
363                    items.iter().map(resolve).collect(),
364                )
365            })
366            .collect();
367        LinksPacket::pack(
368            self.options.external_references,
369            &links,
370            self.options.packed_widths,
371        )
372    }
373}
374
375enum View<'a> {
376    Null,
377    Marker(u64),
378    External(u64),
379    Link(&'a [Reference]),
380}
381
382fn is_marker(reference: Reference) -> bool {
383    matches!(reference, Reference::Internal(address) if (ONE..FIRST_LINK_ADDRESS).contains(&address))
384}
385
386fn starts_with_marker(items: &[Reference]) -> bool {
387    items.first().copied().is_some_and(is_marker)
388}
389
390struct Decoder<'a> {
391    limits: &'a DecodeLimits,
392    string_bytes_left: Cell<usize>,
393    /// `links[i]` is the link at address `FIRST_LINK_ADDRESS + i`.
394    links: Vec<&'a [Reference]>,
395    /// `unary[i]` is the number link `i` denotes, if it is a unary number.
396    unary: Vec<Option<u64>>,
397}
398
399impl<'a> Decoder<'a> {
400    fn new(packet: &'a LinksPacket, limits: &'a DecodeLimits) -> BinaryResult<Self> {
401        if packet.sections.len() as u64 > limits.max_links || packet.link_count() > limits.max_links
402        {
403            return Err(BinaryError::LimitExceeded(format!(
404                "packet declares more than {} links",
405                limits.max_links
406            )));
407        }
408        let mut links: Vec<&'a [Reference]> = Vec::new();
409        packet
410            .validate()
411            .map_err(|error| BinaryError::malformed(error.to_string()))?;
412        let mut unary: Vec<Option<u64>> = Vec::new();
413        let mut references_left = limits.max_references;
414        for (address, link) in packet.links() {
415            references_left = references_left
416                .checked_sub(link.len() as u64)
417                .ok_or_else(|| {
418                    BinaryError::LimitExceeded(format!(
419                        "references exceed the limit of {}",
420                        limits.max_references
421                    ))
422                })?;
423            let expected = FIRST_LINK_ADDRESS + links.len() as u64;
424            if address != expected {
425                return Err(BinaryError::malformed(format!(
426                    "a LiNo packet stores its links contiguously from address \
427                     {FIRST_LINK_ADDRESS}, found link {address} where {expected} belongs"
428                )));
429            }
430            if let Some(&target) = link.iter().find(
431                |&&reference| matches!(reference, Reference::Internal(target) if target >= address),
432            ) {
433                return Err(BinaryError::malformed(format!(
434                    "link {address} refers to {target:?}, which is not an earlier link"
435                )));
436            }
437            // Links only refer backwards, so one forward pass evaluates every
438            // unary number without recursion.
439            let value_of = |reference: Reference| match reference {
440                Reference::Internal(NULL) => Some(0),
441                Reference::Internal(ONE) => Some(1),
442                Reference::Internal(address) if address >= FIRST_LINK_ADDRESS => {
443                    unary[(address - FIRST_LINK_ADDRESS) as usize]
444                }
445                _ => None,
446            };
447            let value = match *link {
448                [source, target] => value_of(source)
449                    .zip(value_of(target))
450                    .and_then(|(source, target)| source.checked_add(target)),
451                _ => None,
452            };
453            unary.push(value);
454            links.push(link);
455        }
456        Ok(Self {
457            limits,
458            string_bytes_left: Cell::new(limits.max_string_bytes),
459            links,
460            unary,
461        })
462    }
463
464    fn view(&self, reference: Reference) -> View<'a> {
465        match reference {
466            Reference::External(value) => View::External(value),
467            Reference::Internal(NULL) => View::Null,
468            Reference::Internal(address) if address < FIRST_LINK_ADDRESS => View::Marker(address),
469            Reference::Internal(address) => {
470                View::Link(self.links[(address - FIRST_LINK_ADDRESS) as usize])
471            }
472        }
473    }
474
475    fn number(&self, reference: Reference) -> BinaryResult<u64> {
476        match reference {
477            Reference::External(value) => Ok(value),
478            Reference::Internal(NULL) => Ok(0),
479            Reference::Internal(ONE) => Ok(1),
480            Reference::Internal(address) if address >= FIRST_LINK_ADDRESS => self.unary
481                [(address - FIRST_LINK_ADDRESS) as usize]
482                .ok_or_else(|| BinaryError::malformed("expected a unary number")),
483            _ => Err(BinaryError::malformed("expected a unary number")),
484        }
485    }
486
487    /// The elements of the cons list `(e1 (e2 (… (en 0))))`.
488    fn chain(&self, mut tail: Reference) -> BinaryResult<Vec<Reference>> {
489        let mut elements = Vec::new();
490        loop {
491            match self.view(tail) {
492                View::Null => return Ok(elements),
493                View::Link(&[head, next]) => {
494                    if elements.len() >= self.limits.max_nodes {
495                        return Err(BinaryError::LimitExceeded("chain too long".into()));
496                    }
497                    elements.push(head);
498                    tail = next;
499                }
500                _ => return Err(BinaryError::malformed("broken element chain")),
501            }
502        }
503    }
504
505    fn typed(
506        &self,
507        marker: u64,
508        elements: &[Reference],
509        depth: usize,
510        budget: &mut usize,
511    ) -> BinaryResult<LiNo<String>> {
512        match marker {
513            NUMBER => match elements {
514                [value] => self.reference_text(self.number(*value)?.to_string()),
515                _ => Err(BinaryError::malformed("a number needs exactly one value")),
516            },
517            STRING => {
518                let mut text =
519                    String::with_capacity(elements.len().min(self.string_bytes_left.get()));
520                for &element in elements {
521                    let code_point = self.number(element)?;
522                    let character = u32::try_from(code_point)
523                        .ok()
524                        .and_then(char::from_u32)
525                        .ok_or_else(|| {
526                            BinaryError::malformed(format!("invalid code point {code_point}"))
527                        })?;
528                    if character.len_utf8()
529                        > self.string_bytes_left.get().saturating_sub(text.len())
530                    {
531                        return Err(BinaryError::LimitExceeded(
532                            "too many expanded string bytes".into(),
533                        ));
534                    }
535                    text.push(character);
536                }
537                self.reference_text(text)
538            }
539            LIST => self.list(elements, depth, budget),
540            IDENTIFIED => {
541                let (&id, values) = elements
542                    .split_first()
543                    .ok_or_else(|| BinaryError::malformed("an identified link needs an id"))?;
544                let LiNo::Ref(id) = self.decode(id, depth, budget)? else {
545                    return Err(BinaryError::malformed("a link id must be a reference"));
546                };
547                Ok(LiNo::Link {
548                    id: Some(id),
549                    values: self.values(values, depth, budget)?,
550                })
551            }
552            _ => Err(BinaryError::malformed(format!(
553                "marker {marker} cannot start a typed value"
554            ))),
555        }
556    }
557
558    fn list(
559        &self,
560        elements: &[Reference],
561        depth: usize,
562        budget: &mut usize,
563    ) -> BinaryResult<LiNo<String>> {
564        Ok(LiNo::Link {
565            id: None,
566            values: self.values(elements, depth, budget)?,
567        })
568    }
569
570    fn values(
571        &self,
572        elements: &[Reference],
573        depth: usize,
574        budget: &mut usize,
575    ) -> BinaryResult<Vec<LiNo<String>>> {
576        elements
577            .iter()
578            .map(|&element| self.decode(element, depth + 1, budget))
579            .collect()
580    }
581
582    fn reference_text(&self, text: String) -> BinaryResult<LiNo<String>> {
583        let remaining = self
584            .string_bytes_left
585            .get()
586            .checked_sub(text.len())
587            .ok_or_else(|| BinaryError::LimitExceeded("too many expanded string bytes".into()))?;
588        self.string_bytes_left.set(remaining);
589        Ok(LiNo::Ref(text))
590    }
591
592    fn decode(
593        &self,
594        reference: Reference,
595        depth: usize,
596        budget: &mut usize,
597    ) -> BinaryResult<LiNo<String>> {
598        if depth >= self.limits.max_depth {
599            return Err(BinaryError::LimitExceeded(format!(
600                "nesting deeper than {}",
601                self.limits.max_depth
602            )));
603        }
604        *budget = budget
605            .checked_sub(1)
606            .ok_or_else(|| BinaryError::LimitExceeded("too many LiNo nodes".into()))?;
607        match self.view(reference) {
608            View::Null => Ok(LiNo::Link {
609                id: None,
610                values: Vec::new(),
611            }),
612            View::External(value) => self.reference_text(value.to_string()),
613            View::Marker(marker) => Err(BinaryError::malformed(format!(
614                "marker {marker} used as a value"
615            ))),
616            View::Link(&[Reference::Internal(NUMBER), value]) => {
617                self.typed(NUMBER, &[value], depth, budget)
618            }
619            View::Link(&[Reference::Internal(marker), chain])
620                if is_marker(Reference::Internal(marker)) =>
621            {
622                let elements = self.chain(chain)?;
623                self.typed(marker, &elements, depth, budget)
624            }
625            View::Link(items) => match items.split_first() {
626                Some((&Reference::Internal(marker), elements)) if starts_with_marker(items) => {
627                    self.typed(marker, elements, depth, budget)
628                }
629                _ => self.list(items, depth, budget),
630            },
631        }
632    }
633}