puns 0.1.1

Type punning proven at compile time: a safe alternative to transmute and to hand-written parsing of bytes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! Storage, in safe Rust, with nothing but `#[derive(Pun)]` and its options: the SQLite database
//! header, FAT boot sectors, GPT partition tables, and USB descriptors.
//!
//! As in `ethernet.rs`, the first half of this file is type declarations only: no `unsafe`, no
//! `impl`, no parsing code. The second half reads them in place, from bytes, and checks that
//! corrupted ones are rejected.
//!
//! What is specific to these formats, and what tells it:
//!
//! | Specificity                                    | Told by                                      |
//! |------------------------------------------------|----------------------------------------------|
//! | a magic of 16 bytes                            | `u128bec<0x5351_4c69_..>`                    |
//! | SQLite: a page size, a power of two (1: 65536) | `valid(1, 512, ..)`, `get(page_bytes: ..)`   |
//! | SQLite: the file is the pages the header tells | `assert(be(28, 4) * .. == ..)`               |
//! | FAT: the kind, by a count of clusters          | `assert({ let total = ..; .. < 65525 })`     |
//! | a jump that is one of two instructions         | `assert((be(0, 1) == 0xeb && ..) \|\| ..)`   |
//! | GPT: a sector size that the bytes do not tell  | a const parameter: `GptDisk<512>`            |
//! | GPT: the entries are where the header says     | `le(S + 72, 8) * S`                          |
//! | GPT: the CRC-32 of the partition entries       | `assert(crc32(start, ..) == le(S + 88, 4))`  |
//! | GPT: the CRC-32 of the header, over itself      | `assert(crc32(S, .., S + 16, S + 20) == ..)` |
//! | USB: descriptors of fixed lengths and types    | `u8c<18>`, `u8c<1>`                          |
//! | USB: descriptors that fill a configuration     | `size = total_length`, `assert(walk(9, ..))` |
//! | USB: the bit fields of an endpoint             | `get(input: bool = address & 0x80 != 0, ..)` |
//!
//! What is not covered, and why:
//!
//! - SQLite: the pages themselves (B-tree pages, of cells at offsets that a page tells, of
//!   varints) are more declarations, of the forms of `executables.rs` and `encodings.rs`.
//! - GPT: the name of a partition is UTF-16, for which the crate has no automaton: it is
//!   `[u16le; 36]`. The sector size is not in the bytes: it is a const parameter, `GptDisk<512>`.
//! - FAT: which of FAT12, FAT16 and FAT32 a volume is depends on its count of clusters, computed
//!   from the fields of its BIOS parameter block: both kinds of boot sector are declared, and an
//!   enum of references tells them apart. The FAT32 one reads that block with `le(..)`, since it
//!   is not repeated as fields there. The tables and the directories are more declarations of the
//!   same kind.
//! - USB: a configuration is followed by interface, endpoint and class descriptors, of their own
//!   sizes: they are read one by one by use code; the configuration checks that they fill its
//!   total length and counts its interfaces.
#![deny(unsafe_code)]

use puns::{
  Error, Pun, from_head,
  num::{u8c, u16be, u16le, u16lec, u32be, u32le, u64le, u128bec},
  try_pun_ref,
};

// -------------------------------------------------------------------------------------------------
// SQLite

/// The header of an SQLite database: its first 100 bytes.
#[derive(Pun)]
#[repr(C)]
// What a page leaves to the B-tree, once its reserved bytes are taken out, is at least 480 bytes.
#[pun(assert(reserved_space <= 32 || page_size + (page_size == 1) as u128 * 65535 - reserved_space >= 480))]
#[pun(get(page_bytes: u32 = page_size + (page_size == 1) as u128 * 65535))]
pub struct SqliteHeader {
  /// `SQLite format 3\0`.
  pub magic: u128bec<0x5351_4c69_7465_2066_6f72_6d61_7420_3300>,
  /// A power of two from 512 to 32768, or 1 for 65536.
  #[pun(valid(1, 512, 1024, 2048, 4096, 8192, 16384, 32768))]
  pub page_size: u16be,
  /// Legacy (1) or WAL (2).
  #[pun(valid(1..=2))]
  pub write_version: u8,
  #[pun(valid(1..=2))]
  pub read_version: u8,
  pub reserved_space: u8,
  pub max_payload_fraction: u8c<64>,
  pub min_payload_fraction: u8c<32>,
  pub leaf_payload_fraction: u8c<32>,
  pub change_counter: u32be,
  pub database_size: u32be,
  pub first_freelist_trunk: u32be,
  pub freelist_count: u32be,
  pub schema_cookie: u32be,
  #[pun(valid(1..=4))]
  pub schema_format: u32be,
  pub default_cache_size: u32be,
  pub largest_root_page: u32be,
  /// UTF-8, UTF-16LE, UTF-16BE.
  #[pun(valid(1..=3))]
  pub text_encoding: u32be,
  pub user_version: u32be,
  #[pun(valid(0..=1))]
  pub incremental_vacuum: u32be,
  pub application_id: u32be,
  pub reserved: [u8c<0>; 20],
  pub version_valid_for: u32be,
  pub sqlite_version: u32be,
}

/// A database file: pages of the size its header tells (1 means 65536), as many as it tells
/// when that count is valid, which it is when "version valid for" is the change counter.
#[derive(Pun)]
#[repr(C)]
#[pun(assert(size_of_val(self) % (page_size + (page_size == 1) as u128 * 65535) == 0))]
#[pun(assert(be(92, 4) != be(24, 4)
  || be(28, 4) * (page_size + (page_size == 1) as u128 * 65535) == size_of_val(self)))]
pub struct Sqlite {
  pub magic: u128bec<0x5351_4c69_7465_2066_6f72_6d61_7420_3300>,
  #[pun(valid(1, 512, 1024, 2048, 4096, 8192, 16384, 32768))]
  pub page_size: u16be,
  pub rest: [u8],
}

// -------------------------------------------------------------------------------------------------
// FAT

/// A FAT12 or FAT16 boot sector: fewer than 65525 clusters.
#[derive(Pun)]
#[repr(C)]
// A jump: a short one and a NOP, or a near one. (An element of an array field cannot be named
// by an expression, `jump[0]`: it is read with `be`.)
#[pun(assert((be(0, 1) == 0xeb && be(2, 1) == 0x90) || be(0, 1) == 0xe9))]
#[pun(assert(fat_size16 != 0 && root_entries != 0))]
// The count of clusters: the sectors of data, divided by the sectors of a cluster.
#[pun(assert({
  let total = if total16 != 0 { total16 } else { total32 };
  let root = (root_entries * 32 + bytes_per_sector - 1) / bytes_per_sector;
  (total - reserved_sectors - fats * fat_size16 - root) / sectors_per_cluster < 65525
}))]
pub struct Fat16Boot {
  pub jump: [u8; 3],
  pub oem: [u8; 8],
  #[pun(valid(512, 1024, 2048, 4096))]
  pub bytes_per_sector: u16le,
  #[pun(valid(1, 2, 4, 8, 16, 32, 64, 128))]
  pub sectors_per_cluster: u8,
  #[pun(valid(1..))]
  pub reserved_sectors: u16le,
  #[pun(valid(1..))]
  pub fats: u8,
  pub root_entries: u16le,
  pub total16: u16le,
  #[pun(valid(0xf0, 0xf8..=0xff))]
  pub media: u8,
  pub fat_size16: u16le,
  pub sectors_per_track: u16le,
  pub heads: u16le,
  pub hidden: u32le,
  pub total32: u32le,
  pub drive: u8,
  pub reserved: u8,
  pub boot_signature: u8c<0x29>,
  pub volume_id: u32le,
  pub label: [u8; 11],
  pub fs_type: [u8; 8],
  pub code: [u8; 448],
  pub signature: u16lec<0xaa55>,
}

/// A FAT32 boot sector: 65525 clusters or more. The BIOS parameter block is the same as the one
/// of [`Fat16Boot`], but for its 16 bits sizes, which are 0: it is read at its offsets.
#[derive(Pun)]
#[repr(C)]
#[pun(assert((be(0, 1) == 0xeb && be(2, 1) == 0x90) || be(0, 1) == 0xe9))]
// No root directory of a fixed size, a size of 32 bits, a FAT of a size of 32 bits.
#[pun(assert(le(17, 2) == 0 && le(19, 2) == 0 && le(22, 2) == 0 && fat_size32 != 0))]
#[pun(assert({
  let bytes_per_sector = le(11, 2);
  let sectors_per_cluster = be(13, 1);
  bytes_per_sector >= 512
    && sectors_per_cluster >= 1
    && (le(32, 4) - le(14, 2) - be(16, 1) * fat_size32) / sectors_per_cluster >= 65525
}))]
#[pun(assert(root_cluster >= 2))]
pub struct Fat32Boot {
  pub bpb: [u8; 36],
  pub fat_size32: u32le,
  pub ext_flags: u16le,
  pub version: u16lec<0>,
  pub root_cluster: u32le,
  pub fs_info: u16le,
  pub backup_boot: u16le,
  pub reserved: [u8; 12],
  pub drive: u8,
  pub reserved1: u8,
  pub boot_signature: u8c<0x29>,
  pub volume_id: u32le,
  pub label: [u8; 11],
  pub fs_type: [u8; 8],
  pub code: [u8; 420],
  pub signature: u16lec<0xaa55>,
}

/// A FAT boot sector, by its count of clusters.
#[derive(Pun)]
pub enum FatBoot<'a> {
  Fat32(&'a Fat32Boot),
  Fat16(&'a Fat16Boot),
}

// -------------------------------------------------------------------------------------------------
// GPT

/// A disk of GPT partitions, of sectors of `S` bytes: a protective MBR, the header at LBA 1, the
/// partition entries where the header says, of the CRC the header tells.
#[derive(Pun)]
#[repr(transparent)]
// The protective MBR: its first partition is of type 0xee.
#[pun(assert(le(510, 2) == 0xaa55 && be(446 + 4, 1) == 0xee))]
// "EFI PART", revision 1.0, a header of 92 bytes or more, at LBA 1.
#[pun(assert(be(S, 8) == 0x4546_4920_5041_5254 && le(S + 8, 4) == 0x0001_0000))]
#[pun(assert(le(S + 12, 4) >= 92 && le(S + 12, 4) <= S && le(S + 24, 8) == 1))]
// The usable blocks, before the backup header.
#[pun(assert(le(S + 40, 8) <= le(S + 48, 8) + 1 && le(S + 48, 8) < le(S + 32, 8)))]
// Entries of 128 bytes times a power of two.
#[pun(assert({
  let size = le(S + 84, 4);
  size >= 128 && size & (size - 1) == 0
}))]
#[pun(assert({
  let start = le(S + 72, 8) * S;
  crc32(start, start + le(S + 80, 4) * le(S + 84, 4)) == le(S + 88, 4)
}))]
// The CRC of the header, its own field taken as zeros.
#[pun(assert(crc32(S, S + le(S + 12, 4), S + 16, S + 20) == le(S + 16, 4)))]
pub struct GptDisk<const S: usize>(pub [u8]);

/// A partition entry: unused if its type is 0.
#[derive(Pun, Debug, Clone, Copy)]
#[repr(C)]
#[pun(assert(first_lba <= last_lba || (first_lba == 0 && last_lba == 0)))]
pub struct GptEntry {
  pub type_guid: [u8; 16],
  pub unique_guid: [u8; 16],
  pub first_lba: u64le,
  pub last_lba: u64le,
  pub attributes: u64le,
  /// UTF-16LE.
  pub name: [u16le; 36],
}

// -------------------------------------------------------------------------------------------------
// USB

/// A USB device descriptor.
#[derive(Pun, Debug, Clone, Copy)]
#[repr(C)]
pub struct DeviceDescriptor {
  pub length: u8c<18>,
  pub kind: u8c<1>,
  /// USB 1.0 to 3.2, as binary-coded decimal.
  #[pun(valid(0x0100, 0x0110, 0x0200, 0x0201, 0x0210, 0x0300, 0x0310, 0x0320))]
  pub usb: u16le,
  pub class: u8,
  pub subclass: u8,
  pub protocol: u8,
  /// 8, 16, 32 or 64 bytes; 9 is 512 bytes (2^9), for USB 3.
  #[pun(valid(8, 16, 32, 64, 9))]
  pub max_packet_size: u8,
  pub vendor: u16le,
  pub product: u16le,
  pub device: u16le,
  pub manufacturer: u8,
  pub product_string: u8,
  pub serial: u8,
  #[pun(valid(1..))]
  pub configurations: u8,
}

/// A configuration descriptor, and the descriptors that follow it (interfaces, endpoints, class
/// descriptors), which fill its total length.
#[derive(Pun)]
#[repr(C)]
#[pun(size = total_length)]
// Bus powered (bit 7); bits 0 to 4 are 0.
#[pun(assert(attributes & 0x80 != 0 && attributes & 0x1f == 0))]
// The descriptors fill the total length, and `interfaces` of them are interfaces of alternate
// setting 0: a walk whose state is an offset (the low 16 bits) and a count.
#[pun(assert({
  let s = walk(
    9,
    |s| s & 0xffff < total_length,
    |s| {
      let at = s & 0xffff;
      if be(at, 1) < 2 {
        1 / 0
      } else {
        s + be(at, 1) + if be(at + 1, 1) == 4 && be(at + 3, 1) == 0 { 0x1_0000 } else { 0 }
      }
    },
  );
  s & 0xffff == total_length && s >> 16 == interfaces
}))]
pub struct Configuration {
  pub length: u8c<9>,
  pub kind: u8c<2>,
  pub total_length: u16le,
  #[pun(valid(1..))]
  pub interfaces: u8,
  pub value: u8,
  pub string: u8,
  pub attributes: u8,
  /// In units of 2 mA.
  pub max_power: u8,
  pub descriptors: [u8],
}

/// An interface descriptor.
#[derive(Pun, Debug, Clone, Copy)]
#[repr(C)]
pub struct InterfaceDescriptor {
  pub length: u8c<9>,
  pub kind: u8c<4>,
  pub number: u8,
  pub alternate: u8,
  pub endpoints: u8,
  pub class: u8,
  pub subclass: u8,
  pub protocol: u8,
  pub string: u8,
}

/// An endpoint descriptor: a direction and a number of 1 to 15, a transfer type.
#[derive(Pun, Debug, Clone, Copy)]
#[repr(C)]
#[pun(assert(address & 0x70 == 0 && address & 0x0f != 0))]
#[pun(get(input: bool = address & 0x80 != 0, transfer: u8 = attributes & 3))]
pub struct EndpointDescriptor {
  pub length: u8c<7>,
  pub kind: u8c<5>,
  pub address: u8,
  pub attributes: u8,
  pub max_packet_size: u16le,
  pub interval: u8,
}

// -------------------------------------------------------------------------------------------------
// Use

/// The header of an SQLite database of two pages of 4096 bytes, as bytes.
const SQLITE: [u8; 100] = [
  b'S', b'Q', b'L', b'i', b't', b'e', 0x20, b'f', b'o', b'r', b'm', b'a', b't', 0x20, 0x33, 0x00,
  0x10, 0x00, 0x01, 0x01, 0x00, 0x40, 0x20, 0x20, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  0x00, 0x2e, 0x76, 0x89,
];

/// The start of the boot sector of a FAT16 volume of 32 MiB, as bytes: its BIOS parameter
/// block, up to the type of the file system.
const FAT16: [u8; 62] = [
  0xeb, 0x3c, 0x90, b'M', b'S', b'W', b'I', b'N', b'4', b'.', b'1', 0x00, 0x02, 0x04, 0x01, 0x00,
  0x02, 0x00, 0x02, 0x00, 0x00, 0xf8, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x29, 0xcd, 0xab, 0x34, 0x12, 0x4e, 0x4f, 0x20, b'N', b'A',
  b'M', b'E', 0x20, 0x20, 0x20, 0x20, b'F', b'A', b'T', b'1', b'6', 0x20, 0x20, 0x20,
];

/// The start of the boot sector of a FAT32 volume of 512 MiB, as bytes.
const FAT32: [u8; 90] = [
  0xeb, 0x58, 0x90, b'M', b'S', b'W', b'I', b'N', b'4', b'.', b'1', 0x00, 0x02, 0x08, 0x20, 0x00,
  0x02, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x10, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
  0x01, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x29, 0xcd, 0xab, 0x34, 0x12, 0x4e, 0x4f, 0x20, b'N', b'A', b'M', b'E', 0x20, 0x20,
  0x20, 0x20, b'F', b'A', b'T', b'3', b'2', 0x20, 0x20, 0x20,
];

/// The GPT header of a disk of 40 sectors of 512 bytes, as bytes: four partition entries from
/// LBA 2, their CRC, its own CRC.
const GPT_HEADER: [u8; 92] = [
  b'E', b'F', b'I', 0x20, b'P', b'A', b'R', b'T', 0x00, 0x00, 0x01, 0x00, 0x5c, 0x00, 0x00, 0x00,
  0xc4, b'C', b'u', b'y', 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x26, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x04, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0xa9, 0x5f, 0x19, 0x2b,
];

/// The first partition entry of the disk, as bytes: a Linux file system from LBA 34 to 38,
/// "data".
const GPT_ENTRY: [u8; 128] = [
  0xaf, 0x3d, 0xc6, 0x0f, 0x83, 0x84, 0x72, 0x47, 0x8e, 0x79, 0x3d, 0x69, 0xd8, 0x47, 0x7d, 0xe4,
  0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
  0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x00, 0x61, 0x00, 0x74, 0x00, 0x61, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
];

/// A USB device descriptor, as bytes: USB 2.0, a packet size of 64 bytes, vendor `0x1d6b`.
const DEVICE: [u8; 18] =
  [18, 1, 0x00, 0x02, 0, 0, 0, 64, 0x6b, 0x1d, 0x04, 0x01, 0x00, 0x01, 1, 2, 3, 1];

/// A USB configuration, as bytes: one interface of two alternate settings, an endpoint each.
const CONFIGURATION: [u8; 41] = [
  9, 2, 41, 0, 1, 1, 0, 0x80, 50, 9, 4, 0, 0, 1, 0xff, 0, 0, 0, 7, 5, 0x81, 2, 0, 2, 0, 9, 4, 0, 1,
  1, 0xff, 0, 0, 0, 7, 5, 0x81, 3, 8, 0, 1,
];

pub fn main() {
  // ---- SQLite: a header of fixed values, and a file of the pages it tells.
  let mut database = SQLITE.to_vec();
  database.resize(2 * 4096, 0);
  let header: &SqliteHeader = try_pun_ref(&database[..100]).unwrap();
  assert_eq!(
    (header.page_bytes(), header.database_size.get(), header.text_encoding.get()),
    (4096, 2, 1)
  );
  assert_eq!(header.sqlite_version.get(), 3_045_001);
  assert!(try_pun_ref::<_, Sqlite>(&database[..]).is_ok());
  // The magic; a page size that is not a power of two; the maximum payload fraction; an
  // incremental vacuum of 4; a reserved byte.
  for (at, value) in [(0, b's'), (17, 1), (21, 63), (67, 4), (75, 1)] {
    let mut bytes = SQLITE;
    bytes[at] = value;
    assert_eq!(try_pun_ref::<_, SqliteHeader>(&bytes[..]).err(), Some(Error::Validity));
  }
  // Two pages are told, one is there; half a page.
  assert_eq!(try_pun_ref::<_, Sqlite>(&database[..4096]).err(), Some(Error::Validity));
  assert_eq!(try_pun_ref::<_, Sqlite>(&database[..6000]).err(), Some(Error::Validity));
  // A page size of 1 means 65536.
  let mut large = SQLITE;
  large[16..18].copy_from_slice(&[0, 1]);
  assert_eq!(try_pun_ref::<_, SqliteHeader>(&large[..]).unwrap().page_bytes(), 65536);

  // ---- FAT: the kind of a volume, by its count of clusters.
  let mut fat16 = FAT16.to_vec();
  fat16.resize(512, 0);
  fat16[510..].copy_from_slice(&[0x55, 0xaa]);
  let Ok(FatBoot::Fat16(boot)) = FatBoot::from_bytes(&fat16) else { panic!() };
  assert_eq!(
    (boot.root_entries.get(), boot.total32.get(), &boot.fs_type),
    (512, 65536, b"FAT16   ")
  );
  let mut fat32 = FAT32.to_vec();
  fat32.resize(512, 0);
  fat32[510..].copy_from_slice(&[0x55, 0xaa]);
  let Ok(FatBoot::Fat32(boot)) = FatBoot::from_bytes(&fat32) else { panic!() };
  assert_eq!(
    (boot.root_cluster.get(), boot.fat_size32.get(), &boot.fs_type),
    (2, 1024, b"FAT32   ")
  );
  // Too many clusters for FAT16: five times the sectors.
  let mut bytes = fat16.clone();
  bytes[34] = 5;
  assert_eq!(FatBoot::from_bytes(&bytes).err(), Some(Error::Validity));
  // The jump, the size of a sector, the media, the signature, the extended boot signature.
  for (at, value) in [(0, 0x00), (11, 0x01), (21, 0x00), (511, 0xab), (38, 0x28)] {
    let mut bytes = fat16.clone();
    bytes[at] = value;
    assert_eq!(FatBoot::from_bytes(&bytes).err(), Some(Error::Validity));
  }
  // FAT32: a root directory of a fixed size; the root cluster.
  for (at, value) in [(17, 1), (44, 1)] {
    let mut bytes = fat32.clone();
    bytes[at] = value;
    assert_eq!(FatBoot::from_bytes(&bytes).err(), Some(Error::Validity));
  }

  // ---- GPT: a protective MBR, a header, entries and their CRC.
  let mut disk = vec![0u8; 40 * 512];
  disk[446 + 4] = 0xee;
  disk[510..512].copy_from_slice(&[0x55, 0xaa]);
  disk[512..512 + 92].copy_from_slice(&GPT_HEADER);
  disk[1024..1024 + 128].copy_from_slice(&GPT_ENTRY);
  assert!(try_pun_ref::<_, GptDisk<512>>(&disk[..]).is_ok());
  let entry: &GptEntry = try_pun_ref(&disk[1024..1152]).unwrap();
  let name: String = entry.name.iter().map(|c| char::from(c.get() as u8)).take(4).collect();
  assert_eq!((entry.first_lba.get(), entry.last_lba.get(), name.as_str()), (34, 38, "data"));
  // A byte of an entry (their CRC); the signature; entries of 100 bytes; the protective type; the
  // first usable block after the last.
  for (at, value) in [(1024 + 3, 1), (512 + 1, 0), (512 + 84, 100), (450, 0x07), (512 + 40, 40)] {
    let mut bytes = disk.clone();
    bytes[at] = value;
    assert_eq!(try_pun_ref::<_, GptDisk<512>>(&bytes[..]).err(), Some(Error::Validity));
  }
  // The CRC of the header, or a byte that it covers.
  for at in [512 + 16, 512 + 40] {
    let mut bytes = disk.clone();
    bytes[at] ^= 1;
    assert_eq!(try_pun_ref::<_, GptDisk<512>>(&bytes[..]).err(), Some(Error::Validity));
  }
  // The sector size is a parameter: as sectors of 4096 bytes, this is not a GPT disk.
  assert_eq!(try_pun_ref::<_, GptDisk<4096>>(&disk[..]).err(), Some(Error::Validity));
  // An entry that ends before it starts.
  let mut bytes = GPT_ENTRY;
  bytes[40] = 30;
  assert_eq!(try_pun_ref::<_, GptEntry>(&bytes[..]).err(), Some(Error::Validity));

  // ---- USB: descriptors of fixed sizes, and a configuration that they fill.
  let device: &DeviceDescriptor = try_pun_ref(&DEVICE).unwrap();
  assert_eq!(
    (device.usb.get(), device.vendor.get(), device.product.get()),
    (0x0200, 0x1d6b, 0x0104)
  );
  let mut bytes = DEVICE;
  bytes[7] = 65;
  assert_eq!(try_pun_ref::<_, DeviceDescriptor>(&bytes).err(), Some(Error::Validity));
  let (configuration, rest) = from_head::<Configuration>(&CONFIGURATION).unwrap();
  assert_eq!((configuration.descriptors.len(), configuration.max_power, rest.len()), (32, 50, 0));
  let (mut descriptors, mut endpoints) = (&configuration.descriptors[..], vec![]);
  while !descriptors.is_empty() {
    let (interface, rest) = from_head::<InterfaceDescriptor>(descriptors).unwrap();
    let (endpoint, rest) = from_head::<EndpointDescriptor>(rest).unwrap();
    endpoints.push((
      interface.alternate,
      endpoint.input(),
      endpoint.transfer(),
      endpoint.max_packet_size.get(),
    ));
    descriptors = rest;
  }
  assert_eq!(endpoints, [(0, true, 2, 512), (1, true, 3, 8)]);
  // Two interfaces are told, one is there; not bus powered; a descriptor of a length of 1; a
  // total length that is not the one of the descriptors.
  for (at, value) in [(4, 2), (7, 0x40), (9, 1), (2, 40)] {
    let mut bytes = CONFIGURATION;
    bytes[at] = value;
    assert!(from_head::<Configuration>(&bytes).is_err());
  }
  // An endpoint 0, which is not described.
  let mut bytes = CONFIGURATION;
  bytes[20] = 0x80;
  assert_eq!(try_pun_ref::<_, EndpointDescriptor>(&bytes[18..25]).err(), Some(Error::Validity));

  println!("ok");
}