Files
Liber-public/crates/liber-format/tests/common/mod.rs
T

357 lines
13 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Fixture builders: every test book is generated here, so no binary is ever committed.
#![allow(dead_code)]
use liber_format::zip::ZipWriter;
pub const CONTAINER: &str = r#"<?xml version="1.0"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
<rootfiles><rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/></rootfiles>
</container>"#;
pub fn xhtml(body: &str) -> String {
format!(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE html>\n<html xmlns=\"http://www.w3.org/1999/xhtml\" \
xmlns:epub=\"http://www.idpf.org/2007/ops\"><head><title>t</title>\
<link rel=\"stylesheet\" href=\"style.css\"/></head><body>{body}</body></html>"
)
}
/// An EPUB 3 with the given chapter bodies (`(title, body)`), plus extra files.
pub struct Epub {
pub title: String,
pub chapters: Vec<(String, String)>,
pub extra: Vec<(String, Vec<u8>)>,
pub extra_manifest: String,
pub metadata_extra: String,
pub opf_override: Option<String>,
}
impl Epub {
pub fn new(title: &str) -> Epub {
Epub {
title: title.into(),
chapters: vec![],
extra: vec![],
extra_manifest: String::new(),
metadata_extra: String::new(),
opf_override: None,
}
}
pub fn chapter(mut self, title: &str, body: &str) -> Epub {
self.chapters.push((title.into(), body.into()));
self
}
pub fn file(mut self, name: &str, data: &[u8]) -> Epub {
self.extra.push((name.into(), data.to_vec()));
self
}
pub fn opf(&self) -> String {
if let Some(o) = &self.opf_override {
return o.clone();
}
let mut manifest =
String::from(r#"<item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/>"#);
let mut spine = String::new();
for (i, _) in self.chapters.iter().enumerate() {
manifest
.push_str(&format!(r#"<item id="c{i}" href="text/ch{i}.xhtml" media-type="application/xhtml+xml"/>"#));
spine.push_str(&format!(r#"<itemref idref="c{i}"/>"#));
}
manifest.push_str(&self.extra_manifest);
format!(
r##"<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="id">
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
<dc:title>{}</dc:title><dc:creator id="a1">Karel Čapek</dc:creator>
<meta refines="#a1" property="role">aut</meta>
<dc:creator id="t1">Some Translator</dc:creator><meta refines="#t1" property="role">trl</meta>
<dc:language>cs</dc:language><dc:identifier id="id">urn:isbn:978-80-207-1247-9</dc:identifier>
<dc:description>&lt;p&gt;A &lt;b&gt;play&lt;/b&gt; about robots.&lt;/p&gt;</dc:description>
<dc:subject>Drama</dc:subject>
<meta property="belongs-to-collection" id="s1">Plays</meta>
<meta refines="#s1" property="collection-type">series</meta><meta refines="#s1" property="group-position">2</meta>
{}
</metadata>
<manifest>{manifest}</manifest>
<spine>{spine}</spine>
</package>"##,
self.title, self.metadata_extra
)
}
pub fn nav(&self) -> String {
let mut li = String::new();
for (i, (t, _)) in self.chapters.iter().enumerate() {
li.push_str(&format!(r#"<li><a href="text/ch{i}.xhtml">{t}</a></li>"#));
}
xhtml(&format!(r#"<nav epub:type="toc"><ol>{li}</ol></nav>"#))
}
pub fn build(&self) -> Vec<u8> {
let mut w = ZipWriter::new(Vec::new());
w.add("mimetype", b"application/epub+zip", false).unwrap();
w.add("META-INF/container.xml", CONTAINER.as_bytes(), true).unwrap();
w.add("OEBPS/content.opf", self.opf().as_bytes(), true).unwrap();
w.add("OEBPS/nav.xhtml", self.nav().as_bytes(), true).unwrap();
for (i, (_, body)) in self.chapters.iter().enumerate() {
w.add(&format!("OEBPS/text/ch{i}.xhtml"), xhtml(body).as_bytes(), true).unwrap();
}
for (n, d) in &self.extra {
w.add(n, d, true).unwrap();
}
w.finish().unwrap()
}
}
/// One entry of a hand-made zip, for archives the safe writer refuses to make.
pub struct Raw {
pub name: String,
pub data: Vec<u8>,
pub deflate: bool,
pub unix_mode: u32,
/// Overrides the declared uncompressed size.
pub declared: Option<u32>,
}
impl Raw {
pub fn file(name: &str, data: &[u8]) -> Raw {
Raw { name: name.into(), data: data.to_vec(), deflate: true, unix_mode: 0o100644, declared: None }
}
}
pub fn raw_zip(entries: &[Raw]) -> Vec<u8> {
let mut out = Vec::new();
let mut central = Vec::new();
for e in entries {
let crc = crc32(&e.data);
let body = if e.deflate { deflate(&e.data) } else { e.data.clone() };
let method: u16 = if e.deflate { 8 } else { 0 };
let usize = e.declared.unwrap_or(e.data.len() as u32);
let off = out.len() as u32;
out.extend_from_slice(&0x0403_4b50u32.to_le_bytes());
out.extend_from_slice(&20u16.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(&method.to_le_bytes());
out.extend_from_slice(&[0, 0, 0x21, 0]);
out.extend_from_slice(&crc.to_le_bytes());
out.extend_from_slice(&(body.len() as u32).to_le_bytes());
out.extend_from_slice(&usize.to_le_bytes());
out.extend_from_slice(&(e.name.len() as u16).to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(e.name.as_bytes());
out.extend_from_slice(&body);
central.extend_from_slice(&0x0201_4b50u32.to_le_bytes());
central.extend_from_slice(&0x0314u16.to_le_bytes());
central.extend_from_slice(&20u16.to_le_bytes());
central.extend_from_slice(&0u16.to_le_bytes());
central.extend_from_slice(&method.to_le_bytes());
central.extend_from_slice(&[0, 0, 0x21, 0]);
central.extend_from_slice(&crc.to_le_bytes());
central.extend_from_slice(&(body.len() as u32).to_le_bytes());
central.extend_from_slice(&usize.to_le_bytes());
central.extend_from_slice(&(e.name.len() as u16).to_le_bytes());
central.extend_from_slice(&[0; 8]);
central.extend_from_slice(&(e.unix_mode << 16).to_le_bytes());
central.extend_from_slice(&off.to_le_bytes());
central.extend_from_slice(e.name.as_bytes());
}
let cd_off = out.len() as u32;
out.extend_from_slice(&central);
out.extend_from_slice(&0x0605_4b50u32.to_le_bytes());
out.extend_from_slice(&[0; 4]);
out.extend_from_slice(&(entries.len() as u16).to_le_bytes());
out.extend_from_slice(&(entries.len() as u16).to_le_bytes());
out.extend_from_slice(&(central.len() as u32).to_le_bytes());
out.extend_from_slice(&cd_off.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out
}
pub fn crc32(d: &[u8]) -> u32 {
let mut c: u32 = 0xffff_ffff;
for &b in d {
c ^= b as u32;
for _ in 0..8 {
c = if c & 1 != 0 { (c >> 1) ^ 0xedb8_8320 } else { c >> 1 };
}
}
!c
}
/// Raw deflate with stored blocks only (enough for fixtures; the bomb uses `deflate_zeros`).
pub fn deflate(d: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
let chunks: Vec<&[u8]> = if d.is_empty() { vec![&[][..]] } else { d.chunks(65_535).collect() };
for (i, c) in chunks.iter().enumerate() {
out.push(if i + 1 == chunks.len() { 1 } else { 0 });
out.extend_from_slice(&(c.len() as u16).to_le_bytes());
out.extend_from_slice(&(!(c.len() as u16)).to_le_bytes());
out.extend_from_slice(c);
}
out
}
/// A raw deflate stream of `n` zero bytes, tiny (fixed Huffman, length-258 back-references): a bomb.
pub fn deflate_zeros(n: usize) -> Vec<u8> {
struct Bits {
out: Vec<u8>,
acc: u32,
n: u32,
}
impl Bits {
fn put(&mut self, v: u32, len: u32) {
self.acc |= v << self.n;
self.n += len;
while self.n >= 8 {
self.out.push(self.acc as u8);
self.acc >>= 8;
self.n -= 8;
}
}
fn put_rev(&mut self, code: u32, len: u32) {
let mut r = 0;
for i in 0..len {
r |= ((code >> i) & 1) << (len - 1 - i);
}
self.put(r, len);
}
}
let mut b = Bits { out: vec![], acc: 0, n: 0 };
b.put(1, 1); // final
b.put(1, 2); // fixed Huffman
// literal 0: code 0x30 (8 bits)
b.put_rev(0x30, 8);
let mut left = n - 1;
while left >= 258 {
// length 258: code 285 → 7-bit code 285-256 = 29 → 0b0011101 (codes 256..279 are 7 bits from 0)... 285 is
// in 280..287: 8 bits, 0xC0 + (285 - 280).
b.put_rev(0xC0 + 5, 8);
// distance 1: code 0 (5 bits), no extra bits
b.put_rev(0, 5);
left -= 258;
}
for _ in 0..left {
b.put_rev(0x30, 8);
}
b.put_rev(0, 7); // end of block (256)
if b.n > 0 {
b.out.push(b.acc as u8);
}
b.out
}
/// A PalmDB MOBI 6 (or KF8 with `version = 8`) around `html`, uncompressed (1) or PalmDOC literals (2).
pub struct Mobi {
pub html: String,
pub compression: u16,
pub encryption: u16,
pub version: u32,
pub images: Vec<Vec<u8>>,
pub exth: Vec<(u32, Vec<u8>)>,
pub title: String,
}
impl Mobi {
pub fn new(html: &str) -> Mobi {
Mobi {
html: html.into(),
compression: 2,
encryption: 0,
version: 6,
images: vec![],
exth: vec![],
title: "Mobi Title".into(),
}
}
pub fn build(&self) -> Vec<u8> {
let text = self.html.as_bytes();
let mut text_recs: Vec<Vec<u8>> = Vec::new();
for chunk in text.chunks(4096) {
text_recs.push(match self.compression {
2 => palmdoc_literals(chunk),
_ => chunk.to_vec(),
});
}
let mut exth = Vec::new();
let mut entries = self.exth.clone();
entries.push((100, "Karel Čapek".as_bytes().to_vec()));
entries.push((104, b"9788020712479".to_vec()));
exth.extend_from_slice(b"EXTH");
let body_len: usize = entries.iter().map(|(_, v)| 8 + v.len()).sum();
exth.extend_from_slice(&((12 + body_len) as u32).to_be_bytes());
exth.extend_from_slice(&(entries.len() as u32).to_be_bytes());
for (t, v) in &entries {
exth.extend_from_slice(&t.to_be_bytes());
exth.extend_from_slice(&((8 + v.len()) as u32).to_be_bytes());
exth.extend_from_slice(v);
}
let header_len: u32 = 0xe8;
let mut r0 = vec![0u8; 16 + header_len as usize];
r0[0..2].copy_from_slice(&self.compression.to_be_bytes());
r0[4..8].copy_from_slice(&(text.len() as u32).to_be_bytes());
r0[8..10].copy_from_slice(&(text_recs.len() as u16).to_be_bytes());
r0[10..12].copy_from_slice(&4096u16.to_be_bytes());
r0[12..14].copy_from_slice(&self.encryption.to_be_bytes());
r0[16..20].copy_from_slice(b"MOBI");
r0[20..24].copy_from_slice(&header_len.to_be_bytes());
r0[24..28].copy_from_slice(&2u32.to_be_bytes());
r0[28..32].copy_from_slice(&65001u32.to_be_bytes());
r0[36..40].copy_from_slice(&self.version.to_be_bytes());
let first_image = 1 + text_recs.len() as u32;
r0[0x6c..0x70].copy_from_slice(&first_image.to_be_bytes());
r0[0x80..0x84].copy_from_slice(&0x40u32.to_be_bytes());
r0.extend_from_slice(&exth);
let name_off = r0.len() as u32;
r0[84..88].copy_from_slice(&name_off.to_be_bytes());
r0[88..92].copy_from_slice(&(self.title.len() as u32).to_be_bytes());
r0.extend_from_slice(self.title.as_bytes());
r0.extend_from_slice(&[0, 0]);
let mut recs = vec![r0];
recs.extend(text_recs);
recs.extend(self.images.iter().cloned());
let mut out = vec![0u8; 78 + recs.len() * 8 + 2];
out[..10].copy_from_slice(b"liber-test");
out[60..68].copy_from_slice(b"BOOKMOBI");
out[76..78].copy_from_slice(&(recs.len() as u16).to_be_bytes());
let mut off = out.len();
for (i, r) in recs.iter().enumerate() {
out[78 + i * 8..82 + i * 8].copy_from_slice(&(off as u32).to_be_bytes());
off += r.len();
}
for r in recs {
out.extend_from_slice(&r);
}
out
}
}
/// PalmDOC with literal runs only: bytes 0x09–0x7f as themselves, others in 1–8 byte literal runs.
pub fn palmdoc_literals(d: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
let mut i = 0;
while i < d.len() {
let b = d[i];
if (0x09..=0x7f).contains(&b) || b == 0 {
out.push(b);
i += 1;
} else {
let n = (d.len() - i).min(8);
out.push(n as u8);
out.extend_from_slice(&d[i..i + n]);
i += n;
}
}
out
}
/// A 1×1 PNG.
pub const PNG: &[u8] = &[
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6,
0, 0, 0, 0x1f, 0x15, 0xc4, 0x89, 0, 0, 0, 13, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf8, 0xcf, 0xc0, 0xf0,
0x1f, 0, 5, 0, 1, 0xff, 0x89, 0x99, 0x3d, 0x1d, 0, 0, 0, 0, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
];