1use crate::content::NodeId;
31use crate::fonts::FontRefEntry;
32use crate::images::Asset;
33use crate::pages::Page;
34use crate::{LayoutOutput, Warning};
35
36pub const VERSION: u16 = 22;
39
40#[derive(Debug, thiserror::Error)]
42pub enum WireError {
43 #[error("wire version {found}, expected {VERSION}")]
46 Version {
47 found: u16,
49 },
50 #[error("the wire could not be read: {0}")]
52 Malformed(#[from] postcard::Error),
53}
54
55#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
63pub struct Reply {
64 pub pages: Vec<Page>,
66 pub first: usize,
68 pub book_pages: usize,
71 pub fonts: Vec<FontRefEntry>,
73 pub assets: Vec<Asset>,
75 pub warnings: Vec<Warning>,
77}
78
79pub fn encode(output: &LayoutOutput) -> Result<Vec<u8>, WireError> {
81 encode_range(output, 0, output.pages.len())
82}
83
84pub 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
112pub 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#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
141pub struct Epub {
142 pub warnings: Vec<Warning>,
145 pub bytes: Vec<u8>,
147}
148
149pub fn encode_epub(bytes: &[u8], warnings: &[Warning]) -> Result<Vec<u8>, WireError> {
151 Ok(postcard::to_stdvec(&(VERSION, warnings, bytes))?)
152}
153
154pub 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#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
167pub struct EpubFiles {
168 pub warnings: Vec<Warning>,
170 pub spine: Vec<EpubSpineEntry>,
172 pub files: Vec<EpubFile>,
174}
175
176#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
178pub struct EpubSpineEntry {
179 pub path: String,
181 pub section: Option<NodeId>,
184}
185
186#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
188pub struct EpubFile {
189 pub path: String,
191 pub media_type: String,
193 pub bytes: Vec<u8>,
195}
196
197pub fn encode_epub_files(files: &EpubFiles) -> Result<Vec<u8>, WireError> {
199 Ok(postcard::to_stdvec(&(VERSION, files))?)
200}
201
202pub 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
212pub 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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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}