Skip to main content

fleuron/
wire.rs

1//! The wire: a display structure as bytes, with a version in front of it.
2//!
3//! JSON is what the content tree serializes to, because a person
4//! reads it. The display structure is machine output: every glyph of
5//! every page, produced once per keystroke and decoded on someone's
6//! main thread. So it crosses as [postcard], which packs varints,
7//! sends no field names, and needs no tree of maps built before the
8//! first page can be read.
9//!
10//! The encoding is positional, which is the price of that: a host's
11//! decoder reads fields in declaration order and has no way to notice
12//! that the order changed. So a version leads the bytes, [`VERSION`]
13//! moves whenever what crosses changes shape, and a host that reads
14//! a number it does not know refuses at the first byte instead of
15//! painting nonsense.
16//!
17//! A reply need not carry the whole book: [`encode_range`] sends a
18//! slice of the pages and says where it falls, so a host looking at
19//! one page pays for one page. Layout still runs over the whole book
20//! either way; what a range saves is serializing and decoding the
21//! pages nobody asked for. `fonts`, `assets` and `warnings` are never
22//! sliced, since none of them is per page.
23//!
24//! An EPUB crosses the same wall behind the same version, with the
25//! warnings writing it raised: see [`encode_epub`]. Its files can
26//! cross one by one instead: see [`encode_epub_files`].
27//!
28//! [postcard]: https://postcard.jamesmunns.com/
29
30use crate::content::NodeId;
31use crate::fonts::FontRefEntry;
32use crate::images::Asset;
33use crate::pages::Page;
34use crate::{LayoutOutput, Warning};
35
36/// What the encoding is. A host checks this before reading anything
37/// else, and a mismatch is a refusal rather than a best effort.
38pub const VERSION: u16 = 22;
39
40/// Why a buffer could not be read as a display structure.
41#[derive(Debug, thiserror::Error)]
42pub enum WireError {
43    /// The bytes were written by a build that disagrees about the
44    /// shape of the display structure.
45    #[error("wire version {found}, expected {VERSION}")]
46    Version {
47        /// The version the buffer leads with.
48        found: u16,
49    },
50    /// The bytes are not a display structure at all, or are truncated.
51    #[error("the wire could not be read: {0}")]
52    Malformed(#[from] postcard::Error),
53}
54
55/// What one wire reply carried, and where it falls in the book.
56///
57/// Distinct from [`LayoutOutput`], whose `pages` is always the whole
58/// run's: a reply's `pages` is a slice, `first` is where that slice
59/// begins (counting from 0), and `book_pages` is how many pages the
60/// book has, so a reply carrying page 12 alone still answers "page 12
61/// of 337".
62#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
63pub struct Reply {
64    /// The pages this reply carries, in reading order.
65    pub pages: Vec<Page>,
66    /// The index of `pages[0]` in the book. Zero for a whole-book reply.
67    pub first: usize,
68    /// How many pages the book has, which is more than `pages.len()`
69    /// for anything short of a whole-book reply.
70    pub book_pages: usize,
71    /// The whole run's font table, unsliced.
72    pub fonts: Vec<FontRefEntry>,
73    /// The whole run's asset table, unsliced.
74    pub assets: Vec<Asset>,
75    /// The whole run's warnings, unsliced.
76    pub warnings: Vec<Warning>,
77}
78
79/// Encodes the whole display structure, version first.
80pub fn encode(output: &LayoutOutput) -> Result<Vec<u8>, WireError> {
81    encode_range(output, 0, output.pages.len())
82}
83
84/// Encodes `count` pages starting at `first`, version first. A range
85/// past the end of the book is clamped rather than refused: an edit
86/// that shortens the book while a page past its new end is still
87/// being asked for gets back whatever is left, not a panic.
88///
89/// `first` and the book's page count travel as `u32`, the same as
90/// every other count on the wire; a book past four billion pages is
91/// not one this format is sized for.
92pub fn encode_range(
93    output: &LayoutOutput,
94    first: usize,
95    count: usize,
96) -> Result<Vec<u8>, WireError> {
97    let book_pages = output.pages.len();
98    let first = first.min(book_pages);
99    let end = first.saturating_add(count).min(book_pages);
100    let slice = &output.pages[first..end];
101    Ok(postcard::to_stdvec(&(
102        VERSION,
103        first as u32,
104        book_pages as u32,
105        &output.fonts,
106        &output.assets,
107        &output.warnings,
108        slice,
109    ))?)
110}
111
112/// Reads a reply back, refusing a version this build does not write.
113pub fn decode(bytes: &[u8]) -> Result<Reply, WireError> {
114    let (found, rest) = postcard::take_from_bytes::<u16>(bytes)?;
115    if found != VERSION {
116        return Err(WireError::Version { found });
117    }
118    let (first, book_pages, fonts, assets, warnings, pages): (
119        u32,
120        u32,
121        Vec<FontRefEntry>,
122        Vec<Asset>,
123        Vec<Warning>,
124        Vec<Page>,
125    ) = postcard::from_bytes(rest)?;
126    Ok(Reply {
127        pages,
128        first: first as usize,
129        book_pages: book_pages as usize,
130        fonts,
131        assets,
132        warnings,
133    })
134}
135
136/// An EPUB as one wire reply, and what writing it warned about.
137///
138/// A display structure carries its warnings, and an EPUB is a file
139/// with no room for them, so the two cross together.
140#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
141pub struct Epub {
142    /// What writing it had to complain about, in the shape a display
143    /// structure's warnings take.
144    pub warnings: Vec<Warning>,
145    /// The whole file.
146    pub bytes: Vec<u8>,
147}
148
149/// Encodes an EPUB and its warnings, version first.
150pub fn encode_epub(bytes: &[u8], warnings: &[Warning]) -> Result<Vec<u8>, WireError> {
151    Ok(postcard::to_stdvec(&(VERSION, warnings, bytes))?)
152}
153
154/// Reads an EPUB reply back, refusing a version this build does not
155/// write.
156pub fn decode_epub(bytes: &[u8]) -> Result<Epub, WireError> {
157    let (found, rest) = postcard::take_from_bytes::<u16>(bytes)?;
158    if found != VERSION {
159        return Err(WireError::Version { found });
160    }
161    Ok(postcard::from_bytes(rest)?)
162}
163
164/// An EPUB as its files, not zipped, and what writing it warned
165/// about.
166#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
167pub struct EpubFiles {
168    /// The same warnings [`Epub::warnings`] holds.
169    pub warnings: Vec<Warning>,
170    /// The documents in reading order.
171    pub spine: Vec<EpubSpineEntry>,
172    /// Every file the zip holds, in the order it holds them.
173    pub files: Vec<EpubFile>,
174}
175
176/// One document of an EPUB's spine.
177#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
178pub struct EpubSpineEntry {
179    /// Where the document is in the container.
180    pub path: String,
181    /// The node of the section the document holds. `None` for the
182    /// one empty document of a book with no sections.
183    pub section: Option<NodeId>,
184}
185
186/// One file of an EPUB.
187#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
188pub struct EpubFile {
189    /// Where the file is in the container.
190    pub path: String,
191    /// Its media type.
192    pub media_type: String,
193    /// Its bytes, not compressed.
194    pub bytes: Vec<u8>,
195}
196
197/// Encodes an EPUB's files, version first.
198pub fn encode_epub_files(files: &EpubFiles) -> Result<Vec<u8>, WireError> {
199    Ok(postcard::to_stdvec(&(VERSION, files))?)
200}
201
202/// Reads an EPUB's files back, refusing a version this build does not
203/// write.
204pub fn decode_epub_files(bytes: &[u8]) -> Result<EpubFiles, WireError> {
205    let (found, rest) = postcard::take_from_bytes::<u16>(bytes)?;
206    if found != VERSION {
207        return Err(WireError::Version { found });
208    }
209    Ok(postcard::from_bytes(rest)?)
210}
211
212/// The version a buffer leads with, without reading the rest of it.
213pub fn version(bytes: &[u8]) -> Result<u16, WireError> {
214    Ok(postcard::take_from_bytes::<u16>(bytes)?.0)
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220    use crate::Warning;
221    use crate::content::{NodeId, PseudoElement, SourceRange};
222    use crate::fonts::{AxisSetting, FaceAttributes, FeatureSetting, Features, FontRefEntry};
223    use crate::images::{Asset, Intrinsic};
224    use crate::pages::{Corners, DrawItem, Glyph, Link, LinkTo, Page, PageBox, Radius, Side};
225    use crate::style::{BlendMode, Color, Edges};
226
227    fn output() -> LayoutOutput {
228        LayoutOutput {
229            pages: vec![Page {
230                number: 1,
231                side: Side::Recto,
232                width: 396.0,
233                height: 612.0,
234                bleed: 9.0,
235                slug: 24.0,
236                sections: vec![NodeId::UNASSIGNED],
237                items: vec![
238                    DrawItem::Text {
239                        x: 72.0,
240                        y: 96.5,
241                        font_id: 0,
242                        size: 11.0,
243                        width: 18.5,
244                        text: "FI ❦".into(),
245                        source: "fi ❦".into(),
246                        source_map: vec![0, 1, 2, 3, 4, 5, 6],
247                        origin: Some(SourceRange {
248                            node: NodeId::UNASSIGNED,
249                            range: 3..9,
250                        }),
251                        pseudo_element: Some(NodeId::new(7).pseudo(PseudoElement::FirstLine)),
252                        features: Features::new(true, vec![FeatureSetting::new(*b"onum", 1)]),
253                        color: Color::rgb(180, 30, 30),
254                        glyphs: vec![Glyph {
255                            id: 42,
256                            x: 72.0,
257                            range: 0..2,
258                        }],
259                        layer: 10,
260                        blend: BlendMode::Normal,
261                    },
262                    DrawItem::Rect {
263                        x: 0.0,
264                        y: 0.0,
265                        w: 396.0,
266                        h: 0.5,
267                        color: Color::BLACK,
268                        layer: DrawItem::PAGE_BACKGROUND,
269                        blend: BlendMode::Normal,
270                    },
271                    DrawItem::Image {
272                        x: 1.0,
273                        y: 2.0,
274                        w: 3.0,
275                        h: 4.0,
276                        asset: 7,
277                        alpha: 128,
278                        layer: -1,
279                        blend: BlendMode::Normal,
280                    },
281                    DrawItem::Rounded {
282                        x: 5.0,
283                        y: 6.0,
284                        w: 70.0,
285                        h: 20.0,
286                        radii: Corners {
287                            top_left: Radius { x: 3.0, y: 3.0 },
288                            ..Corners::SQUARE
289                        },
290                        ring: Edges {
291                            left: 2.0,
292                            ..Edges::all(0.0)
293                        },
294                        color: Color::rgba(51, 102, 153, 128),
295                        layer: 0,
296                        blend: BlendMode::Normal,
297                    },
298                ],
299                links: vec![
300                    Link {
301                        areas: vec![
302                            PageBox {
303                                page: 0,
304                                x: 72.0,
305                                y: 88.0,
306                                width: 40.0,
307                                height: 12.0,
308                            },
309                            PageBox {
310                                page: 0,
311                                x: 72.0,
312                                y: 102.0,
313                                width: 20.0,
314                                height: 12.0,
315                            },
316                        ],
317                        to: LinkTo::Place {
318                            node: NodeId::new(12),
319                            place: PageBox {
320                                page: 4,
321                                x: 72.0,
322                                y: 72.0,
323                                width: 252.0,
324                                height: 30.0,
325                            },
326                        },
327                    },
328                    Link {
329                        areas: vec![],
330                        to: LinkTo::Uri("https://example.com".into()),
331                    },
332                ],
333            }],
334            fonts: vec![FontRefEntry {
335                family: "eb garamond".into(),
336                name: "EB Garamond Regular".into(),
337                style: "Regular".into(),
338                attributes: FaceAttributes::REGULAR,
339                variations: vec![AxisSetting {
340                    tag: *b"wght",
341                    value: 400.0,
342                }],
343            }],
344            assets: vec![Asset {
345                url: "plate.jpg".into(),
346                intrinsic: Intrinsic {
347                    width: 480,
348                    height: 320,
349                    dpi_x: 300.0,
350                    dpi_y: 300.0,
351                    sized: true,
352                },
353            }],
354            warnings: vec![Warning {
355                message: "a table became prose".into(),
356                origin: Some("ch01.md:12:1".into()),
357            }],
358            navigation: Default::default(),
359        }
360    }
361
362    /// A reply as a `LayoutOutput`, for re-encoding it and comparing
363    /// the bytes: sound whenever the reply is a whole book, which is
364    /// all the round-trip tests below ask of it.
365    fn as_output(reply: Reply) -> LayoutOutput {
366        LayoutOutput {
367            pages: reply.pages,
368            fonts: reply.fonts,
369            assets: reply.assets,
370            warnings: reply.warnings,
371            navigation: Default::default(),
372        }
373    }
374
375    /// What went out comes back, and going out again writes the same
376    /// bytes.
377    #[test]
378    fn the_wire_round_trips() {
379        let bytes = encode(&output()).unwrap();
380        let read = decode(&bytes).unwrap();
381        assert_eq!(read.pages, output().pages);
382        assert_eq!(read.first, 0, "a whole-book reply starts at page 0");
383        assert_eq!(
384            read.book_pages,
385            output().pages.len(),
386            "a whole-book reply's total is its own page count"
387        );
388        assert_eq!(read.fonts, output().fonts);
389        assert_eq!(read.assets, output().assets);
390        assert_eq!(read.warnings, output().warnings);
391        assert_eq!(encode(&as_output(read)).unwrap(), bytes);
392    }
393
394    /// The version leads the bytes, so a host reads it before it
395    /// commits to anything.
396    #[test]
397    fn the_version_leads_the_bytes() {
398        let bytes = encode(&output()).unwrap();
399        assert_eq!(version(&bytes).unwrap(), VERSION);
400        assert_eq!(bytes[0], VERSION as u8);
401    }
402
403    /// A version this build does not write is refused rather than
404    /// read as best it can be.
405    #[test]
406    fn an_unknown_version_is_refused() {
407        let mut bytes = encode(&output()).unwrap();
408        bytes[0] = VERSION as u8 + 1;
409        assert!(matches!(decode(&bytes), Err(WireError::Version { .. })));
410    }
411
412    /// A ranged reply carries only its own slice, but the tables and
413    /// the book's total page count are the whole run's.
414    #[test]
415    fn a_range_carries_only_its_own_slice_with_the_full_tables() {
416        let mut book = output();
417        book.pages.push(Page {
418            number: 2,
419            side: Side::Verso,
420            width: 396.0,
421            height: 612.0,
422            bleed: 0.0,
423            slug: 0.0,
424            sections: vec![],
425            items: vec![],
426            links: vec![],
427        });
428        let bytes = encode_range(&book, 1, 1).unwrap();
429        let read = decode(&bytes).unwrap();
430        assert_eq!(read.pages, book.pages[1..2]);
431        assert_eq!(read.first, 1);
432        assert_eq!(read.book_pages, 2);
433        assert_eq!(read.fonts, book.fonts, "the font table is not sliced");
434        assert_eq!(read.assets, book.assets, "the asset table is not sliced");
435        assert_eq!(read.warnings, book.warnings, "the warnings are not sliced");
436    }
437
438    /// A range past the end of the book is clamped to what is left
439    /// rather than refused or panicking: a page asked for from a book
440    /// an edit just shortened still gets an answer.
441    #[test]
442    fn a_range_past_the_end_clamps_rather_than_panics() {
443        let book = output();
444        let bytes = encode_range(&book, 5, 3).unwrap();
445        let read = decode(&bytes).unwrap();
446        assert!(read.pages.is_empty());
447        assert_eq!(read.first, 1, "first clamps to the book's own length");
448        assert_eq!(read.book_pages, 1);
449    }
450
451    /// An EPUB's files cross with their paths, media types and
452    /// spine, and a version this build does not write is refused.
453    #[test]
454    fn an_epub_s_files_round_trip() {
455        let files = EpubFiles {
456            warnings: output().warnings,
457            spine: vec![
458                EpubSpineEntry {
459                    path: "EPUB/section-001.xhtml".into(),
460                    section: Some(NodeId::new(7)),
461                },
462                EpubSpineEntry {
463                    path: "EPUB/section-002.xhtml".into(),
464                    section: None,
465                },
466            ],
467            files: vec![
468                EpubFile {
469                    path: "mimetype".into(),
470                    media_type: "text/plain".into(),
471                    bytes: b"application/epub+zip".to_vec(),
472                },
473                EpubFile {
474                    path: "EPUB/section-001.xhtml".into(),
475                    media_type: "application/xhtml+xml".into(),
476                    bytes: b"<html/>".to_vec(),
477                },
478            ],
479        };
480        let bytes = encode_epub_files(&files).unwrap();
481        assert_eq!(version(&bytes).unwrap(), VERSION);
482        assert_eq!(decode_epub_files(&bytes).unwrap(), files);
483
484        let mut stale = bytes;
485        stale[0] = VERSION as u8 + 1;
486        assert!(matches!(
487            decode_epub_files(&stale),
488            Err(WireError::Version { .. })
489        ));
490    }
491
492    /// An EPUB crosses whole, its warnings beside it, and a version
493    /// this build does not write is refused.
494    #[test]
495    fn an_epub_round_trips_with_its_warnings() {
496        let file = b"PK\x03\x04mimetypeapplication/epub+zip".to_vec();
497        let warnings = output().warnings;
498        let bytes = encode_epub(&file, &warnings).unwrap();
499        assert_eq!(version(&bytes).unwrap(), VERSION);
500        assert_eq!(
501            decode_epub(&bytes).unwrap(),
502            Epub {
503                warnings,
504                bytes: file
505            }
506        );
507
508        let mut stale = bytes;
509        stale[0] = VERSION as u8 + 1;
510        assert!(matches!(
511            decode_epub(&stale),
512            Err(WireError::Version { .. })
513        ));
514    }
515}