rust-hdf5 0.6.1

Pure Rust HDF5 library with full read/write and SWMR support
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
/// Object Header v2 encode/decode.
///
/// The Object Header is the primary metadata container in HDF5. Every named
/// object (group, dataset, committed datatype) has one. Version 2 headers use
/// the "OHDR" signature and end with a Jenkins checksum.
///
/// Layout of the header prefix (before messages):
/// ```text
/// "OHDR" (4 bytes)
/// Version: 2 (1 byte)
/// Flags (1 byte):
///   bits 0-1: chunk#0 data-size encoding (0=1B, 1=2B, 2=4B, 3=8B)
///   bit 2:    attribute creation order tracked
///   bit 3:    attribute creation order indexed
///   bit 4:    non-default attribute storage phase-change thresholds
///   bit 5:    store access/modify/change/birth timestamps
/// [if bit 5 set: 4x uint32 timestamps (16 bytes)]
/// [if bit 4 set: max_compact(u16) + min_dense(u16) (4 bytes)]
/// chunk0_data_size: 1/2/4/8 bytes depending on bits 0-1
/// <messages>
/// Checksum (4 bytes)
/// ```
///
/// Each message (v2 format):
/// ```text
/// msg_type:       u8
/// msg_data_size:  u16 LE
/// msg_flags:      u8
/// [if obj header flags bit 2: creation_order: u16 LE]
/// msg_data:       [u8; msg_data_size]
/// ```
use crate::format::checksum::checksum_metadata;
use crate::format::creation_order::CreationOrder;
use crate::format::{FormatContext, FormatError, FormatResult, ObjectFormat};

/// The 4-byte object header v2 signature.
pub const OHDR_SIGNATURE: [u8; 4] = *b"OHDR";

/// The 4-byte signature of a version-2 object header continuation chunk.
pub const OCHK_SIGNATURE: [u8; 4] = *b"OCHK";

/// `H5O_NULL_ID` — the message that covers space a chunk holds but does not
/// use.
const MSG_NIL: u8 = 0x00;

/// `H5O_CONT_ID` — the message naming a continuation chunk.
const MSG_CONTINUATION: u8 = 0x10;

/// Object header version 2.
pub const OHDR_VERSION: u8 = 2;

/// Largest payload one object header message can carry.
///
/// The message envelope encodes the payload length in a `u16`, so this is a
/// hard on-disk ceiling, not a policy: libhdf5 refuses the same sizes through
/// `H5O_MESG_MAX_SIZE` (65536) and moves anything that reaches it out of the
/// header — `H5O__attr_create` switches such an attribute to dense storage.
pub const MAX_MESSAGE_SIZE: usize = u16::MAX as usize;

// Flag bit masks
const FLAG_SIZE_MASK: u8 = 0x03;
const FLAG_ATTR_CREATION_ORDER_TRACKED: u8 = 0x04;
const FLAG_ATTR_CREATION_ORDER_INDEXED: u8 = 0x08;
const FLAG_NON_DEFAULT_ATTR_THRESHOLDS: u8 = 0x10;
const FLAG_STORE_TIMESTAMPS: u8 = 0x20;

/// A single message within an object header.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ObjectHeaderMessage {
    /// Message type ID (e.g., 0x01 = Dataspace, 0x03 = Datatype, etc.)
    pub msg_type: u8,
    /// Per-message flags (bit 0 = constant, bit 1 = shared, etc.)
    pub flags: u8,
    /// Creation index, written only when the header tracks attribute creation
    /// order (flags bit 2). Only the attribute message class has one in
    /// libhdf5 — `H5O_msg_class_t::get_crt_index` is null for every other
    /// type, leaving the field zero (`H5O_msg_append_real`).
    pub creation_index: u16,
    /// Raw message payload.
    pub data: Vec<u8>,
}

/// The four times a version-2 object header stores, in the order
/// `H5O__cache_serialize` writes them: seconds since the epoch, as `H5_now`
/// produces them.
///
/// Their presence *is* the `H5O_HDR_STORE_TIMES` flag — see
/// [`ObjectHeader::times`] — so an object created with
/// `H5Pset_obj_track_times(true)` cannot be encoded with the flag set and no
/// times behind it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ObjectTimes {
    /// Access time (`oh->atime`).
    pub access: u32,
    /// Modification time (`oh->mtime`).
    pub modification: u32,
    /// Change time (`oh->ctime`).
    pub change: u32,
    /// Birth time (`oh->btime`).
    pub birth: u32,
}

impl ObjectTimes {
    /// All four set to `now` — what `H5O_create_ohdr` does for an object
    /// created with timestamps enabled.
    pub fn created_at(now: u32) -> Self {
        Self {
            access: now,
            modification: now,
            change: now,
            birth: now,
        }
    }

    /// These times after a real modification of the object.
    ///
    /// `H5O_touch_oh` moves access and change time to `now` for a version-2
    /// header and leaves modification and birth time as they were — the
    /// modification time is what its own `XXX` comment says is not updated
    /// yet. Following it means a rewrite reports the same times libhdf5 would.
    pub fn touched(self, now: u32) -> Self {
        Self {
            access: now,
            change: now,
            ..self
        }
    }
}

/// How an object header's messages divide between chunk 0 and one
/// continuation chunk, produced by [`ObjectHeader::plan_chunks`] and consumed
/// by [`ObjectHeader::encode_chunked`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChunkPlan {
    /// Messages before this index go in chunk 0, the rest in the continuation
    /// chunk.
    split: usize,
    /// Bytes chunk 0 occupies, prefix and checksum included.
    pub chunk0_size: usize,
    /// Bytes the continuation chunk occupies, signature and checksum
    /// included; zero when every message fits chunk 0.
    pub continuation_size: usize,
    /// The flags byte chunk 0 is encoded under: the header's own with the
    /// chunk-0 size field width that fits the area — the narrowest that
    /// expresses it, or, in a plan into an existing block
    /// ([`ObjectHeader::plan_chunks_in`]), the one that makes chunk 0 the
    /// block's length.
    flags: u8,
}

/// Object Header v2.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ObjectHeader {
    /// Header flags byte: the optional prefix fields (attribute thresholds)
    /// and the attribute creation-order policy.
    ///
    /// Two groups of bits are *not* held here, because each describes the
    /// image rather than the header. Bit 5 (`H5O_HDR_STORE_TIMES`) is derived
    /// from [`times`](Self::times) at encode and stripped at decode, so the
    /// flag and the four values it announces cannot disagree. Bits 0-1, the
    /// chunk-0 size field width, are chosen at encode for the size chunk 0
    /// turns out to have — the narrowest field that expresses it, as
    /// `H5O_apply_ohdr` picks it (H5Oint.c:459-464) — and stripped at decode
    /// for the same reason. Setting either by hand here does nothing.
    pub flags: u8,
    /// The stored times, when this object tracks them.
    pub times: Option<ObjectTimes>,
    /// The ordered list of header messages.
    pub messages: Vec<ObjectHeaderMessage>,
}

impl ObjectHeader {
    /// Create a new, empty object header with default flags: no timestamps,
    /// no attribute creation order, no non-default thresholds.
    pub fn new() -> Self {
        Self {
            flags: 0,
            times: None,
            messages: Vec::new(),
        }
    }

    /// The times this header records, wherever its version keeps them.
    ///
    /// One answer for both versions, which store a different number of times
    /// in different places: version 2 keeps all four in the prefix under
    /// `H5O_HDR_STORE_TIMES`, and version 1 keeps at most one, in an
    /// `H5O_MTIME_NEW` message. `None` means the object was created with
    /// `H5Pset_obj_track_times(false)` — or is a version-1 group or committed
    /// datatype, whose header has nowhere to record a time even while the
    /// property is on, since only `H5D__update_oh_info` calls `H5O_touch_oh`
    /// with the `force` that creates the message (H5Dint.c:1022-1026).
    ///
    /// The one time a version-1 header stores fills all four fields. Only
    /// [`ObjectTimes::change`] is written back for that version — it is the
    /// field `H5O_touch_oh` moves to now on both versions (H5Oint.c:1290-1345)
    /// — so the other three are there to keep one struct across both versions
    /// rather than to claim the file said anything about them.
    pub fn recorded_times(&self) -> Option<ObjectTimes> {
        if let Some(times) = self.times {
            return Some(times);
        }
        self.messages
            .iter()
            .find(|m| m.msg_type == crate::format::messages::MSG_MOD_TIME)
            .and_then(|m| crate::format::messages::mod_time::ModificationTime::decode(&m.data).ok())
            .map(|t| ObjectTimes::created_at(t.0))
    }

    /// Append a message to the object header.
    pub fn add_message(&mut self, msg_type: u8, flags: u8, data: Vec<u8>) {
        self.add_message_indexed(msg_type, flags, data, 0);
    }

    /// Append a message carrying a creation index.
    ///
    /// The index reaches the file only when the header's flags bit 2 says the
    /// creation order is tracked; libhdf5 does not encode the field otherwise
    /// (`H5O_SIZEOF_MSGHDR_OH`).
    pub fn add_message_indexed(
        &mut self,
        msg_type: u8,
        flags: u8,
        data: Vec<u8>,
        creation_index: u16,
    ) {
        self.messages.push(ObjectHeaderMessage {
            msg_type,
            flags,
            creation_index,
            data,
        });
    }

    /// Declare `order` as this object's attribute creation-order policy.
    ///
    /// `H5Pget_attr_creation_order` reads these two bits back out of the
    /// header, not out of the Attribute Info message (`H5Pocpl.c`), so they
    /// are what makes an object report its attributes as creation-ordered.
    /// Setting `TRACKED` also widens every message envelope by the two-byte
    /// creation index.
    pub fn set_attribute_creation_order(&mut self, order: CreationOrder) {
        self.flags &= !(FLAG_ATTR_CREATION_ORDER_TRACKED | FLAG_ATTR_CREATION_ORDER_INDEXED);
        if order.is_tracked() {
            self.flags |= FLAG_ATTR_CREATION_ORDER_TRACKED;
        }
        if order.is_indexed() {
            self.flags |= FLAG_ATTR_CREATION_ORDER_INDEXED;
        }
    }

    /// This object's attribute creation-order policy, as its flag bits
    /// declare it — the reverse of
    /// [`set_attribute_creation_order`](Self::set_attribute_creation_order),
    /// and what a reopen must consult so a rewrite re-declares what the file
    /// already says.
    pub fn attribute_creation_order(&self) -> CreationOrder {
        CreationOrder::from_flags(
            self.flags & FLAG_ATTR_CREATION_ORDER_TRACKED != 0,
            self.flags & FLAG_ATTR_CREATION_ORDER_INDEXED != 0,
        )
    }

    /// The flags byte as it reaches the file: everything [`flags`](Self::flags)
    /// holds, with `H5O_HDR_STORE_TIMES` taken from
    /// [`times`](Self::times) — the one place the two are joined, so a header
    /// can neither claim times it does not have nor carry times it does not
    /// declare.
    fn encoded_flags(&self, flags: u8) -> u8 {
        let base = flags & !FLAG_STORE_TIMESTAMPS;
        match self.times {
            Some(_) => base | FLAG_STORE_TIMESTAMPS,
            None => base,
        }
    }

    /// The flags chunk 0 is encoded under when its message area is `area`
    /// bytes: this header's, with bits 0-1 naming the narrowest size field
    /// that expresses the area — `H5O_apply_ohdr`'s choice for a new header
    /// (H5Oint.c:459-464), and what `H5O__alloc_extend_chunk` widens to as
    /// chunk 0 grows (H5Oalloc.c:538-557).
    fn flags_for_area(&self, area: usize) -> u8 {
        let bits = match area as u64 {
            0..=0xFF => 0,
            0x100..=0xFFFF => 1,
            0x1_0000..=0xFFFF_FFFF => 2,
            _ => 3,
        };
        (self.flags & !FLAG_SIZE_MASK) | bits
    }

    /// Whether attribute creation order tracking is enabled (flags bit 2).
    pub fn has_creation_order(&self) -> bool {
        self.flags & FLAG_ATTR_CREATION_ORDER_TRACKED != 0
    }

    /// Bytes a message envelope takes: type, size and flags, plus the creation
    /// index when this header tracks one (`H5O_SIZEOF_MSGHDR_OH`).
    pub fn message_envelope_size(&self) -> usize {
        if self.has_creation_order() {
            1 + 2 + 1 + 2 // type + size + flags + creation_order
        } else {
            1 + 2 + 1 // type + size + flags
        }
    }

    /// Bytes `messages` occupy in a chunk, envelopes included.
    fn messages_size(&self, messages: &[ObjectHeaderMessage]) -> usize {
        messages
            .iter()
            .map(|m| self.message_envelope_size() + m.data.len())
            .sum()
    }

    /// Compute the byte size of the messages region (chunk0 data).
    fn messages_data_size(&self) -> usize {
        self.messages_size(&self.messages)
    }

    /// Bytes chunk 0 spends before its message area when encoded under
    /// `flags`: signature, version, flags, the optional prefix fields, and
    /// the chunk-0 size field.
    fn prefix_size_under(&self, flags: u8) -> usize {
        let mut size = 4 + 1 + 1; // OHDR + version + flags
        if self.times.is_some() {
            size += 16; // 4 x u32
        }
        if flags & FLAG_NON_DEFAULT_ATTR_THRESHOLDS != 0 {
            size += 4; // max_compact(u16) + min_dense(u16)
        }
        size + Self::size_field_width(flags)
    }

    /// The chunk-0 size field width `flags` bits 0-1 name.
    fn size_field_width(flags: u8) -> usize {
        match flags & FLAG_SIZE_MASK {
            0 => 1,
            1 => 2,
            2 => 4,
            3 => 8,
            _ => unreachable!(),
        }
    }

    /// Reject a message whose payload the `u16` size field cannot express.
    ///
    /// Writing such a message would record its length modulo 65536: the reader
    /// would then take the payload's own tail for the next message envelope and
    /// every message after it would decode as garbage. Nothing downstream can
    /// detect that — the checksum is computed over the truncated image and
    /// matches — so the check has to happen before any bytes are produced.
    fn check_message_sizes(messages: &[ObjectHeaderMessage]) -> FormatResult<()> {
        for msg in messages {
            if msg.data.len() > MAX_MESSAGE_SIZE {
                return Err(FormatError::InvalidData(format!(
                    "object header message type 0x{:02X} is {} bytes, over the \
                     {MAX_MESSAGE_SIZE}-byte limit the message size field can express",
                    msg.msg_type,
                    msg.data.len()
                )));
            }
        }
        Ok(())
    }

    /// Append `messages` in wire form, then pad to `data_size` bytes.
    ///
    /// Space left over is filled the way `H5O__chunk_serialize` leaves a
    /// partly used chunk: a NIL message covering the rest when its envelope
    /// fits, and otherwise a "gap" of zero bytes too short to hold any message
    /// header at all (`H5O_SIZEOF_MSGHDR_OH`, H5Ocache.c).
    fn write_messages(
        &self,
        buf: &mut Vec<u8>,
        messages: &[ObjectHeaderMessage],
        data_size: usize,
    ) {
        let envelope = self.message_envelope_size();
        let mut write = |msg_type: u8, flags: u8, creation_index: u16, data: &[u8]| {
            buf.push(msg_type);
            // Checked against MAX_MESSAGE_SIZE by `check_message_sizes`.
            buf.extend_from_slice(&(data.len() as u16).to_le_bytes());
            buf.push(flags);
            if self.has_creation_order() {
                buf.extend_from_slice(&creation_index.to_le_bytes());
            }
            buf.extend_from_slice(data);
        };
        for msg in messages {
            write(msg.msg_type, msg.flags, msg.creation_index, &msg.data);
        }
        let spare = data_size - self.messages_size(messages);
        if spare >= envelope {
            write(MSG_NIL, 0x00, 0, &vec![0u8; spare - envelope]);
        } else {
            buf.extend(std::iter::repeat_n(0u8, spare));
        }
    }

    /// Encode the object header to a byte vector, including "OHDR" signature
    /// and trailing checksum, with every message in chunk 0.
    ///
    /// Fails when any message payload exceeds [`MAX_MESSAGE_SIZE`] — see
    /// `check_message_sizes`.
    pub fn encode(&self) -> FormatResult<Vec<u8>> {
        let exact = self.messages_data_size();
        self.encode_chunk0(&self.messages, exact, self.flags_for_area(exact))
    }

    /// Chunk 0 holding `messages`, with a message area of exactly `data_size`
    /// bytes, encoded under `flags` — the sole producer of a version-2
    /// chunk-0 image.
    fn encode_chunk0(
        &self,
        messages: &[ObjectHeaderMessage],
        data_size: usize,
        flags: u8,
    ) -> FormatResult<Vec<u8>> {
        Self::check_message_sizes(messages)?;
        debug_assert!(data_size >= self.messages_size(messages));
        let total = self.prefix_size_under(flags) + data_size + 4; // + checksum
        let mut buf = Vec::with_capacity(total);

        buf.extend_from_slice(&OHDR_SIGNATURE);
        buf.push(OHDR_VERSION);
        buf.push(self.encoded_flags(flags));

        // Optional timestamps (bit 5), in `H5O__cache_serialize` order.
        if let Some(t) = self.times {
            for field in [t.access, t.modification, t.change, t.birth] {
                buf.extend_from_slice(&field.to_le_bytes());
            }
        }

        // Optional attr storage thresholds (bit 4) -- write defaults if enabled
        if flags & FLAG_NON_DEFAULT_ATTR_THRESHOLDS != 0 {
            // max_compact = 8, min_dense = 6 (HDF5 defaults)
            buf.extend_from_slice(&8u16.to_le_bytes());
            buf.extend_from_slice(&6u16.to_le_bytes());
        }

        let csb = Self::size_field_width(flags);
        buf.extend_from_slice(&(data_size as u64).to_le_bytes()[..csb]);

        self.write_messages(&mut buf, messages, data_size);

        // Checksum over everything before the checksum
        let cksum = checksum_metadata(&buf);
        buf.extend_from_slice(&cksum.to_le_bytes());

        debug_assert_eq!(buf.len(), total);
        Ok(buf)
    }

    /// A continuation chunk holding `messages`: the `"OCHK"` signature, the
    /// messages, and the Jenkins checksum over both, exactly as
    /// `H5O__chunk_serialize` writes one. Sized to fit, so it needs no
    /// padding.
    fn encode_continuation(&self, messages: &[ObjectHeaderMessage]) -> FormatResult<Vec<u8>> {
        Self::check_message_sizes(messages)?;
        let data_size = self.messages_size(messages);
        let mut buf = Vec::with_capacity(OCHK_SIGNATURE.len() + data_size + 4);
        buf.extend_from_slice(&OCHK_SIGNATURE);
        self.write_messages(&mut buf, messages, data_size);
        let cksum = checksum_metadata(&buf);
        buf.extend_from_slice(&cksum.to_le_bytes());
        Ok(buf)
    }

    /// Bytes `msg` occupies in a chunk of version `format`, envelope included.
    ///
    /// Version 1 spends eight bytes on the envelope and rounds the body up to
    /// eight (`H5O_ALIGN_OLD`); version 2 spends exactly the envelope.
    fn message_size_for(&self, format: ObjectFormat, msg: &ObjectHeaderMessage) -> usize {
        match format {
            ObjectFormat::Legacy => V1_MSG_HEADER_SIZE + align_old(msg.data.len()),
            ObjectFormat::Modern => self.message_envelope_size() + msg.data.len(),
        }
    }

    /// Bytes `messages` occupy in a chunk of version `format`.
    fn messages_size_for(&self, format: ObjectFormat, messages: &[ObjectHeaderMessage]) -> usize {
        messages
            .iter()
            .map(|m| self.message_size_for(format, m))
            .sum()
    }

    /// Bytes chunk 0 spends outside its message area in version `format`
    /// under `flags`: the prefix, and the checksum version 2 appends.
    fn chunk0_overhead(&self, format: ObjectFormat, flags: u8) -> usize {
        match format {
            ObjectFormat::Legacy => V1_PREFIX_SIZE,
            ObjectFormat::Modern => self.prefix_size_under(flags) + 4,
        }
    }

    /// Bytes a continuation chunk spends outside its message area: nothing in
    /// version 1, the `OCHK` signature and a checksum in version 2.
    fn continuation_overhead(format: ObjectFormat) -> usize {
        match format {
            ObjectFormat::Legacy => 0,
            ObjectFormat::Modern => OCHK_SIGNATURE.len() + 4,
        }
    }

    /// The message naming a continuation chunk of `size` bytes at `addr`
    /// (`H5O_CONT_ID`: the block's address, then its length).
    fn continuation_message(ctx: &FormatContext, addr: u64, size: usize) -> ObjectHeaderMessage {
        let sa = ctx.sizeof_addr as usize;
        let ss = ctx.sizeof_size as usize;
        let mut body = Vec::with_capacity(sa + ss);
        body.extend_from_slice(&addr.to_le_bytes()[..sa]);
        body.extend_from_slice(&(size as u64).to_le_bytes()[..ss]);
        ObjectHeaderMessage {
            msg_type: MSG_CONTINUATION,
            flags: 0x00,
            creation_index: 0,
            data: body,
        }
    }

    /// How this header divides between chunk 0 and its continuation chunk
    /// when chunk 0's message area holds at most `capacity` bytes.
    ///
    /// The whole point of a plan is that both sizes are known before either
    /// chunk has an address: the caller allocates the continuation from
    /// [`continuation_size`](ChunkPlan::continuation_size) and hands the
    /// address back to [`encode_chunked`](Self::encode_chunked), which is the
    /// only way chunk 0 can name a block that does not exist yet.
    ///
    /// Messages fill chunk 0 in order and the rest go to the continuation, so
    /// a message never moves ahead of one that was written before it.
    pub fn plan_chunks(
        &self,
        format: ObjectFormat,
        capacity: usize,
        ctx: &FormatContext,
    ) -> FormatResult<ChunkPlan> {
        self.plan_under(format, capacity, ctx, None)
    }

    /// [`plan_chunks`](Self::plan_chunks) with chunk 0 encoded under `flags`
    /// when given, and otherwise under the narrowest size field for the area
    /// the plan gives chunk 0.
    fn plan_under(
        &self,
        format: ObjectFormat,
        capacity: usize,
        ctx: &FormatContext,
        flags: Option<u8>,
    ) -> FormatResult<ChunkPlan> {
        let exact = self.messages_size_for(format, &self.messages);
        if exact <= capacity {
            let flags = flags.unwrap_or_else(|| self.flags_for_area(exact));
            return Ok(ChunkPlan {
                split: self.messages.len(),
                chunk0_size: self.chunk0_overhead(format, flags) + exact,
                continuation_size: 0,
                flags,
            });
        }
        let flags = flags.unwrap_or_else(|| self.flags_for_area(capacity));
        // Chunk 0 has to keep room for the message naming the continuation,
        // whose body is the block's address and length (`H5O_CONT_ID`).
        let continuation_message =
            self.message_size_for(format, &Self::continuation_message(ctx, 0, 0));
        if capacity < continuation_message {
            return Err(FormatError::InvalidData(format!(
                "an object header chunk-0 capacity of {capacity} bytes cannot hold the \
                 {continuation_message}-byte message naming its continuation chunk"
            )));
        }
        let mut used = continuation_message;
        let mut split = 0;
        for msg in &self.messages {
            let size = self.message_size_for(format, msg);
            if used + size > capacity {
                break;
            }
            used += size;
            split += 1;
        }
        let spilled = self.messages_size_for(format, &self.messages[split..]);
        Ok(ChunkPlan {
            split,
            chunk0_size: self.chunk0_overhead(format, flags) + capacity,
            continuation_size: Self::continuation_overhead(format) + spilled,
            flags,
        })
    }

    /// How this header divides when chunk 0 is written over a `block`-byte
    /// block — the one an existing header occupies, which a rewrite keeps so
    /// that every reference naming the header stays good.
    ///
    /// Messages that fit leave the rest of the block padded, as
    /// `H5O__chunk_serialize` leaves a chunk whose messages shrank; past it,
    /// the plan is [`plan_chunks`](Self::plan_chunks)'s over the block's
    /// message area. A version-2 chunk 0 is sized under the narrowest chunk-0
    /// size field that can express its area, the one that leaves the most of
    /// the block to messages, so a header libhdf5 sized exactly for its
    /// messages takes them back without spilling. Refused for a block the
    /// chunk cannot describe: one too short
    /// for the prefix, or, in version 1, one whose message area is not a
    /// multiple of eight — version 1 has no gap, so every byte of the area
    /// has to belong to a message.
    pub fn plan_chunks_in(
        &self,
        format: ObjectFormat,
        block: usize,
        ctx: &FormatContext,
    ) -> FormatResult<ChunkPlan> {
        let too_short = || {
            FormatError::InvalidData(format!(
                "a {block}-byte block cannot hold this object header's chunk 0 prefix"
            ))
        };
        let (area, flags) = match format {
            ObjectFormat::Legacy => {
                let area = block.checked_sub(V1_PREFIX_SIZE).ok_or_else(too_short)?;
                if area % 8 != 0 {
                    return Err(FormatError::InvalidData(format!(
                        "a version-1 object header cannot hold a {area}-byte message area: \
                         version 1 aligns every message to eight bytes"
                    )));
                }
                (area, self.flags)
            }
            ObjectFormat::Modern => {
                let mut fit = None;
                for bits in 0..=3u8 {
                    let flags = (self.flags & !FLAG_SIZE_MASK) | bits;
                    let Some(area) = block.checked_sub(self.chunk0_overhead(format, flags)) else {
                        break;
                    };
                    if area as u64 <= u64::MAX >> (64 - 8 * Self::size_field_width(flags)) {
                        fit = Some((area, flags));
                        break;
                    }
                }
                fit.ok_or_else(too_short)?
            }
        };
        let mut plan = self.plan_under(format, area, ctx, Some(flags))?;
        if plan.continuation_size == 0 {
            plan.chunk0_size = block;
        }
        Ok(plan)
    }

    /// Encode this header as `plan` divides it, in version `format`, with the
    /// continuation chunk at `continuation_addr`.
    ///
    /// Returns chunk 0 and, when the plan spills, the continuation chunk's
    /// image. `continuation_addr` is ignored for a plan that does not spill,
    /// and `nlink` reaches the file only in the version-1 prefix (see
    /// [`encode_for`](Self::encode_for)).
    pub fn encode_chunked(
        &self,
        plan: &ChunkPlan,
        format: ObjectFormat,
        ctx: &FormatContext,
        continuation_addr: u64,
        nlink: u32,
    ) -> FormatResult<(Vec<u8>, Option<Vec<u8>>)> {
        let area = plan.chunk0_size - self.chunk0_overhead(format, plan.flags);
        if plan.continuation_size == 0 {
            let chunk0 = match format {
                ObjectFormat::Legacy => self.encode_v1_chunk0(&self.messages, area, nlink, 0)?,
                ObjectFormat::Modern => self.encode_chunk0(&self.messages, area, plan.flags)?,
            };
            return Ok((chunk0, None));
        }
        let mut chunk0 = self.messages[..plan.split].to_vec();
        chunk0.push(Self::continuation_message(
            ctx,
            continuation_addr,
            plan.continuation_size,
        ));
        let spilled = &self.messages[plan.split..];
        let (chunk0, continuation) = match format {
            ObjectFormat::Legacy => (
                self.encode_v1_chunk0(&chunk0, area, nlink, spilled.len())?,
                self.encode_v1_continuation(spilled)?,
            ),
            ObjectFormat::Modern => (
                self.encode_chunk0(&chunk0, area, plan.flags)?,
                self.encode_continuation(spilled)?,
            ),
        };
        debug_assert_eq!(continuation.len(), plan.continuation_size);
        Ok((chunk0, Some(continuation)))
    }

    /// Decode an object header from a byte buffer. Returns the parsed header
    /// and the number of bytes consumed from the buffer.
    pub fn decode(buf: &[u8]) -> FormatResult<(Self, usize)> {
        // Minimum: OHDR(4) + version(1) + flags(1) + chunk0_size(1) + checksum(4) = 11
        if buf.len() < 11 {
            return Err(FormatError::BufferTooShort {
                needed: 11,
                available: buf.len(),
            });
        }

        // Signature
        if buf[0..4] != OHDR_SIGNATURE {
            return Err(FormatError::InvalidSignature);
        }

        // Version
        let version = buf[4];
        if version != OHDR_VERSION {
            return Err(FormatError::InvalidVersion(version));
        }

        // Bit 5 is stripped here and carried by `times` instead, and bits 0-1
        // are stripped and carried by the image's own width, so neither can
        // disagree with what it describes — see [`ObjectHeader::flags`].
        let flags = buf[5] & !(FLAG_STORE_TIMESTAMPS | FLAG_SIZE_MASK);
        let mut pos: usize = 6;

        // Optional timestamps (bit 5)
        let times = if buf[5] & FLAG_STORE_TIMESTAMPS != 0 {
            if buf.len() < pos + 16 {
                return Err(FormatError::BufferTooShort {
                    needed: pos + 16,
                    available: buf.len(),
                });
            }
            let read = |off: usize| {
                u32::from_le_bytes([buf[off], buf[off + 1], buf[off + 2], buf[off + 3]])
            };
            let t = ObjectTimes {
                access: read(pos),
                modification: read(pos + 4),
                change: read(pos + 8),
                birth: read(pos + 12),
            };
            pos += 16;
            Some(t)
        } else {
            None
        };

        // Optional attr storage thresholds (bit 4)
        if flags & FLAG_NON_DEFAULT_ATTR_THRESHOLDS != 0 {
            if buf.len() < pos + 4 {
                return Err(FormatError::BufferTooShort {
                    needed: pos + 4,
                    available: buf.len(),
                });
            }
            // Skip thresholds for now
            pos += 4;
        }

        // Chunk0 data size
        let chunk0_size_bytes = Self::size_field_width(buf[5]);

        if buf.len() < pos + chunk0_size_bytes {
            return Err(FormatError::BufferTooShort {
                needed: pos + chunk0_size_bytes,
                available: buf.len(),
            });
        }

        let chunk0_data_size =
            crate::format::bytes::read_le_uint(&buf[pos..], chunk0_size_bytes) as usize;
        pos += chunk0_size_bytes;

        // We need chunk0_data_size bytes of messages + 4 bytes of checksum.
        // chunk0_data_size is a file field up to 8 bytes wide; guard the
        // addition so a crafted absurd value yields a clean error instead of
        // an overflow panic (debug) or wrap (release).
        let total_consumed = pos
            .checked_add(chunk0_data_size)
            .and_then(|x| x.checked_add(4))
            .ok_or_else(|| {
                FormatError::InvalidData("object header chunk-0 size overflows usize".into())
            })?;
        if buf.len() < total_consumed {
            return Err(FormatError::BufferTooShort {
                needed: total_consumed,
                available: buf.len(),
            });
        }

        // Verify checksum: covers everything from start up to (but not
        // including) the 4-byte checksum.
        let data_end = total_consumed - 4;
        let stored_cksum = u32::from_le_bytes([
            buf[data_end],
            buf[data_end + 1],
            buf[data_end + 2],
            buf[data_end + 3],
        ]);
        let computed_cksum = checksum_metadata(&buf[..data_end]);
        if stored_cksum != computed_cksum {
            return Err(FormatError::ChecksumMismatch {
                expected: stored_cksum,
                computed: computed_cksum,
            });
        }

        // Parse messages
        let has_creation_order = flags & FLAG_ATTR_CREATION_ORDER_TRACKED != 0;
        let messages_end = pos + chunk0_data_size;
        let mut messages = Vec::new();

        while pos < messages_end {
            // Each message: type(1) + size(2) + flags(1) [+ creation_order(2)]
            let msg_header_size = if has_creation_order { 6 } else { 4 };
            if pos + msg_header_size > messages_end {
                // libhdf5 (H5O__chunk_deserialize) permits a gap smaller than
                // one message header at the end of a v2 chunk; treat the
                // remaining bytes as such a gap rather than an error.
                break;
            }

            let msg_type = buf[pos];
            let msg_data_size = u16::from_le_bytes([buf[pos + 1], buf[pos + 2]]) as usize;
            let msg_flags = buf[pos + 3];
            pos += 4;

            let creation_index = if has_creation_order {
                let v = u16::from_le_bytes([buf[pos], buf[pos + 1]]);
                pos += 2;
                v
            } else {
                0
            };

            if pos + msg_data_size > messages_end {
                return Err(FormatError::InvalidData(format!(
                    "message data ({} bytes) extends past chunk0 boundary",
                    msg_data_size
                )));
            }

            let data = buf[pos..pos + msg_data_size].to_vec();
            pos += msg_data_size;

            messages.push(ObjectHeaderMessage {
                msg_type,
                flags: msg_flags,
                creation_index,
                data,
            });
        }

        Ok((
            ObjectHeader {
                flags,
                times,
                messages,
            },
            total_consumed,
        ))
    }
}

impl Default for ObjectHeader {
    fn default() -> Self {
        Self::new()
    }
}

// =========================================================================
// Object Header v1 — for reading and writing legacy HDF5 files
// =========================================================================

/// `H5O_ALIGN_OLD` (H5Opkg.h:57): version 1 rounds every message body, and the
/// header prefix, up to a multiple of 8.
fn align_old(n: usize) -> usize {
    (n + 7) & !7
}

/// `H5O_SIZEOF_HDR` for version 1 (H5Opkg.h:85): `H5O_ALIGN_OLD(1 + 1 + 2 + 4
/// + 4)` — the four trailing bytes are the alignment pad, not a field.
const V1_PREFIX_SIZE: usize = 16;

/// `H5O_SIZEOF_MSGHDR_VERS` for version 1 (H5Opkg.h:112):
/// `H5O_ALIGN_OLD(2 + 2 + 1 + 3)`.
const V1_MSG_HEADER_SIZE: usize = 8;

impl ObjectHeader {
    /// Why this header cannot be written in version 1, when it cannot.
    ///
    /// A header carrying attribute-creation-order flags is refused: those bits
    /// live in the version-2 flags byte, which version 1 does not have, so
    /// encoding such a header would silently drop the policy the caller set.
    ///
    /// A header carrying [`times`](Self::times) is refused for the same
    /// reason. The four times and the `H5O_HDR_STORE_TIMES` bit that
    /// announces them are version-2 prefix fields; a version-1 header records
    /// at most a modification time, in an `H5O_MTIME_NEW` message among the
    /// messages. Refusing keeps the version gate at the one encoder that
    /// knows which prefix it is writing, instead of letting a v2-shaped header
    /// reach it and come back out with its times gone.
    fn check_v1_encodable(&self) -> FormatResult<()> {
        if self.flags & (FLAG_ATTR_CREATION_ORDER_TRACKED | FLAG_ATTR_CREATION_ORDER_INDEXED) != 0 {
            return Err(FormatError::InvalidData(
                "a version-1 object header cannot record attribute creation order: \
                 the tracking flags exist only in the version-2 header prefix"
                    .into(),
            ));
        }
        if self.times.is_some() {
            return Err(FormatError::InvalidData(
                "a version-1 object header cannot store access/modification/change/birth \
                 times: they are version-2 prefix fields, and version 1 carries only a \
                 modification time, as an H5O_MTIME_NEW message"
                    .into(),
            ));
        }
        Ok(())
    }

    /// Reject a message whose body, once aligned to eight, the version-1 size
    /// field cannot express — the version-1 counterpart of
    /// `check_message_sizes`, which the *padded* length is what matters to.
    fn check_v1_message_sizes(messages: &[ObjectHeaderMessage]) -> FormatResult<()> {
        for msg in messages {
            let padded = align_old(msg.data.len());
            if padded > MAX_MESSAGE_SIZE {
                return Err(FormatError::InvalidData(format!(
                    "object header message type 0x{:02X} is {} bytes, {padded} once \
                     aligned to 8, over the {MAX_MESSAGE_SIZE}-byte limit the message \
                     size field can express",
                    msg.msg_type,
                    msg.data.len()
                )));
            }
        }
        Ok(())
    }

    /// Append `messages` in version-1 wire form: a two-byte type, the
    /// *padded* body length in the size field (`H5O_msg_flush` writes
    /// `mesg->raw_size`, which `H5O__alloc` already aligned), the flags,
    /// three reserved bytes where version 2 puts the creation index, and the
    /// body padded out to eight bytes.
    fn write_messages_v1(buf: &mut Vec<u8>, messages: &[ObjectHeaderMessage]) {
        for msg in messages {
            let padded = align_old(msg.data.len());
            buf.extend_from_slice(&u16::from(msg.msg_type).to_le_bytes());
            buf.extend_from_slice(&(padded as u16).to_le_bytes());
            buf.push(msg.flags);
            buf.extend_from_slice(&[0u8; 3]); // reserved
            buf.extend_from_slice(&msg.data);
            buf.resize(buf.len() + (padded - msg.data.len()), 0);
        }
    }

    /// Chunk 0 of a version-1 header holding `messages` in a message area of
    /// exactly `data_size` bytes, with `spilled` more messages in its
    /// continuation chunk — the sole producer of a version-1 chunk-0 image.
    ///
    /// Space left in the area is one NIL message, the only padding version 1
    /// has: with no signature and no checksum, the prefix is the version, the
    /// reference count, and the two counts libhdf5 checks the chunks against —
    /// the area's size, and the number of messages in the *whole* header
    /// (`H5O_protect` compares it with what every chunk yielded, H5Oint.c:1094),
    /// the NIL padding and the continuation message included.
    fn encode_v1_chunk0(
        &self,
        messages: &[ObjectHeaderMessage],
        data_size: usize,
        nlink: u32,
        spilled: usize,
    ) -> FormatResult<Vec<u8>> {
        self.check_v1_encodable()?;
        Self::check_v1_message_sizes(messages)?;
        let used = self.messages_size_for(ObjectFormat::Legacy, messages);
        debug_assert!(data_size >= used);
        let spare = data_size - used;
        // Every version-1 size is a multiple of eight, so spare space is
        // either nothing or room for a NIL message's envelope.
        debug_assert_eq!(spare % 8, 0);
        let padded = spare >= V1_MSG_HEADER_SIZE;
        let Ok(chunk0_size) = u32::try_from(data_size) else {
            return Err(FormatError::InvalidData(format!(
                "version-1 object header chunk 0 is {data_size} bytes, over the 4-byte \
                 size field's range"
            )));
        };
        let total_messages = messages.len() + usize::from(padded) + spilled;
        let Ok(nmesgs) = u16::try_from(total_messages) else {
            return Err(FormatError::InvalidData(format!(
                "version-1 object header holds {total_messages} messages, over the 2-byte \
                 count field's range"
            )));
        };

        let total = V1_PREFIX_SIZE + data_size;
        let mut buf = Vec::with_capacity(total);
        buf.push(1); // version
        buf.push(0); // reserved
        buf.extend_from_slice(&nmesgs.to_le_bytes());
        buf.extend_from_slice(&nlink.to_le_bytes());
        buf.extend_from_slice(&chunk0_size.to_le_bytes());
        buf.extend_from_slice(&[0u8; 4]); // pad to H5O_ALIGN_OLD(12)

        Self::write_messages_v1(&mut buf, messages);
        if padded {
            buf.extend_from_slice(&u16::from(MSG_NIL).to_le_bytes());
            buf.extend_from_slice(&((spare - V1_MSG_HEADER_SIZE) as u16).to_le_bytes());
            buf.push(0);
            buf.extend_from_slice(&[0u8; 3]);
            buf.resize(total, 0);
        }

        debug_assert_eq!(buf.len(), total);
        Ok(buf)
    }

    /// A version-1 continuation chunk holding `messages`: bare messages, with
    /// no signature and no checksum, which is all `H5O__chunk_deserialize`
    /// expects of one. Sized to fit, so it needs no padding.
    fn encode_v1_continuation(&self, messages: &[ObjectHeaderMessage]) -> FormatResult<Vec<u8>> {
        Self::check_v1_message_sizes(messages)?;
        let mut buf = Vec::with_capacity(self.messages_size_for(ObjectFormat::Legacy, messages));
        Self::write_messages_v1(&mut buf, messages);
        Ok(buf)
    }

    /// Encode this header in the version-1 format, with `nlink` as the object
    /// reference count and every message in chunk 0.
    ///
    /// The differences from [`encode`](Self::encode) are all
    /// `H5O_ALIGN_OLD`'s doing: no signature and no checksum, a two-byte
    /// message type, three reserved bytes where version 2 puts the optional
    /// creation index, and every message body padded out to eight bytes with
    /// the *padded* length in the size field. Refuses the two version-2
    /// prefix fields — see `check_v1_encodable`.
    pub fn encode_v1(&self, nlink: u32) -> FormatResult<Vec<u8>> {
        let exact = self.messages_size_for(ObjectFormat::Legacy, &self.messages);
        self.encode_v1_chunk0(&self.messages, exact, nlink, 0)
    }

    /// Encode this header in the version `format` calls for.
    ///
    /// `nlink` reaches the file only in the version-1 layout; the version-2
    /// header has no reference-count field (an object with more than one hard
    /// link carries an Object Reference Count message instead).
    pub fn encode_for(&self, format: ObjectFormat, nlink: u32) -> FormatResult<Vec<u8>> {
        match format {
            ObjectFormat::Legacy => self.encode_v1(nlink),
            ObjectFormat::Modern => self.encode(),
        }
    }
}

impl ObjectHeader {
    /// Decode a v1 object header from a byte buffer.
    ///
    /// v1 headers do NOT have the "OHDR" signature or a checksum. The layout is:
    /// ```text
    /// Byte 0: version = 1
    /// Byte 1: reserved
    /// Bytes 2-3: num_messages (u16 LE)
    /// Bytes 4-7: obj_ref_count (u32 LE)
    /// Bytes 8-11: header_data_size (u32 LE) — size of message data in first chunk
    /// Messages follow, each:
    ///   type: u16 LE
    ///   data_size: u16 LE
    ///   flags: u8
    ///   reserved: 3 bytes
    ///   data: data_size bytes (padded to 8-byte alignment)
    /// ```
    pub fn decode_v1(buf: &[u8]) -> FormatResult<(Self, usize)> {
        // V1 header prefix is 16 bytes: version(1) + reserved(1) + num_msg(2)
        // + ref_count(4) + chunk0_data_size(4) + reserved_padding(4)
        if buf.len() < 16 {
            return Err(FormatError::BufferTooShort {
                needed: 16,
                available: buf.len(),
            });
        }

        let version = buf[0];
        if version != 1 {
            return Err(FormatError::InvalidVersion(version));
        }

        // buf[1] = reserved
        let num_messages = u16::from_le_bytes([buf[2], buf[3]]) as usize;
        let _obj_ref_count = u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]);
        let header_data_size = u32::from_le_bytes([buf[8], buf[9], buf[10], buf[11]]) as usize;
        // buf[12..16] = reserved alignment padding

        let total_consumed = 16 + header_data_size;
        if buf.len() < total_consumed {
            return Err(FormatError::BufferTooShort {
                needed: total_consumed,
                available: buf.len(),
            });
        }

        let msg_data_start = 16; // offset where message data begins (after 16-byte prefix)
        let mut pos = msg_data_start;
        let messages_end = msg_data_start + header_data_size;
        let mut messages = Vec::with_capacity(num_messages);

        for _ in 0..num_messages {
            if pos + 8 > messages_end {
                break; // no more room for a message header
            }

            let msg_type = u16::from_le_bytes([buf[pos], buf[pos + 1]]);
            let data_size = u16::from_le_bytes([buf[pos + 2], buf[pos + 3]]) as usize;
            let msg_flags = buf[pos + 4];
            // bytes pos+5..pos+8 are reserved
            pos += 8;

            if pos + data_size > messages_end {
                return Err(FormatError::InvalidData(format!(
                    "v1 message data ({} bytes) extends past header boundary",
                    data_size
                )));
            }

            let data = buf[pos..pos + data_size].to_vec();
            pos += data_size;

            // In v1, messages are padded to 8-byte alignment relative to
            // the start of the message data region.
            let rel = pos - msg_data_start;
            let aligned_rel = (rel + 7) & !7;
            let aligned_pos = msg_data_start + aligned_rel;
            if aligned_pos <= messages_end {
                pos = aligned_pos;
            }

            // Skip null/padding messages (type 0)
            if msg_type == 0 {
                continue;
            }

            messages.push(ObjectHeaderMessage {
                msg_type: msg_type as u8,
                flags: msg_flags,
                // A version-1 message envelope has no creation index.
                creation_index: 0,
                data,
            });
        }

        Ok((
            ObjectHeader {
                flags: 0,
                // A v1 header keeps its modification time in a message
                // (`H5O_MSG_MTIME`), never in the prefix.
                times: None,
                messages,
            },
            total_consumed,
        ))
    }

    /// Auto-detect and decode either v1 or v2 object header.
    ///
    /// Checks for the "OHDR" signature to decide v2; otherwise tries v1.
    pub fn decode_any(buf: &[u8]) -> FormatResult<(Self, usize)> {
        if buf.len() >= 4 && buf[0..4] == OHDR_SIGNATURE {
            Self::decode(buf)
        } else if !buf.is_empty() && buf[0] == 1 {
            Self::decode_v1(buf)
        } else {
            // Try v2 first (will fail with proper error)
            Self::decode(buf)
        }
    }
}

#[cfg(test)]
mod tests_v1 {
    use super::*;

    /// Build a minimal v1 object header with given messages.
    fn build_v1_header(messages: &[(u16, u8, &[u8])]) -> Vec<u8> {
        let mut msg_data = Vec::new();
        for (msg_type, flags, data) in messages {
            msg_data.extend_from_slice(&msg_type.to_le_bytes());
            msg_data.extend_from_slice(&(data.len() as u16).to_le_bytes());
            msg_data.push(*flags);
            msg_data.extend_from_slice(&[0u8; 3]); // reserved
            msg_data.extend_from_slice(data);
            // Pad to 8-byte alignment
            let aligned = (msg_data.len() + 7) & !7;
            msg_data.resize(aligned, 0);
        }

        let mut buf = Vec::new();
        buf.push(1); // version
        buf.push(0); // reserved
        buf.extend_from_slice(&(messages.len() as u16).to_le_bytes());
        buf.extend_from_slice(&1u32.to_le_bytes()); // ref count
        buf.extend_from_slice(&(msg_data.len() as u32).to_le_bytes());
        buf.extend_from_slice(&[0u8; 4]); // reserved padding (align to 16 bytes)
        buf.extend_from_slice(&msg_data);
        buf
    }

    #[test]
    fn test_decode_v1_empty() {
        let buf = build_v1_header(&[]);
        let (hdr, consumed) = ObjectHeader::decode_v1(&buf).unwrap();
        assert_eq!(consumed, 16); // 16-byte prefix, no messages
        assert!(hdr.messages.is_empty());
    }

    #[test]
    fn test_decode_v1_single_message() {
        let data = vec![0xAA, 0xBB, 0xCC];
        let buf = build_v1_header(&[(0x03, 0x00, &data)]);
        let (hdr, _consumed) = ObjectHeader::decode_v1(&buf).unwrap();
        assert_eq!(hdr.messages.len(), 1);
        assert_eq!(hdr.messages[0].msg_type, 0x03);
        assert_eq!(hdr.messages[0].data, data);
    }

    #[test]
    fn test_decode_v1_multiple_messages() {
        let buf = build_v1_header(&[
            (0x01, 0x00, &[1, 2, 3, 4]),
            (0x03, 0x01, &[10, 20]),
            (0x08, 0x00, &[0xFF; 16]),
        ]);
        let (hdr, _) = ObjectHeader::decode_v1(&buf).unwrap();
        assert_eq!(hdr.messages.len(), 3);
        assert_eq!(hdr.messages[0].msg_type, 0x01);
        assert_eq!(hdr.messages[1].msg_type, 0x03);
        assert_eq!(hdr.messages[2].msg_type, 0x08);
        assert_eq!(hdr.messages[2].data, vec![0xFF; 16]);
    }

    /// The exact bytes h5py 3.15/libhdf5 1.14.6 wrote for the header of a
    /// contiguous `<i4` dataset of shape (6,) in a default (superblock-0)
    /// file: five messages, the last a null pad, chunk 0 of 256 bytes. Only
    /// the first four are re-encoded here — the pad is libhdf5 pre-allocating
    /// room to grow, not content — so the assertion is on the prefix shape and
    /// on each message's aligned envelope.
    #[test]
    fn an_encoded_v1_header_matches_the_envelope_libhdf5_writes() {
        let dataspace = vec![
            0x01, 0x01, 0x01, 0x00, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0,
        ];
        let datatype = vec![0x10, 0x08, 0, 0, 0x04, 0, 0, 0, 0, 0, 0x20, 0, 0, 0, 0, 0];
        let fill = vec![0x02, 0x02, 0x02, 0x01, 0, 0, 0, 0];
        // 18 raw bytes: version 3 contiguous layout, address then size.
        let layout = vec![
            0x03, 0x01, 0, 0x08, 0, 0, 0, 0, 0, 0, 0x18, 0, 0, 0, 0, 0, 0, 0,
        ];
        let mut header = ObjectHeader::new();
        header.add_message(0x01, 0x00, dataspace);
        header.add_message(0x03, 0x01, datatype);
        header.add_message(0x05, 0x01, fill);
        header.add_message(0x08, 0x00, layout);

        let buf = header.encode_v1(1).unwrap();
        assert_eq!(buf[0], 1, "version");
        assert_eq!(u16::from_le_bytes([buf[2], buf[3]]), 4, "message count");
        assert_eq!(
            u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]),
            1,
            "reference count"
        );
        // (8 + 24) + (8 + 16) + (8 + 8) + (8 + 24), the layout body aligned
        // from 18 to 24.
        assert_eq!(
            u32::from_le_bytes([buf[8], buf[9], buf[10], buf[11]]),
            104,
            "chunk 0 data size"
        );
        assert_eq!(buf.len(), 16 + 104);
        // The layout message's size field records the aligned length.
        let layout_at = 16 + 32 + 24 + 16;
        assert_eq!(u16::from_le_bytes([buf[layout_at], buf[layout_at + 1]]), 8);
        assert_eq!(
            u16::from_le_bytes([buf[layout_at + 2], buf[layout_at + 3]]),
            24
        );
        assert_eq!(&buf[layout_at + 8 + 18..layout_at + 8 + 24], &[0u8; 6]);
    }

    #[test]
    fn a_v1_header_round_trips_through_its_own_decoder() {
        let mut header = ObjectHeader::new();
        header.add_message(0x11, 0x00, vec![0xAB; 16]);
        header.add_message(0x0C, 0x00, vec![0xCD; 21]);
        let buf = header.encode_v1(3).unwrap();
        let (back, consumed) = ObjectHeader::decode_v1(&buf).unwrap();
        assert_eq!(consumed, buf.len());
        assert_eq!(back.messages.len(), 2);
        assert_eq!(back.messages[0].data, vec![0xAB; 16]);
        // The 21-byte body came back padded to 24, so re-encoding is stable.
        assert_eq!(back.messages[1].data.len(), 24);
        assert_eq!(back.encode_v1(3).unwrap(), buf);
        // `decode_any` must not mistake it for a version-2 header.
        assert_eq!(ObjectHeader::decode_any(&buf).unwrap().1, buf.len());
    }

    #[test]
    fn a_v1_header_refuses_to_drop_attribute_creation_order() {
        let mut header = ObjectHeader::new();
        header.set_attribute_creation_order(CreationOrder::Tracked);
        assert!(matches!(
            header.encode_v1(1).unwrap_err(),
            FormatError::InvalidData(_)
        ));
    }

    /// The times gate is the header version, not the caller: a version-1
    /// prefix has nowhere to put them, so `encode_v1` says so instead of
    /// returning a header whose times are gone.
    #[test]
    fn a_v1_header_refuses_to_drop_its_stored_times() {
        let mut header = ObjectHeader::new();
        header.add_message(0x11, 0x00, vec![0u8; 16]);
        assert!(header.encode_v1(1).is_ok());

        header.times = Some(ObjectTimes::created_at(0x1234_5678));
        assert!(matches!(
            header.encode_v1(1).unwrap_err(),
            FormatError::InvalidData(_)
        ));
        // The same header is fine as version 2, where the prefix holds them.
        let v2 = header.encode().unwrap();
        assert_eq!(v2[5] & FLAG_STORE_TIMESTAMPS, FLAG_STORE_TIMESTAMPS);
    }

    #[test]
    fn encode_for_picks_the_version_the_format_calls_for() {
        use crate::format::ObjectFormat;
        let mut header = ObjectHeader::new();
        header.add_message(0x11, 0x00, vec![0u8; 16]);
        assert_eq!(header.encode_for(ObjectFormat::Legacy, 1).unwrap()[0], 1);
        assert_eq!(
            &header.encode_for(ObjectFormat::Modern, 1).unwrap()[0..4],
            &OHDR_SIGNATURE
        );
    }

    #[test]
    fn test_decode_v1_skips_null_messages() {
        let buf = build_v1_header(&[
            (0x00, 0x00, &[0; 8]), // null message (type 0)
            (0x03, 0x00, &[1, 2]),
        ]);
        let (hdr, _) = ObjectHeader::decode_v1(&buf).unwrap();
        assert_eq!(hdr.messages.len(), 1);
        assert_eq!(hdr.messages[0].msg_type, 0x03);
    }

    #[test]
    fn test_decode_any_v2() {
        let mut hdr = ObjectHeader::new();
        hdr.add_message(0x01, 0x00, vec![1, 2, 3]);
        let encoded = hdr.encode().unwrap();
        let (decoded, _) = ObjectHeader::decode_any(&encoded).unwrap();
        assert_eq!(decoded.messages.len(), 1);
    }

    #[test]
    fn test_decode_any_v1() {
        let buf = build_v1_header(&[(0x03, 0x00, &[1, 2])]);
        let (decoded, _) = ObjectHeader::decode_any(&buf).unwrap();
        assert_eq!(decoded.messages.len(), 1);
        assert_eq!(decoded.messages[0].msg_type, 0x03);
    }

    #[test]
    fn test_decode_v1_bad_version() {
        let mut buf = build_v1_header(&[]);
        buf[0] = 5;
        assert!(matches!(
            ObjectHeader::decode_v1(&buf).unwrap_err(),
            FormatError::InvalidVersion(5)
        ));
    }

    #[test]
    fn test_decode_v1_buffer_too_short() {
        assert!(matches!(
            ObjectHeader::decode_v1(&[1, 0, 0]).unwrap_err(),
            FormatError::BufferTooShort { .. }
        ));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_empty_header_roundtrip() {
        let hdr = ObjectHeader::new();
        let encoded = hdr.encode().unwrap();

        // OHDR(4) + version(1) + flags(1) + chunk0_size(1) + checksum(4) = 11:
        // no messages, so the narrowest size field, as `H5O_apply_ohdr`
        // picks it.
        assert_eq!(encoded.len(), 11);
        assert_eq!(&encoded[..4], b"OHDR");
        assert_eq!(encoded[4], 2); // version
        assert_eq!(encoded[5] & FLAG_SIZE_MASK, 0);

        let (decoded, consumed) = ObjectHeader::decode(&encoded).expect("decode failed");
        assert_eq!(consumed, encoded.len());
        assert_eq!(decoded, hdr);
    }

    #[test]
    fn test_single_message_roundtrip() {
        let mut hdr = ObjectHeader::new();
        hdr.add_message(0x01, 0x00, vec![0xAA, 0xBB, 0xCC]);

        let encoded = hdr.encode().unwrap();
        let (decoded, consumed) = ObjectHeader::decode(&encoded).expect("decode failed");
        assert_eq!(consumed, encoded.len());
        assert_eq!(decoded.messages.len(), 1);
        assert_eq!(decoded.messages[0].msg_type, 0x01);
        assert_eq!(decoded.messages[0].flags, 0x00);
        assert_eq!(decoded.messages[0].data, vec![0xAA, 0xBB, 0xCC]);
    }

    #[test]
    fn test_multiple_messages_roundtrip() {
        let mut hdr = ObjectHeader::new();
        hdr.add_message(0x01, 0x00, vec![1, 2, 3, 4]);
        hdr.add_message(0x03, 0x01, vec![10, 20]);
        hdr.add_message(0x0C, 0x00, vec![]);

        let encoded = hdr.encode().unwrap();
        let (decoded, consumed) = ObjectHeader::decode(&encoded).expect("decode failed");
        assert_eq!(consumed, encoded.len());
        assert_eq!(decoded.messages.len(), 3);
        assert_eq!(decoded, hdr);
    }

    #[test]
    fn test_with_creation_order() {
        let mut hdr = ObjectHeader {
            flags: 0x02 | FLAG_ATTR_CREATION_ORDER_TRACKED,
            times: None,
            messages: Vec::new(),
        };
        hdr.add_message(0x01, 0x00, vec![0xFF; 8]);
        hdr.add_message(0x03, 0x00, vec![0xEE; 4]);

        let encoded = hdr.encode().unwrap();
        let (decoded, consumed) = ObjectHeader::decode(&encoded).expect("decode failed");
        assert_eq!(consumed, encoded.len());
        assert_eq!(decoded.messages.len(), 2);
        assert_eq!(decoded.messages[0].data, vec![0xFF; 8]);
        assert_eq!(decoded.messages[1].data, vec![0xEE; 4]);
    }

    /// The per-message creation index survives a round trip, and lands where
    /// libhdf5 puts it: right after the message flags byte, ahead of the
    /// message data.
    #[test]
    fn a_tracked_header_round_trips_each_message_creation_index() {
        let mut hdr = ObjectHeader::new();
        hdr.set_attribute_creation_order(CreationOrder::Indexed);
        hdr.add_message_indexed(0x0C, 0x00, vec![0xAA; 6], 0);
        hdr.add_message_indexed(0x0C, 0x00, vec![0xBB; 6], 1);
        hdr.add_message_indexed(0x0C, 0x00, vec![0xCC; 6], 2);

        let encoded = hdr.encode().unwrap();
        let (decoded, consumed) = ObjectHeader::decode(&encoded).expect("decode failed");
        assert_eq!(consumed, encoded.len());
        assert_eq!(decoded, hdr);
        let indices: Vec<u16> = decoded.messages.iter().map(|m| m.creation_index).collect();
        assert_eq!(indices, vec![0, 1, 2]);

        // Off: no index is written, and every message decodes with 0.
        let mut plain = ObjectHeader::new();
        plain.add_message(0x0C, 0x00, vec![0xAA; 6]);
        assert!(plain.encode().unwrap().len() < encoded.len());
        let (plain_back, _) = ObjectHeader::decode(&plain.encode().unwrap()).unwrap();
        assert_eq!(plain_back.messages[0].creation_index, 0);
    }

    /// The two flag bits are set and read back independently, so a header that
    /// tracks without indexing survives a decode as exactly that — the state
    /// `H5Pset_attr_creation_order(H5P_CRT_ORDER_TRACKED)` produces.
    #[test]
    fn each_attribute_creation_order_state_round_trips_through_the_flags() {
        for order in [
            CreationOrder::Untracked,
            CreationOrder::Tracked,
            CreationOrder::Indexed,
        ] {
            let mut hdr = ObjectHeader::new();
            hdr.set_attribute_creation_order(order);
            hdr.add_message_indexed(0x0C, 0x00, vec![0xAA; 6], 3);
            let (decoded, _) = ObjectHeader::decode(&hdr.encode().unwrap()).unwrap();
            assert_eq!(decoded.attribute_creation_order(), order);
            let want_index = if order.is_tracked() { 3 } else { 0 };
            assert_eq!(decoded.messages[0].creation_index, want_index);
        }
    }

    /// Setting a policy clears whatever the previous one left behind, so a
    /// header recovered as indexed and re-declared untracked does not keep a
    /// stale bit.
    #[test]
    fn setting_a_weaker_policy_clears_the_stronger_one() {
        let mut hdr = ObjectHeader::new();
        hdr.set_attribute_creation_order(CreationOrder::Indexed);
        hdr.set_attribute_creation_order(CreationOrder::Untracked);
        assert_eq!(hdr.attribute_creation_order(), CreationOrder::Untracked);
        assert_eq!(hdr.flags, 0);
    }

    /// The four times survive a round trip in `H5O__cache_serialize` order,
    /// and their presence is what sets `H5O_HDR_STORE_TIMES` in the file.
    #[test]
    fn stored_times_round_trip_and_set_the_flag() {
        let mut hdr = ObjectHeader::new();
        hdr.add_message(0x01, 0x00, vec![1, 2, 3]);
        let without = hdr.encode().unwrap();

        hdr.times = Some(ObjectTimes {
            access: 0x0A0A_0A0A,
            modification: 0x0B0B_0B0B,
            change: 0x0C0C_0C0C,
            birth: 0x0D0D_0D0D,
        });
        let with = hdr.encode().unwrap();

        assert_eq!(with.len(), without.len() + 16);
        assert_eq!(with[5] & FLAG_STORE_TIMESTAMPS, FLAG_STORE_TIMESTAMPS);
        assert_eq!(&with[6..10], &0x0A0A_0A0Au32.to_le_bytes());
        assert_eq!(&with[10..14], &0x0B0B_0B0Bu32.to_le_bytes());
        assert_eq!(&with[14..18], &0x0C0C_0C0Cu32.to_le_bytes());
        assert_eq!(&with[18..22], &0x0D0D_0D0Du32.to_le_bytes());

        let (decoded, consumed) = ObjectHeader::decode(&with).expect("decode failed");
        assert_eq!(consumed, with.len());
        assert_eq!(decoded, hdr);
    }

    /// The flag cannot be set without the times behind it: bit 5 poked into
    /// `flags` by hand is dropped at encode rather than announcing sixteen
    /// bytes that are not there — the shape that made a rewrite emit zero
    /// timestamps.
    #[test]
    fn the_timestamps_flag_is_never_written_without_times() {
        let mut hdr = ObjectHeader::new();
        hdr.flags |= FLAG_STORE_TIMESTAMPS;
        hdr.add_message(0x01, 0x00, vec![1, 2, 3]);

        let encoded = hdr.encode().unwrap();
        assert_eq!(encoded[5] & FLAG_STORE_TIMESTAMPS, 0);
        let (decoded, _) = ObjectHeader::decode(&encoded).expect("decode failed");
        assert_eq!(decoded.times, None);
        assert_eq!(decoded.flags & FLAG_STORE_TIMESTAMPS, 0);
    }

    /// `H5O_touch_oh` on a version-2 header moves access and change time to
    /// now and leaves modification and birth time alone.
    #[test]
    fn touching_moves_access_and_change_time_only() {
        let before = ObjectTimes {
            access: 100,
            modification: 200,
            change: 300,
            birth: 400,
        };
        assert_eq!(
            before.touched(999),
            ObjectTimes {
                access: 999,
                modification: 200,
                change: 999,
                birth: 400,
            }
        );
        assert_eq!(
            ObjectTimes::created_at(7).touched(7),
            ObjectTimes::created_at(7)
        );
    }

    #[test]
    fn test_chunk0_size_1byte() {
        // flags bits 0-1 = 0 => 1-byte chunk0 size
        let mut hdr = ObjectHeader {
            flags: 0x00,
            times: None,
            messages: Vec::new(),
        };
        hdr.add_message(0x01, 0x00, vec![42]);

        let encoded = hdr.encode().unwrap();
        let (decoded, consumed) = ObjectHeader::decode(&encoded).expect("decode failed");
        assert_eq!(consumed, encoded.len());
        assert_eq!(decoded.messages[0].data, vec![42]);
    }

    #[test]
    fn test_chunk0_size_2byte() {
        // flags bits 0-1 = 1 => 2-byte chunk0 size
        let mut hdr = ObjectHeader {
            flags: 0x01,
            times: None,
            messages: Vec::new(),
        };
        hdr.add_message(0x01, 0x00, vec![1, 2, 3]);

        let encoded = hdr.encode().unwrap();
        let (decoded, consumed) = ObjectHeader::decode(&encoded).expect("decode failed");
        assert_eq!(consumed, encoded.len());
        assert_eq!(decoded.messages[0].data, vec![1, 2, 3]);
    }

    #[test]
    fn test_chunk0_size_8byte() {
        // flags bits 0-1 = 3 => 8-byte chunk0 size
        let mut hdr = ObjectHeader {
            flags: 0x03,
            times: None,
            messages: Vec::new(),
        };
        hdr.add_message(0x01, 0x00, vec![0xDE, 0xAD]);

        let encoded = hdr.encode().unwrap();
        let (decoded, consumed) = ObjectHeader::decode(&encoded).expect("decode failed");
        assert_eq!(consumed, encoded.len());
        assert_eq!(decoded.messages[0].data, vec![0xDE, 0xAD]);
    }

    #[test]
    fn test_decode_bad_signature() {
        let mut data = vec![0u8; 20];
        data[0..4].copy_from_slice(b"XHDR");
        let err = ObjectHeader::decode(&data).unwrap_err();
        assert!(matches!(err, FormatError::InvalidSignature));
    }

    #[test]
    fn test_decode_bad_version() {
        let hdr = ObjectHeader::new();
        let mut encoded = hdr.encode().unwrap();
        encoded[4] = 99; // corrupt version
        let err = ObjectHeader::decode(&encoded).unwrap_err();
        assert!(matches!(err, FormatError::InvalidVersion(99)));
    }

    #[test]
    fn test_decode_checksum_mismatch() {
        let mut hdr = ObjectHeader::new();
        hdr.add_message(0x01, 0x00, vec![1, 2, 3]);
        let mut encoded = hdr.encode().unwrap();
        // Corrupt a message byte
        let last_data = encoded.len() - 5;
        encoded[last_data] ^= 0xFF;
        let err = ObjectHeader::decode(&encoded).unwrap_err();
        assert!(matches!(err, FormatError::ChecksumMismatch { .. }));
    }

    #[test]
    fn test_decode_buffer_too_short() {
        let err = ObjectHeader::decode(&[0u8; 5]).unwrap_err();
        assert!(matches!(err, FormatError::BufferTooShort { .. }));
    }

    #[test]
    fn test_decode_with_trailing_data() {
        let mut hdr = ObjectHeader::new();
        hdr.add_message(0x01, 0x00, vec![7, 8, 9]);
        let mut encoded = hdr.encode().unwrap();
        let original_len = encoded.len();
        encoded.extend_from_slice(&[0xBB; 50]); // trailing garbage

        let (decoded, consumed) = ObjectHeader::decode(&encoded).expect("decode failed");
        assert_eq!(consumed, original_len);
        assert_eq!(decoded, hdr);
    }

    #[test]
    fn test_large_message_payload() {
        let mut hdr = ObjectHeader::new();
        let big_data = vec![0x42; 1000];
        hdr.add_message(0x0C, 0x00, big_data.clone());

        let encoded = hdr.encode().unwrap();
        let (decoded, consumed) = ObjectHeader::decode(&encoded).expect("decode failed");
        assert_eq!(consumed, encoded.len());
        assert_eq!(decoded.messages[0].data.len(), 1000);
        assert_eq!(decoded.messages[0].data, big_data);
    }

    /// The largest payload the size field can express still round-trips.
    #[test]
    fn test_message_payload_at_size_limit() {
        let mut hdr = ObjectHeader::new();
        hdr.add_message(0x0C, 0x00, vec![0x42; MAX_MESSAGE_SIZE]);

        let encoded = hdr.encode().expect("encode at the limit must succeed");
        let (decoded, consumed) = ObjectHeader::decode(&encoded).expect("decode failed");
        assert_eq!(consumed, encoded.len());
        assert_eq!(decoded.messages[0].data.len(), MAX_MESSAGE_SIZE);
    }

    /// One byte past the limit is refused. Encoding it would store the length
    /// modulo 65536 — here 0 — and every message after it would decode from
    /// the middle of this one's payload, with a checksum that still matches.
    #[test]
    fn test_message_payload_over_size_limit_is_refused() {
        let mut hdr = ObjectHeader::new();
        hdr.add_message(0x01, 0x00, vec![7; 4]);
        hdr.add_message(0x0C, 0x00, vec![0x42; MAX_MESSAGE_SIZE + 1]);

        let err = hdr.encode().expect_err("over the limit must not encode");
        let msg = err.to_string();
        assert!(msg.contains("0x0C"), "{msg}");
        assert!(msg.contains(&(MAX_MESSAGE_SIZE + 1).to_string()), "{msg}");
    }

    #[test]
    fn test_default() {
        let hdr = ObjectHeader::default();
        assert_eq!(hdr.flags, 0);
        assert!(hdr.messages.is_empty());
    }

    /// A header with three 40-byte messages, for the chunking tests below.
    fn chunked_header() -> ObjectHeader {
        let mut hdr = ObjectHeader::new();
        for (i, t) in [0x02u8, 0x0A, 0x0C].iter().enumerate() {
            hdr.add_message(*t, 0x00, vec![i as u8; 40]);
        }
        hdr
    }

    /// A capacity that covers every message leaves one chunk, and the image is
    /// the one `encode` produces on its own.
    #[test]
    fn a_capacity_that_fits_every_message_plans_one_chunk() {
        let hdr = chunked_header();
        let ctx = FormatContext::default_v3();
        let plan = hdr.plan_chunks(ObjectFormat::Modern, 1024, &ctx).unwrap();
        assert_eq!(plan.continuation_size, 0);
        let (chunk0, continuation) = hdr
            .encode_chunked(&plan, ObjectFormat::Modern, &ctx, 0x1000, 1)
            .unwrap();
        assert!(continuation.is_none());
        assert_eq!(chunk0, hdr.encode().unwrap());
        assert_eq!(chunk0.len(), plan.chunk0_size);
    }

    /// Past the capacity the tail of the message list moves into an `OCHK`
    /// chunk, chunk 0 names it by address and length, and both chunks carry a
    /// checksum over their own image.
    #[test]
    fn messages_past_the_capacity_move_into_a_continuation_chunk() {
        let hdr = chunked_header();
        let ctx = FormatContext::default_v3();
        // Room for one 44-byte message and the 20-byte continuation message.
        let plan = hdr.plan_chunks(ObjectFormat::Modern, 64, &ctx).unwrap();
        assert_eq!(plan.continuation_size, 4 + 2 * 44 + 4);
        let (chunk0, continuation) = hdr
            .encode_chunked(&plan, ObjectFormat::Modern, &ctx, 0x2000, 1)
            .unwrap();
        let continuation = continuation.unwrap();
        assert_eq!(chunk0.len(), plan.chunk0_size);
        assert_eq!(continuation.len(), plan.continuation_size);
        assert_eq!(&continuation[..4], &OCHK_SIGNATURE);

        let (decoded, consumed) = ObjectHeader::decode(&chunk0).unwrap();
        assert_eq!(consumed, chunk0.len());
        assert_eq!(
            decoded.messages.len(),
            2,
            "the first message and the pointer"
        );
        assert_eq!(decoded.messages[0], hdr.messages[0]);
        let pointer = &decoded.messages[1];
        assert_eq!(pointer.msg_type, MSG_CONTINUATION);
        assert_eq!(
            u64::from_le_bytes(pointer.data[..8].try_into().unwrap()),
            0x2000
        );
        assert_eq!(
            u64::from_le_bytes(pointer.data[8..16].try_into().unwrap()),
            plan.continuation_size as u64
        );

        let body = &continuation[..continuation.len() - 4];
        let stored = u32::from_le_bytes(continuation[continuation.len() - 4..].try_into().unwrap());
        assert_eq!(stored, checksum_metadata(body));
    }

    /// Space left in chunk 0 becomes a NIL message when a message envelope
    /// fits in it, and zero bytes — a "gap" — when it does not.
    #[test]
    fn leftover_chunk_zero_space_is_a_nil_message_or_a_gap() {
        let hdr = chunked_header();
        let ctx = FormatContext::default_v3();

        // 44 (message) + 20 (continuation) + 8 leaves room for a NIL.
        let (chunk0, _) = hdr
            .encode_chunked(
                &hdr.plan_chunks(ObjectFormat::Modern, 72, &ctx).unwrap(),
                ObjectFormat::Modern,
                &ctx,
                0x2000,
                1,
            )
            .unwrap();
        let tail = &chunk0[chunk0.len() - 4 - 8..chunk0.len() - 4];
        assert_eq!(tail, [MSG_NIL, 4, 0, 0, 0, 0, 0, 0]);

        // Three bytes over is one short of an envelope, so they stay a gap.
        let (chunk0, _) = hdr
            .encode_chunked(
                &hdr.plan_chunks(ObjectFormat::Modern, 67, &ctx).unwrap(),
                ObjectFormat::Modern,
                &ctx,
                0x2000,
                1,
            )
            .unwrap();
        assert_eq!(&chunk0[chunk0.len() - 4 - 3..chunk0.len() - 4], [0, 0, 0]);
        // A gap is not a message: the decoder stops at it.
        let (decoded, _) = ObjectHeader::decode(&chunk0).unwrap();
        assert_eq!(decoded.messages.len(), 2);
    }

    /// A capacity with no room for the message naming the continuation cannot
    /// be planned: chunk 0 would spill with nothing pointing at the spill.
    #[test]
    fn a_capacity_below_the_continuation_message_is_refused() {
        let hdr = chunked_header();
        let err = hdr
            .plan_chunks(ObjectFormat::Modern, 19, &FormatContext::default_v3())
            .expect_err("19 bytes cannot hold a 20-byte continuation message");
        assert!(err.to_string().contains("continuation chunk"), "{err}");
    }

    /// The times a version-2 header stores sit in its prefix, ahead of the
    /// message area a plan divides — so a header carrying them reserves
    /// sixteen more bytes for chunk 0 and spills at exactly the same message.
    ///
    /// `chunk0_capacity` in the writer budgets the *message* area, and the
    /// prefix is added on top of it here; a plan that folded the times into
    /// that budget would size chunk 0 sixteen bytes short of the image
    /// `encode_chunked` then produces, which `check_header_size` refuses.
    #[test]
    fn the_times_prefix_widens_chunk_zero_without_moving_the_split() {
        let ctx = FormatContext::default_v3();
        let plain = chunked_header();
        let mut timed = chunked_header();
        timed.times = Some(ObjectTimes::created_at(0x5EED_1234));

        for capacity in [72usize, 120, 1024] {
            let a = plain
                .plan_chunks(ObjectFormat::Modern, capacity, &ctx)
                .unwrap();
            let b = timed
                .plan_chunks(ObjectFormat::Modern, capacity, &ctx)
                .unwrap();
            assert_eq!(a.split, b.split, "capacity {capacity}: same split");
            assert_eq!(
                a.continuation_size, b.continuation_size,
                "capacity {capacity}: same continuation"
            );
            assert_eq!(
                b.chunk0_size,
                a.chunk0_size + 16,
                "capacity {capacity}: four times of four bytes"
            );
        }

        // And the plan describes the image: chunk 0 is the length the plan
        // said, times included.
        let plan = timed.plan_chunks(ObjectFormat::Modern, 72, &ctx).unwrap();
        let (chunk0, continuation) = timed
            .encode_chunked(&plan, ObjectFormat::Modern, &ctx, 0x2000, 1)
            .unwrap();
        assert_eq!(chunk0.len(), plan.chunk0_size);
        assert_eq!(continuation.unwrap().len(), plan.continuation_size);
        let (decoded, _) = ObjectHeader::decode(&chunk0).unwrap();
        assert_eq!(decoded.times, timed.times);
    }

    /// A version-1 header planned with no bound is one chunk, and the image
    /// is the one `encode_v1` produces on its own — which is how the writer
    /// lays out a fresh legacy header whatever it holds.
    #[test]
    fn a_version_one_plan_with_no_bound_is_one_chunk() {
        let hdr = chunked_header();
        let ctx = FormatContext::default_v3();
        let plan = hdr
            .plan_chunks(ObjectFormat::Legacy, usize::MAX, &ctx)
            .unwrap();
        assert_eq!(plan.continuation_size, 0);
        let (chunk0, continuation) = hdr
            .encode_chunked(&plan, ObjectFormat::Legacy, &ctx, 0x2000, 3)
            .unwrap();
        assert!(continuation.is_none());
        assert_eq!(chunk0, hdr.encode_v1(3).unwrap());
        assert_eq!(chunk0.len(), plan.chunk0_size);
    }

    /// Past the capacity a version-1 header spills into a bare continuation
    /// chunk — messages with no signature and no checksum — and chunk 0's
    /// prefix counts every message in the header: its own, the one naming
    /// the continuation, the NIL filling the rest of the area, and the
    /// spilled ones, which is the count `H5O_protect` checks the chunks
    /// against (H5Oint.c:1094).
    #[test]
    fn a_version_one_header_spills_into_a_bare_continuation_chunk() {
        let hdr = chunked_header();
        let ctx = FormatContext::default_v3();
        // Each message is 8 + 40 bytes; the continuation message is 8 + 16.
        // 80 bytes hold one of each and leave 8: a NIL with an empty body.
        let plan = hdr.plan_chunks(ObjectFormat::Legacy, 80, &ctx).unwrap();
        assert_eq!(plan.chunk0_size, 16 + 80);
        assert_eq!(plan.continuation_size, 2 * 48);
        let (chunk0, continuation) = hdr
            .encode_chunked(&plan, ObjectFormat::Legacy, &ctx, 0x2000, 1)
            .unwrap();
        let continuation = continuation.unwrap();
        assert_eq!(chunk0.len(), plan.chunk0_size);
        assert_eq!(continuation.len(), plan.continuation_size);
        assert_eq!(u16::from_le_bytes([chunk0[2], chunk0[3]]), 5, "nmesgs");
        assert_eq!(&chunk0[8..12], &80u32.to_le_bytes());
        // The NIL closes the area: type 0, an empty padded body.
        assert_eq!(&chunk0[16 + 48 + 24..], &[0u8; 8]);

        let (decoded, consumed) = ObjectHeader::decode_v1(&chunk0).unwrap();
        assert_eq!(consumed, chunk0.len());
        assert_eq!(
            decoded.messages.len(),
            2,
            "the first message and the pointer"
        );
        assert_eq!(decoded.messages[0], hdr.messages[0]);
        let pointer = &decoded.messages[1];
        assert_eq!(pointer.msg_type, MSG_CONTINUATION);
        assert_eq!(
            u64::from_le_bytes(pointer.data[..8].try_into().unwrap()),
            0x2000
        );
        assert_eq!(
            u64::from_le_bytes(pointer.data[8..16].try_into().unwrap()),
            plan.continuation_size as u64
        );
        // Bare messages: the second message's envelope opens the chunk.
        assert_eq!(&continuation[..4], &[0x0A, 0, 40, 0]);
        assert_eq!(&continuation[8..48], &hdr.messages[1].data[..]);
        assert_eq!(&continuation[48..52], &[0x0C, 0, 40, 0]);
    }

    /// A plan into an existing block holds chunk 0 to the block: a header
    /// that fits leaves the rest as a NIL message (version 2) or a NIL whose
    /// padded body fills it (version 1), and a block the messages outgrow
    /// spills exactly as a capacity would.
    #[test]
    fn a_plan_into_a_block_holds_chunk_zero_to_it() {
        let hdr = chunked_header();
        let ctx = FormatContext::default_v3();

        // Version 2 under a one-byte size field: 4 + 1 + 1 + 1 of prefix, the
        // three 44-byte messages, 20 bytes to spare, and the checksum.
        let block = 7 + 3 * 44 + 20 + 4;
        let plan = hdr
            .plan_chunks_in(ObjectFormat::Modern, block, &ctx)
            .unwrap();
        assert_eq!((plan.chunk0_size, plan.continuation_size), (block, 0));
        let (chunk0, continuation) = hdr
            .encode_chunked(&plan, ObjectFormat::Modern, &ctx, 0, 1)
            .unwrap();
        assert!(continuation.is_none());
        assert_eq!(chunk0.len(), block);
        let (decoded, consumed) = ObjectHeader::decode(&chunk0).unwrap();
        assert_eq!(consumed, block);
        assert_eq!(decoded.messages[..3], hdr.messages[..]);
        assert_eq!(decoded.messages[3].msg_type, MSG_NIL);
        assert_eq!(decoded.messages[3].data.len(), 20 - 4);

        // The same block split: 7 + area + 4 with area = 44 + 20 (pointer) + 8.
        let plan = hdr
            .plan_chunks_in(ObjectFormat::Modern, 7 + 72 + 4, &ctx)
            .unwrap();
        assert_eq!(plan.chunk0_size, 7 + 72 + 4);
        assert_eq!(plan.continuation_size, 4 + 2 * 44 + 4);

        // Version 1: 16 of prefix, three 48-byte messages, and 16 to spare —
        // a NIL with an 8-byte padded body.
        let block = 16 + 3 * 48 + 16;
        let plan = hdr
            .plan_chunks_in(ObjectFormat::Legacy, block, &ctx)
            .unwrap();
        assert_eq!((plan.chunk0_size, plan.continuation_size), (block, 0));
        let (chunk0, _) = hdr
            .encode_chunked(&plan, ObjectFormat::Legacy, &ctx, 0, 1)
            .unwrap();
        assert_eq!(chunk0.len(), block);
        assert_eq!(u16::from_le_bytes([chunk0[2], chunk0[3]]), 4, "nmesgs");
        assert_eq!(&chunk0[block - 16..block - 12], &[0, 0, 8, 0]);
        let (decoded, consumed) = ObjectHeader::decode_v1(&chunk0).unwrap();
        assert_eq!(consumed, block);
        assert_eq!(decoded.messages, hdr.messages);

        // A version-1 area that is not a multiple of eight has no legal
        // padding; a block too short for either prefix has no chunk 0.
        for (format, block) in [
            (ObjectFormat::Legacy, 16 + 3 * 48 + 12),
            (ObjectFormat::Legacy, 8),
            (ObjectFormat::Modern, 10),
        ] {
            hdr.plan_chunks_in(format, block, &ctx)
                .expect_err("an undescribable block");
        }
    }

    /// A plan into a block takes the narrowest chunk-0 size field that can
    /// express the area, whatever width the header's own flags name: a
    /// header libhdf5 sized exactly for its messages — under a one-byte
    /// field — takes them back without spilling, and a block past 255 bytes
    /// of area widens the field rather than being refused.
    #[test]
    fn a_plan_into_a_block_takes_the_narrowest_size_field() {
        let mut hdr = chunked_header();
        // The header's own field would be the widest: the plan ignores it.
        hdr.flags |= 3;
        let ctx = FormatContext::default_v3();

        // libhdf5's exact fit for these messages: a one-byte field.
        let exact = 7 + 3 * 44 + 4;
        let plan = hdr
            .plan_chunks_in(ObjectFormat::Modern, exact, &ctx)
            .unwrap();
        assert_eq!(plan.continuation_size, 0);
        let (chunk0, _) = hdr
            .encode_chunked(&plan, ObjectFormat::Modern, &ctx, 0, 1)
            .unwrap();
        assert_eq!(chunk0.len(), exact);
        assert_eq!(chunk0[5] & FLAG_SIZE_MASK, 0);
        let (decoded, _) = ObjectHeader::decode(&chunk0).unwrap();
        assert_eq!(decoded.messages, hdr.messages);

        // 300 bytes of area need a two-byte field.
        let plan = hdr
            .plan_chunks_in(ObjectFormat::Modern, 8 + 300 + 4, &ctx)
            .unwrap();
        let (chunk0, _) = hdr
            .encode_chunked(&plan, ObjectFormat::Modern, &ctx, 0, 1)
            .unwrap();
        assert_eq!(chunk0.len(), 8 + 300 + 4);
        assert_eq!(chunk0[5] & FLAG_SIZE_MASK, 1);
        let (decoded, consumed) = ObjectHeader::decode(&chunk0).unwrap();
        assert_eq!(consumed, chunk0.len());
        assert_eq!(decoded.messages[..3], hdr.messages[..]);

        // The header itself is left as it was.
        assert_eq!(hdr.flags & FLAG_SIZE_MASK, 3);
    }
}