1use super::ModuleError;
2use super::codec::{Reader, Writer};
3use super::crc::{crc32, extend};
4use super::strings::StringTable;
5
6pub const MAGIC: [u8; 8] = [0x89, b'I', b'W', b'M', 0x0D, 0x0A, 0x1A, 0x0A];
7
8pub const OPTIONAL: u32 = 1;
10
11pub const EXTENSIONS: u32 = 0x8000;
13
14const HEADER: usize = 32;
15const ENTRY: usize = 28;
16const HEADER_CRC: usize = 28;
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub struct Version {
20 pub major: u16,
21 pub minor: u16,
22}
23
24impl Version {
25 pub const CURRENT: Self = Self { major: 0, minor: 1 };
26
27 pub const fn reads(self, found: Self) -> bool {
29 found.major == self.major && (self.major != 0 || found.minor == self.minor)
30 }
31}
32
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub struct Section {
36 pub id: u32,
37 pub name: &'static str,
38}
39
40impl Section {
41 pub const STRINGS: Self = Self { id: 1, name: "STRINGS" };
42 pub const DIRECTORY: Self = Self { id: 2, name: "DIRECTORY" };
43 pub const OPTIONS: Self = Self { id: 3, name: "OPTIONS" };
44 pub const LAYOUT: Self = Self { id: 4, name: "LAYOUT" };
45 pub const LIR: Self = Self { id: 5, name: "LIR" };
46 pub const SQL: Self = Self { id: 6, name: "SQL" };
47 pub const BMS: Self = Self { id: 7, name: "BMS" };
48 pub const DEBUG: Self = Self { id: 8, name: "DEBUG" };
49
50 pub const ALL: [Self; 8] =
51 [Self::STRINGS, Self::DIRECTORY, Self::OPTIONS, Self::LAYOUT, Self::LIR, Self::SQL, Self::BMS, Self::DEBUG];
52
53 pub fn by_id(id: u32) -> Option<Self> {
54 Self::ALL.into_iter().find(|s| s.id == id)
55 }
56}
57
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub struct SectionEntry {
60 pub id: u32,
61 pub flags: u32,
62 pub offset: u64,
63 pub length: u64,
64 pub crc: u32,
65}
66
67impl SectionEntry {
68 pub fn name(&self) -> Option<&'static str> {
69 Section::by_id(self.id).map(|s| s.name)
70 }
71
72 pub fn optional(&self) -> bool {
73 self.flags & OPTIONAL != 0
74 }
75}
76
77fn le<const N: usize>(bytes: &[u8], at: usize) -> Option<[u8; N]> {
78 bytes.get(at..)?.first_chunk().copied()
79}
80
81fn u16_at(bytes: &[u8], at: usize) -> Option<u16> {
82 le(bytes, at).map(u16::from_le_bytes)
83}
84
85fn u32_at(bytes: &[u8], at: usize) -> Option<u32> {
86 le(bytes, at).map(u32::from_le_bytes)
87}
88
89fn u64_at(bytes: &[u8], at: usize) -> Option<u64> {
90 le(bytes, at).map(u64::from_le_bytes)
91}
92
93fn assemble(version: Version, features: u32, sections: &[(u32, u32, &[u8])]) -> Vec<u8> {
95 let table_end = HEADER + sections.len() * ENTRY;
96 let file_len = table_end + sections.iter().map(|s| s.2.len()).sum::<usize>();
97 let mut out = Vec::with_capacity(file_len);
98 out.extend_from_slice(&MAGIC);
99 out.extend_from_slice(&version.major.to_le_bytes());
100 out.extend_from_slice(&version.minor.to_le_bytes());
101 out.extend_from_slice(&features.to_le_bytes());
102 out.extend_from_slice(&(sections.len() as u32).to_le_bytes());
103 out.extend_from_slice(&(file_len as u64).to_le_bytes());
104 out.extend_from_slice(&[0; 4]);
105 let mut offset = table_end as u64;
106 for &(id, flags, body) in sections {
107 out.extend_from_slice(&id.to_le_bytes());
108 out.extend_from_slice(&flags.to_le_bytes());
109 out.extend_from_slice(&offset.to_le_bytes());
110 out.extend_from_slice(&(body.len() as u64).to_le_bytes());
111 out.extend_from_slice(&crc32(body).to_le_bytes());
112 offset += body.len() as u64;
113 }
114 let crc = extend(crc32(&out[..HEADER_CRC]), &out[HEADER..]);
115 out[HEADER_CRC..HEADER].copy_from_slice(&crc.to_le_bytes());
116 for &(_, _, body) in sections {
117 out.extend_from_slice(body);
118 }
119 out
120}
121
122#[derive(Debug, Default)]
124pub struct ModuleWriter {
125 writer: Writer,
126 sections: Vec<(u32, u32, Vec<u8>)>,
127}
128
129impl ModuleWriter {
130 pub fn new() -> Self {
131 Self::default()
132 }
133
134 pub fn section(&mut self, section: Section, build: impl FnOnce(&mut Writer)) {
136 self.push(section.id, 0, build);
137 }
138
139 pub fn extension(&mut self, id: u32, build: impl FnOnce(&mut Writer)) {
141 assert!(id >= EXTENSIONS, "extension section {id:#x} is below {EXTENSIONS:#x}");
142 self.push(id, OPTIONAL, build);
143 }
144
145 fn push(&mut self, id: u32, flags: u32, build: impl FnOnce(&mut Writer)) {
146 let last = self.sections.last().map_or(Section::STRINGS.id, |s| s.0);
147 assert!(id > last, "section {id:#x} written after section {last:#x}");
148 build(&mut self.writer);
149 let body = self.writer.take();
150 self.sections.push((id, flags, body));
151 }
152
153 pub fn finish(self) -> Vec<u8> {
155 for required in &Section::ALL[1..] {
156 assert!(self.sections.iter().any(|s| s.0 == required.id), "section {} was not written", required.name);
157 }
158 let strings = self.writer.strings().encode();
159 let mut sections = vec![(Section::STRINGS.id, 0, strings.as_slice())];
160 sections.extend(self.sections.iter().map(|(id, flags, body)| (*id, *flags, body.as_slice())));
161 assemble(Version::CURRENT, 0, §ions)
162 }
163}
164
165#[derive(Clone, Debug)]
167pub struct Module<'a> {
168 bytes: &'a [u8],
169 version: Version,
170 sections: Vec<SectionEntry>,
171}
172
173impl<'a> Module<'a> {
174 pub fn read(bytes: &'a [u8]) -> Result<Self, ModuleError> {
176 let actual = bytes.len() as u64;
177 let shown = bytes.len().min(MAGIC.len());
178 if bytes[..shown] != MAGIC[..shown] {
179 return Err(ModuleError::NotAModule);
180 }
181 let truncated = ModuleError::Truncated { expected: HEADER as u64, actual };
182 let header = (
183 u16_at(bytes, 8),
184 u16_at(bytes, 10),
185 u32_at(bytes, 12),
186 u32_at(bytes, 16),
187 u64_at(bytes, 20),
188 u32_at(bytes, HEADER_CRC),
189 );
190 let (Some(major), Some(minor), Some(features), Some(count), Some(file_len), Some(stored)) = header else {
191 return Err(truncated);
192 };
193 let version = Version { major, minor };
194 if !Version::CURRENT.reads(version) {
195 return Err(ModuleError::Version(version));
196 }
197 if actual < file_len {
198 return Err(ModuleError::Truncated { expected: file_len, actual });
199 }
200 if actual > file_len {
201 return Err(ModuleError::TrailingBytes { expected: file_len, actual });
202 }
203 let table_end = HEADER as u64 + u64::from(count) * ENTRY as u64;
204 let table = bytes.get(HEADER..table_end.min(actual) as usize).unwrap_or_default();
205 let computed = extend(crc32(&bytes[..HEADER_CRC]), table);
206 if computed != stored {
207 return Err(ModuleError::HeaderChecksum { computed, stored });
208 }
209 if features != 0 {
210 return Err(ModuleError::Feature(features));
211 }
212 let malformed = |offset, reason| ModuleError::Malformed { section: "section table", offset, reason };
213 if table_end > file_len {
214 return Err(malformed(
215 16,
216 format!("{count} sections need a table to byte {table_end}, past the end at {file_len}"),
217 ));
218 }
219
220 let mut sections: Vec<SectionEntry> = Vec::with_capacity(count as usize);
221 let mut next = table_end;
222 for at in (HEADER..table_end as usize).step_by(ENTRY) {
223 let fields = (
224 u32_at(bytes, at),
225 u32_at(bytes, at + 4),
226 u64_at(bytes, at + 8),
227 u64_at(bytes, at + 16),
228 u32_at(bytes, at + 24),
229 );
230 let (Some(id), Some(flags), Some(offset), Some(length), Some(crc)) = fields else {
231 return Err(truncated);
232 };
233 let entry = SectionEntry { id, flags, offset, length, crc };
234 if let Some(last) = sections.last()
235 && last.id >= id
236 {
237 return Err(malformed(at, format!("section {id:#x} follows section {:#x}", last.id)));
238 }
239 if offset != next {
240 return Err(malformed(at, format!("section {id:#x} begins at byte {offset}, not {next}")));
241 }
242 next = match offset.checked_add(length) {
243 Some(end) if end <= file_len => end,
244 _ => return Err(malformed(at, format!("section {id:#x} of {length} bytes runs past the end"))),
245 };
246 if flags & !OPTIONAL != 0 {
247 return Err(malformed(at, format!("section {id:#x} has flags {flags:#x}")));
248 }
249 match (Section::by_id(id), entry.optional()) {
250 (Some(known), true) => {
251 return Err(malformed(at, format!("required section {} is flagged optional", known.name)));
252 }
253 (None, false) => return Err(ModuleError::UnknownSection(id)),
254 _ => {}
255 }
256 sections.push(entry);
257 }
258 if next != file_len {
259 return Err(malformed(HEADER, format!("the sections end at byte {next}, before the end at {file_len}")));
260 }
261 if let Some(missing) = Section::ALL.iter().find(|s| !sections.iter().any(|e| e.id == s.id)) {
262 return Err(ModuleError::MissingSection(missing.id));
263 }
264 Ok(Self { bytes, version, sections })
265 }
266
267 pub fn version(&self) -> Version {
268 self.version
269 }
270
271 pub fn sections(&self) -> &[SectionEntry] {
273 &self.sections
274 }
275
276 pub fn body(&self, id: u32) -> Result<&'a [u8], ModuleError> {
278 let entry = self.sections.iter().find(|e| e.id == id).ok_or(ModuleError::MissingSection(id))?;
279 let body = usize::try_from(entry.offset)
280 .ok()
281 .zip(usize::try_from(entry.length).ok())
282 .and_then(|(start, len)| self.bytes.get(start..start.checked_add(len)?))
283 .ok_or(ModuleError::Truncated {
284 expected: entry.offset.saturating_add(entry.length),
285 actual: self.bytes.len() as u64,
286 })?;
287 let computed = crc32(body);
288 if computed != entry.crc {
289 return Err(ModuleError::SectionChecksum { id, computed, stored: entry.crc });
290 }
291 Ok(body)
292 }
293
294 pub fn strings(&self) -> Result<StringTable, ModuleError> {
295 StringTable::decode(self.body(Section::STRINGS.id)?)
296 }
297
298 pub fn reader<'r>(&self, section: Section, strings: &'r StringTable) -> Result<Reader<'r>, ModuleError>
299 where
300 'a: 'r,
301 {
302 Ok(Reader::new(section.name, self.body(section.id)?, strings))
303 }
304}
305
306#[cfg(test)]
307mod tests {
308 use super::*;
309 use crate::module::codec::{Decode, Encode};
310
311 const TABLE_END: usize = HEADER + 8 * ENTRY;
312
313 fn names(texts: &[&str]) -> Vec<String> {
314 texts.iter().map(|s| (*s).to_owned()).collect()
315 }
316
317 fn sample(ids: &[String]) -> Vec<u8> {
319 let mut w = ModuleWriter::new();
320 w.section(Section::DIRECTORY, |w| ids.to_vec().encode(w));
321 for section in &Section::ALL[2..] {
322 w.section(*section, |w| w.count(0));
323 }
324 w.finish()
325 }
326
327 fn plain() -> Vec<(u32, u32, &'static [u8])> {
329 Section::ALL.iter().map(|s| (s.id, 0, &[0u8][..])).collect()
330 }
331
332 fn read(bytes: &[u8]) -> Result<Vec<u32>, ModuleError> {
333 Module::read(bytes).map(|m| m.sections().iter().map(|e| e.id).collect())
334 }
335
336 fn reseal(bytes: &mut [u8]) {
337 let count = u32::from_le_bytes(bytes[16..20].try_into().unwrap()) as usize;
338 let end = (HEADER + count * ENTRY).min(bytes.len());
339 let crc = extend(crc32(&bytes[..HEADER_CRC]), &bytes[HEADER..end]);
340 bytes[HEADER_CRC..HEADER].copy_from_slice(&crc.to_le_bytes());
341 }
342
343 fn table_malformed(result: Result<Vec<u32>, ModuleError>) -> String {
344 match result {
345 Err(ModuleError::Malformed { section: "section table", reason, .. }) => reason,
346 other => panic!("{other:?}"),
347 }
348 }
349
350 #[test]
351 fn a_module_lists_its_sections_and_decodes_them() {
352 let ids = names(&["PAYROLL", "SUB", "PAYROLL"]);
353 let bytes = sample(&ids);
354 let module = Module::read(&bytes).unwrap();
355 assert_eq!(module.version(), Version::CURRENT);
356 let listed: Vec<_> = module.sections().iter().map(|e| (e.id, e.name(), e.optional())).collect();
357 let expected: Vec<_> = Section::ALL.iter().map(|s| (s.id, Some(s.name), false)).collect();
358 assert_eq!(listed, expected);
359 let strings = module.strings().unwrap();
360 assert_eq!(strings.iter().collect::<Vec<_>>(), ["PAYROLL", "SUB"]);
361 let mut r = module.reader(Section::DIRECTORY, &strings).unwrap();
362 assert_eq!(Vec::<String>::decode(&mut r), Ok(ids));
363 assert_eq!(r.finish(), Ok(()));
364 assert_eq!(module.body(Section::DEBUG.id), Ok(&[0u8][..]));
365 }
366
367 #[test]
368 fn the_header_and_table_have_the_documented_layout() {
369 let bytes = sample(&names(&["A"]));
370 assert_eq!(bytes[..8], [0x89, 0x49, 0x57, 0x4D, 0x0D, 0x0A, 0x1A, 0x0A]);
371 assert_eq!(bytes[8..20], [0, 0, 1, 0, 0, 0, 0, 0, 8, 0, 0, 0]);
372 assert_eq!(u64_at(&bytes, 20), Some(bytes.len() as u64));
373 assert_eq!(u32_at(&bytes, HEADER_CRC), Some(extend(crc32(&bytes[..28]), &bytes[32..TABLE_END])));
374 let strings_body = [1, 1, b'A'];
375 assert_eq!(u32_at(&bytes, 32), Some(1));
376 assert_eq!(u32_at(&bytes, 36), Some(0));
377 assert_eq!(u64_at(&bytes, 40), Some(TABLE_END as u64));
378 assert_eq!(u64_at(&bytes, 48), Some(3));
379 assert_eq!(u32_at(&bytes, 56), Some(crc32(&strings_body)));
380 assert_eq!(bytes[TABLE_END..TABLE_END + 3], strings_body);
381 assert_eq!(u64_at(&bytes, 32 + ENTRY + 8), Some(TABLE_END as u64 + 3));
382 assert_eq!(bytes.len(), TABLE_END + 3 + 2 + 6);
383 }
384
385 #[test]
386 fn reading_and_writing_again_gives_the_same_bytes() {
387 let bytes = sample(&names(&["MAIN", "", "SUB", "MAIN"]));
388 assert_eq!(sample(&names(&["MAIN", "", "SUB", "MAIN"])), bytes);
389 let module = Module::read(&bytes).unwrap();
390 let strings = module.strings().unwrap();
391 let mut r = module.reader(Section::DIRECTORY, &strings).unwrap();
392 let decoded = Vec::<String>::decode(&mut r).unwrap();
393 assert_eq!(sample(&decoded), bytes);
394 }
395
396 #[test]
397 fn every_strict_prefix_is_truncated() {
398 let bytes = sample(&names(&["PAYROLL"]));
399 for len in 0..bytes.len() {
400 assert!(matches!(read(&bytes[..len]), Err(ModuleError::Truncated { .. })), "{len}");
401 }
402 assert_eq!(read(&bytes[..100]), Err(ModuleError::Truncated { expected: bytes.len() as u64, actual: 100 }));
403 assert_eq!(read(&bytes[..20]), Err(ModuleError::Truncated { expected: 32, actual: 20 }));
404 }
405
406 #[test]
407 fn a_bad_magic_is_not_a_module() {
408 let bytes = sample(&names(&["A"]));
409 let mut changed = bytes.clone();
410 changed[0] = 0x09;
411 assert_eq!(read(&changed), Err(ModuleError::NotAModule));
412 let text_mode: Vec<u8> = [&bytes[..4], &bytes[5..]].concat();
413 assert_eq!(read(&text_mode), Err(ModuleError::NotAModule));
414 assert_eq!(read(b"IDENTIFICATION DIVISION."), Err(ModuleError::NotAModule));
415 assert_eq!(read(b"\x89IX"), Err(ModuleError::NotAModule));
416 assert_eq!(ModuleError::NotAModule.to_string(), "not an ironwork load module");
417 }
418
419 #[test]
420 fn a_longer_file_has_trailing_bytes() {
421 let mut bytes = sample(&names(&["A"]));
422 let len = bytes.len() as u64;
423 bytes.push(0);
424 assert_eq!(read(&bytes), Err(ModuleError::TrailingBytes { expected: len, actual: len + 1 }));
425 }
426
427 #[test]
428 fn another_major_or_before_one_another_minor_is_refused() {
429 for version in [Version { major: 1, minor: 0 }, Version { major: 0, minor: 2 }, Version { major: 0, minor: 0 }]
430 {
431 assert_eq!(read(&assemble(version, 0, &plain())), Err(ModuleError::Version(version)));
432 }
433 let message = ModuleError::Version(Version { major: 2, minor: 0 }).to_string();
434 assert_eq!(message, "load module format 2.0; this ironwork reads 0.1. Compile the source again");
435 let reader = Version { major: 1, minor: 2 };
436 assert!(reader.reads(Version { major: 1, minor: 0 }));
437 assert!(reader.reads(Version { major: 1, minor: 5 }));
438 assert!(!reader.reads(Version { major: 2, minor: 0 }));
439 assert!(!reader.reads(Version { major: 0, minor: 2 }));
440 assert!(Version::CURRENT.reads(Version::CURRENT));
441 }
442
443 #[test]
444 fn a_changed_header_or_table_byte_is_a_bad_header_checksum() {
445 let bytes = sample(&names(&["A"]));
446 for at in (12..20).chain(HEADER_CRC..TABLE_END) {
447 let mut changed = bytes.clone();
448 changed[at] ^= 0x10;
449 assert!(matches!(read(&changed), Err(ModuleError::HeaderChecksum { .. })), "byte {at}");
450 }
451 let mut changed = bytes.clone();
452 changed[20] ^= 1;
453 assert!(matches!(read(&changed), Err(ModuleError::Truncated { .. } | ModuleError::TrailingBytes { .. })));
454 }
455
456 #[test]
457 fn a_set_feature_bit_is_refused_by_name() {
458 assert_eq!(read(&assemble(Version::CURRENT, 4, &plain())), Err(ModuleError::Feature(4)));
459 assert_eq!(
460 ModuleError::Feature(4).to_string(),
461 "load module needs features 0x00000004, which this ironwork lacks"
462 );
463 }
464
465 #[test]
466 fn a_changed_section_byte_is_found_when_the_section_is_read() {
467 let bytes = sample(&names(&["A"]));
468 let module = Module::read(&bytes).unwrap();
469 let layout = module.sections()[3];
470 let mut changed = bytes.clone();
471 changed[layout.offset as usize] ^= 0x01;
472 let module = Module::read(&changed).unwrap();
473 let err = module.body(Section::LAYOUT.id).unwrap_err();
474 let computed = crc32(&[1]);
475 assert_eq!(err, ModuleError::SectionChecksum { id: 4, computed, stored: layout.crc });
476 assert_eq!(
477 err.to_string(),
478 format!("section LAYOUT is corrupt (checksum {computed:08X}, expected {:08X})", layout.crc)
479 );
480 assert!(module.body(Section::LIR.id).is_ok());
481 assert!(module.strings().is_ok());
482 }
483
484 #[test]
485 fn an_unknown_section_is_skipped_only_if_optional() {
486 let mut sections = plain();
487 sections.push((9, 0, &[1, 2]));
488 assert_eq!(read(&assemble(Version::CURRENT, 0, §ions)), Err(ModuleError::UnknownSection(9)));
489 assert_eq!(ModuleError::UnknownSection(9).to_string(), "required section 0x9 is unknown to this ironwork");
490
491 let mut sections = plain();
492 sections.push((9, OPTIONAL, &[1, 2]));
493 sections.push((EXTENSIONS + 1, OPTIONAL, &[3]));
494 let bytes = assemble(Version::CURRENT, 0, §ions);
495 assert_eq!(read(&bytes), Ok(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, EXTENSIONS + 1]));
496 let module = Module::read(&bytes).unwrap();
497 assert_eq!(module.sections()[8].name(), None);
498 assert_eq!(module.body(9), Ok(&[1u8, 2][..]));
499
500 let mut w = ModuleWriter::new();
501 for section in &Section::ALL[1..] {
502 w.section(*section, |w| w.count(0));
503 }
504 w.extension(EXTENSIONS, |w| w.string("NOTE"));
505 let module_bytes = w.finish();
506 let module = Module::read(&module_bytes).unwrap();
507 assert!(module.sections()[8].optional());
508 assert_eq!(module.strings().unwrap().get(0), Some("NOTE"));
509 }
510
511 #[test]
512 fn flags_must_match_what_the_reader_knows() {
513 let mut sections = plain();
514 sections[3].1 = OPTIONAL;
515 assert_eq!(
516 table_malformed(read(&assemble(Version::CURRENT, 0, §ions))),
517 "required section LAYOUT is flagged optional"
518 );
519 let mut sections = plain();
520 sections[2].1 = 2;
521 assert_eq!(table_malformed(read(&assemble(Version::CURRENT, 0, §ions))), "section 0x3 has flags 0x2");
522 }
523
524 #[test]
525 fn a_missing_required_section_is_refused() {
526 let sections = &plain()[..7];
527 assert_eq!(read(&assemble(Version::CURRENT, 0, sections)), Err(ModuleError::MissingSection(8)));
528 assert_eq!(ModuleError::MissingSection(8).to_string(), "required section DEBUG is missing");
529 assert_eq!(read(&assemble(Version::CURRENT, 0, &[])), Err(ModuleError::MissingSection(1)));
530 let bytes = sample(&[]);
531 assert_eq!(Module::read(&bytes).unwrap().body(9), Err(ModuleError::MissingSection(9)));
532 }
533
534 #[test]
535 fn only_the_canonical_layout_is_read() {
536 let mut sections = plain();
537 sections.swap(4, 5);
538 assert_eq!(table_malformed(read(&assemble(Version::CURRENT, 0, §ions))), "section 0x5 follows section 0x6");
539 let mut sections = plain();
540 sections.insert(4, (4, 0, &[0]));
541 assert_eq!(table_malformed(read(&assemble(Version::CURRENT, 0, §ions))), "section 0x4 follows section 0x4");
542
543 let bytes = assemble(Version::CURRENT, 0, &plain());
544 let mut gap = bytes.clone();
545 gap[32 + ENTRY + 8] += 1;
546 reseal(&mut gap);
547 assert_eq!(
548 table_malformed(read(&gap)),
549 format!("section 0x2 begins at byte {}, not {}", TABLE_END + 2, TABLE_END + 1)
550 );
551 let mut long = bytes.clone();
552 long[32 + 7 * ENTRY + 16] += 1;
553 reseal(&mut long);
554 assert_eq!(table_malformed(read(&long)), "section 0x8 of 2 bytes runs past the end");
555 let mut short = bytes.clone();
556 short[32 + 7 * ENTRY + 16] -= 1;
557 reseal(&mut short);
558 assert_eq!(
559 table_malformed(read(&short)),
560 format!("the sections end at byte {}, before the end at {}", TABLE_END + 7, TABLE_END + 8)
561 );
562 let mut many = bytes;
563 many[16] = 200;
564 reseal(&mut many);
565 assert_eq!(
566 table_malformed(read(&many)),
567 format!("200 sections need a table to byte {}, past the end at {}", HEADER + 200 * ENTRY, TABLE_END + 8)
568 );
569 }
570
571 #[test]
572 #[should_panic(expected = "section 0x3 written after section 0x4")]
573 fn the_writer_takes_sections_in_id_order() {
574 let mut w = ModuleWriter::new();
575 w.section(Section::LAYOUT, |_| {});
576 w.section(Section::OPTIONS, |_| {});
577 }
578
579 #[test]
580 #[should_panic(expected = "section SQL was not written")]
581 fn the_writer_writes_every_required_section() {
582 let mut w = ModuleWriter::new();
583 for section in
584 [Section::DIRECTORY, Section::OPTIONS, Section::LAYOUT, Section::LIR, Section::BMS, Section::DEBUG]
585 {
586 w.section(section, |w| w.count(0));
587 }
588 w.finish();
589 }
590}