xisf-core 0.5.2

Core engine for reading and writing XISF (Extensible Image Serialization Format) files
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
//! Writing monolithic XISF files.
//!
//! # The positioning problem
//!
//! An attached block is addressed by `location="attachment:position:size"`,
//! where the position is an *absolute* file offset. But the header sits before
//! the blocks, so a block's position depends on how long the header is -- and
//! the header's length depends on how many digits those positions take. A
//! naive encoder either leaves a gap or writes a position that is wrong by the
//! width of a number.
//!
//! Both PixInsight and libXISF place the first block immediately after the
//! header with no padding, so the addressing here does the same, by iterating
//! to a fixed point: render the header assuming a length, see what length it
//! actually came out, and render again if it changed. It converges because a
//! longer header can only push positions further out, which can only add
//! digits, and adding digits only lengthens the header -- a monotonic climb
//! that stops as soon as no number gains a digit. In practice that is one or
//! two rounds.

use crate::block::{ChecksumAlgorithm, Codec, Compression, HEADER_DIR_TOKEN};
use crate::codec;
use crate::err;
use crate::error::Result;
use crate::image::{ColorFilterArray, DisplayFunction, Gamma, Image, Resolution, RgbWorkingSpace};
use crate::layout::{PREAMBLE_LEN, SIGNATURE};
use crate::reader::{checksum_of, digest_hex};
use crate::table::Table;

/// How a block should be stored.
#[derive(Clone, Debug, Default)]
pub struct BlockOptions {
    /// Codec and shuffling to apply, or `None` to store the bytes as they are.
    pub compression: Option<CompressionRequest>,
    /// Hash to record, or `None` for no checksum.
    pub checksum: Option<ChecksumAlgorithm>,
}

/// A request to compress, before the compressed size is known.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct CompressionRequest {
    pub codec: Codec2,
    /// Byte-shuffle in items of this width first. `None` for no shuffling.
    ///
    /// Shuffling only helps when the item width matches the data's element
    /// size, which is why this is chosen by the caller rather than guessed.
    pub shuffle_item_size: Option<u64>,
}

/// The codecs this crate can *write*.
///
/// Narrower than [`Codec`], deliberately: [`Codec`] also names LZ4_HC, which
/// is an encoder setting rather than a stream format and which this writer
/// does not offer, and the codecs a future file might use that this build
/// cannot produce. A separate type makes that a compile-time fact rather than
/// a runtime surprise.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Codec2 {
    /// Zstandard, which Revision 1 makes the recommended codec. It is the
    /// default here for that reason.
    #[default]
    Zstd,
    Zlib,
    Lz4,
}

impl Codec2 {
    fn as_codec(self) -> Codec {
        match self {
            Codec2::Zstd => Codec::Zstd,
            Codec2::Zlib => Codec::Zlib,
            Codec2::Lz4 => Codec::Lz4,
        }
    }
}

/// How the header names its blocks.
///
/// The two XISF forms differ in exactly this and nothing else, so the header
/// is rendered once and told how to address rather than written twice.
#[derive(Clone, Copy, Debug)]
enum Addressing<'a> {
    /// Monolithic: `attachment:position:size`, an absolute offset into the
    /// same file. Needs the position the data begins at, which is what makes
    /// the fixed-point loop necessary.
    Attached { data_at: usize },
    /// Distributed: `path(name.xisb):0xID`, naming a block in a separate data
    /// blocks file by its index identifier. No positions appear in the
    /// header, so nothing has to converge.
    Distributed { blocks_file: &'a str },
}

/// A distributed unit: an XISF header file and the data blocks file it names.
#[derive(Clone, Debug)]
pub struct DistributedUnit {
    /// The `.xish` header file's contents: the XML header and nothing else.
    pub header: Vec<u8>,
    /// The `.xisb` data blocks file's contents.
    pub blocks: Vec<u8>,
    /// The blocks file's name, as the header refers to it.
    pub blocks_file_name: String,
}

/// An image to write, with its pixel data and whatever is attached to it.
///
/// The ancillary elements are what a reader loses if a writer cannot produce
/// them: a read-modify-write cycle through a writer that only knows about
/// pixels drops the colour profile, the preview and the mosaic pattern
/// without saying so.
#[derive(Clone, Debug)]
pub struct PendingImage {
    pub image: Image,
    pub data: Vec<u8>,
    pub options: BlockOptions,
    /// Pixels per unit of length.
    pub resolution: Option<Resolution>,
    /// The colour space the pixel values are expressed in.
    pub rgb_working_space: Option<RgbWorkingSpace>,
    /// How the image should be displayed, which is not how it is stored.
    pub display_function: Option<DisplayFunction>,
    /// The mosaic pattern, for an image straight off a colour sensor.
    pub color_filter_array: Option<ColorFilterArray>,
    /// A raw ICC profile, written to its own data block.
    pub icc_profile: Option<Vec<u8>>,
    /// A preview of this image, written to its own data block.
    pub thumbnail: Option<PendingThumbnail>,
    /// FITS keywords, in the order they should appear.
    pub fits_keywords: Vec<FitsKeyword>,
    /// Table properties belonging to this image.
    pub tables: Vec<Table>,
}

/// A preview image attached to another image.
#[derive(Clone, Debug)]
pub struct PendingThumbnail {
    pub image: Image,
    pub data: Vec<u8>,
    pub options: BlockOptions,
}

/// One `<FITSKeyword>` element.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FitsKeyword {
    pub name: String,
    pub value: String,
    pub comment: String,
}

impl PendingImage {
    /// An image with pixel data and nothing attached to it.
    pub fn new(image: Image, data: Vec<u8>, options: BlockOptions) -> Self {
        PendingImage {
            image,
            data,
            options,
            resolution: None,
            rgb_working_space: None,
            display_function: None,
            color_filter_array: None,
            icc_profile: None,
            thumbnail: None,
            fits_keywords: Vec::new(),
            tables: Vec::new(),
        }
    }

    pub fn with_resolution(mut self, resolution: Resolution) -> Self {
        self.resolution = Some(resolution);
        self
    }

    pub fn with_rgb_working_space(mut self, space: RgbWorkingSpace) -> Self {
        self.rgb_working_space = Some(space);
        self
    }

    pub fn with_display_function(mut self, function: DisplayFunction) -> Self {
        self.display_function = Some(function);
        self
    }

    pub fn with_color_filter_array(mut self, cfa: ColorFilterArray) -> Self {
        self.color_filter_array = Some(cfa);
        self
    }

    /// Attach a raw ICC profile.
    ///
    /// The bytes are written as given but for one bit. The specification
    /// requires a profile to be stored "unaltered, except for the embedded
    /// profile flag, which must be set", and that flag "must be set to one to
    /// signify that the profile has been embedded in a file" -- a profile
    /// taken straight off disk normally has it clear, so writing it verbatim
    /// produces an embedded profile advertising that it is not embedded, and
    /// a colour-managed reader may substitute the display profile and shift
    /// every colour in the image.
    ///
    /// An ICC profile is defined as big-endian by its own specification, so
    /// the spec forbids a `byteOrder` attribute on this block and none is
    /// written.
    pub fn with_icc_profile(mut self, profile: Vec<u8>) -> Self {
        self.icc_profile = Some(profile);
        self
    }

    /// Attach a preview image.
    ///
    /// A thumbnail must be a two-dimensional 8- or 16-bit image, which is
    /// checked when the file is written rather than here, so a caller building
    /// one up can do it in any order.
    pub fn with_thumbnail(mut self, thumbnail: PendingThumbnail) -> Self {
        self.thumbnail = Some(thumbnail);
        self
    }

    /// Attach a table property to this image.
    pub fn with_table(mut self, table: Table) -> Self {
        self.tables.push(table);
        self
    }

    pub fn with_fits_keyword(
        mut self,
        name: impl Into<String>,
        value: impl Into<String>,
        comment: impl Into<String>,
    ) -> Self {
        self.fits_keywords.push(FitsKeyword {
            name: name.into(),
            value: value.into(),
            comment: comment.into(),
        });
        self
    }
}

impl PendingThumbnail {
    pub fn new(image: Image, data: Vec<u8>, options: BlockOptions) -> Self {
        PendingThumbnail { image, data, options }
    }
}

/// Builds a monolithic XISF file.
#[derive(Clone, Debug, Default)]
pub struct Writer {
    images: Vec<PendingImage>,
    /// Extra `<Property>` elements for the `<Metadata>` block.
    metadata: Vec<(String, String, String)>,
    creator: Option<String>,
    /// `XISF:CreationTime`, as an ISO 8601 instant. `None` means "now",
    /// resolved when the file is rendered.
    creation_time: Option<String>,
    /// Standalone `<Table>` elements, belonging to the unit rather than to
    /// any one image.
    tables: Vec<Table>,
}

impl Writer {
    pub fn new() -> Self {
        Self::default()
    }

    /// Name the software that produced the file. Written as
    /// `XISF:CreatorApplication`, which is the property the spec reserves.
    pub fn with_creator(mut self, creator: impl Into<String>) -> Self {
        self.creator = Some(creator.into());
        self
    }

    /// Set `XISF:CreationTime` rather than taking it from the clock.
    ///
    /// The spec requires the property, so it is always written; this exists
    /// because a timestamp makes output non-reproducible, and a caller
    /// rebuilding a file or comparing two runs needs to be able to pin it.
    /// The value is written as given, so it must be a valid ISO 8601 instant.
    pub fn with_creation_time(mut self, instant: impl Into<String>) -> Self {
        self.creation_time = Some(instant.into());
        self
    }

    /// Add a string property to the file's `<Metadata>`.
    ///
    /// The identifier must satisfy the format's grammar, since a property
    /// nothing can look up by name is not a property.
    pub fn add_metadata(&mut self, id: impl Into<String>, value: impl Into<String>) -> Result<()> {
        let id = id.into();
        check_property_id(&id)?;
        self.metadata.push((id, "String".into(), value.into()));
        Ok(())
    }

    /// Add a scalar property to the file's `<Metadata>`.
    ///
    /// A baseline encoder must "write properties of all 8-bit, 16-bit, 32-bit
    /// and 64-bit scalar types", and until this existed the only property this
    /// writer could emit was a string -- so a caller had no way to record an
    /// exposure time as a `Float32` or a gain as an `Int32` without writing
    /// the number out as text under a type that says it is text.
    ///
    /// The value is serialized as the specification's plain text for its type,
    /// and is checked against the declared type before it is accepted, so a
    /// value that does not fit is refused here rather than read back as a
    /// different number.
    pub fn add_scalar_property(
        &mut self,
        id: impl Into<String>,
        value: ScalarProperty,
    ) -> Result<()> {
        let id = id.into();
        check_property_id(&id)?;
        let (kind, text) = value.serialize();
        self.metadata.push((id, kind.into(), text));
        Ok(())
    }

    /// Add a table property describing the unit as a whole.
    pub fn add_table(&mut self, table: Table) -> Result<()> {
        check_table(&table)?;
        self.tables.push(table);
        Ok(())
    }

    /// Add an image, checking that its data matches the geometry it declares.
    pub fn add_image(&mut self, pending: PendingImage) -> Result<()> {
        // Revision 1: "The id attribute of an Image core element must be
        // unique within the XISF unit." An id is how a caller asks for one
        // image out of several, so a duplicate does not merely break a rule --
        // it makes the question "which image is `Light`?" unanswerable, and
        // the writer is the last place that can still refuse to pose it.
        if let Some(id) = &pending.image.id
            && self.images.iter().any(|existing| existing.image.id.as_ref() == Some(id))
        {
            return Err(err!(
                InvalidArgument,
                "two images share the id {id:?}, which must be unique within the unit"
            ));
        }

        // "The bounds attribute is required for floating point real images."
        // Without it a reader has no black and white point and must guess --
        // PixInsight assumes [0,1], a pipeline working in ADU assumes
        // [0,65535] -- so the pixels survive and every statistic taken from
        // them is wrong by a factor nothing reports.
        if pending.image.sample_format.requires_bounds() && pending.image.bounds.is_none() {
            return Err(err!(
                InvalidArgument,
                "a {} image must declare its bounds; there is no default \
                 representable range for floating point real pixel data",
                pending.image.sample_format.name()
            ));
        }

        if let Some(id) = &pending.image.id {
            check_image_id(id)?;
        }
        if let Some(uuid) = &pending.image.uuid {
            check_uuid(uuid)?;
        }

        let expected = pending
            .image
            .data_size()
            .ok_or_else(|| err!(InvalidArgument, "the image's geometry overflows"))?;
        if pending.data.len() as u64 != expected {
            return Err(err!(
                InvalidArgument,
                "the image declares {expected} bytes of pixel data but {} were given",
                pending.data.len()
            ));
        }
        // A thumbnail is a preview meant to be cheap to display, so the spec
        // restricts it to two dimensions and to 8- or 16-bit samples. Writing
        // one that breaks those rules produces a file readers may reject, and
        // the writer is the last place that can still say so usefully.
        if let Some(thumbnail) = &pending.thumbnail {
            let expected = thumbnail
                .image
                .data_size()
                .ok_or_else(|| err!(InvalidArgument, "the thumbnail's geometry overflows"))?;
            if thumbnail.data.len() as u64 != expected {
                return Err(err!(
                    InvalidArgument,
                    "the thumbnail declares {expected} bytes but {} were given",
                    thumbnail.data.len()
                ));
            }
            if thumbnail.image.dimensions.len() != 2 {
                return Err(err!(
                    InvalidArgument,
                    "a thumbnail must be two-dimensional, got {} dimension(s)",
                    thumbnail.image.dimensions.len()
                ));
            }
            if !matches!(
                thumbnail.image.sample_format,
                crate::image::SampleFormat::UInt8 | crate::image::SampleFormat::UInt16
            ) {
                return Err(err!(
                    InvalidArgument,
                    "a thumbnail must be UInt8 or UInt16, got {}",
                    thumbnail.image.sample_format.name()
                ));
            }
            // The spec forbids `bounds` on a thumbnail outright: its range is
            // always the full width of its integer type, so a bounds
            // attribute would be either redundant or a contradiction.
            if thumbnail.image.bounds.is_some() {
                return Err(err!(
                    InvalidArgument,
                    "a thumbnail must not declare bounds; its range is its sample format's"
                ));
            }
            if !matches!(
                thumbnail.image.color_space,
                crate::image::ColorSpace::Gray | crate::image::ColorSpace::Rgb
            ) {
                return Err(err!(
                    InvalidArgument,
                    "a thumbnail must be grayscale or RGB, got {}",
                    thumbnail.image.color_space.name()
                ));
            }
        }

        for keyword in &pending.fits_keywords {
            check_fits_name(&keyword.name)?;
        }
        for table in &pending.tables {
            check_table(table)?;
        }

        self.images.push(pending);
        Ok(())
    }

    /// Serialise the whole file.
    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        // Each block is compressed once, up front: the stored bytes decide
        // both the sizes in the header and the checksums, so doing it inside
        // the positioning loop would be wasted work and, worse, would let a
        // non-deterministic codec change sizes between rounds.
        let stored = self.prepare_blocks()?;

        // Fixed point on the header length; see the module comment.
        let mut assumed =
            self.render(&stored, Addressing::Attached { data_at: PREAMBLE_LEN })?.len();
        let header = loop {
            let header =
                self.render(&stored, Addressing::Attached { data_at: PREAMBLE_LEN + assumed })?;
            if header.len() == assumed {
                break header;
            }
            // Monotonic: a longer header only ever pushes positions outward.
            assumed = header.len();
        };

        let mut out = Vec::with_capacity(
            PREAMBLE_LEN
                + header.len()
                + stored.blocks.iter().map(|b| b.bytes.len()).sum::<usize>(),
        );
        out.extend_from_slice(SIGNATURE);
        out.extend_from_slice(
            &(u32::try_from(header.len()).map_err(|_| {
                err!(Unsupported, "the header is larger than the format's 32-bit length field")
            })?)
            .to_le_bytes(),
        );
        out.extend_from_slice(&[0; 4]);
        out.extend_from_slice(header.as_bytes());
        for block in &stored.blocks {
            out.extend_from_slice(&block.bytes);
        }
        Ok(out)
    }

    /// Serialise as a *distributed* unit: a header file and a blocks file.
    ///
    /// `blocks_file_name` is what the header will name, so it must be the
    /// name the blocks file is actually saved under, and the two must end up
    /// in the same directory. The reader resolves a relative locator beside
    /// the file that named it.
    ///
    /// Unlike the monolithic form this needs no fixed point: the header names
    /// blocks by identifier rather than by position, so its length does not
    /// feed back into its contents.
    pub fn to_distributed(&self, blocks_file_name: &str) -> Result<DistributedUnit> {
        if blocks_file_name.is_empty() || blocks_file_name.contains('/') {
            return Err(err!(
                InvalidArgument,
                "the blocks file name must be a plain file name, got {blocks_file_name:?}"
            ));
        }

        let stored = self.prepare_blocks()?;

        let blocks: Vec<crate::distributed::PendingBlock> = stored
            .blocks
            .iter()
            .enumerate()
            .map(|(index, block)| crate::distributed::PendingBlock {
                id: block_id(index),
                bytes: block.bytes.clone(),
                // The index element records the size before compression, and
                // zero for a block stored as it is.
                uncompressed_length: block
                    .compression
                    .as_ref()
                    .map(|compression| compression.uncompressed_size),
            })
            .collect();

        let header =
            self.render(&stored, Addressing::Distributed { blocks_file: blocks_file_name })?;
        Ok(DistributedUnit {
            header: header.into_bytes(),
            blocks: crate::distributed::write_blocks_file(&blocks)?,
            blocks_file_name: blocks_file_name.to_string(),
        })
    }

    /// Compress every block once, and record which belongs to which image.
    ///
    /// An image can own three blocks -- its pixels, an ICC profile and a
    /// thumbnail -- so blocks are no longer one per image and the mapping has
    /// to be kept rather than inferred from a position in the list.
    fn prepare_blocks(&self) -> Result<StoredBlocks> {
        let mut blocks = Vec::new();
        let mut owners = Vec::with_capacity(self.images.len());

        let mut push = |data: &[u8], options: &BlockOptions| -> Result<usize> {
            blocks.push(StoredBlock::prepare(data, options)?);
            Ok(blocks.len() - 1)
        };

        for pending in &self.images {
            // The order here is the order the blocks are written in, and the
            // positions are derived from it, so it must not drift from the
            // order used when the file is assembled.
            let data = push(&pending.data, &pending.options)?;
            let icc = match &pending.icc_profile {
                None => None,
                Some(profile) => {
                    Some(push(&with_embedded_profile_flag(profile)?, &BlockOptions::default())?)
                }
            };
            let thumbnail = match &pending.thumbnail {
                None => None,
                Some(thumb) => Some(push(&thumb.data, &thumb.options)?),
            };
            owners.push(ImageBlocks { data, icc, thumbnail });
        }
        Ok(StoredBlocks { blocks, owners })
    }

    /// Render the XML header, naming blocks as `addressing` says.
    fn render(&self, stored: &StoredBlocks, addressing: Addressing<'_>) -> Result<String> {
        let mut xml = String::from(r#"<?xml version="1.0" encoding="UTF-8"?>"#);
        xml.push_str(r#"<xisf version="1.0" xmlns="http://www.pixinsight.com/xisf" "#);
        xml.push_str(r#"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" "#);
        xml.push_str(
            r#"xsi:schemaLocation="http://www.pixinsight.com/xisf http://pixinsight.com/xisf/xisf-1.0.xsd">"#,
        );

        // Every block's position is settled before anything is emitted, so
        // the order elements are written in cannot drift from the order the
        // blocks are laid down in. Getting that wrong silently points an
        // element at another element's bytes.
        let base = match addressing {
            Addressing::Attached { data_at } => data_at,
            Addressing::Distributed { .. } => 0,
        };
        let mut positions = Vec::with_capacity(stored.blocks.len());
        let mut cursor = base;
        for block in &stored.blocks {
            positions.push(cursor);
            cursor += block.bytes.len();
        }

        // How one block is addressed, whichever form the unit takes.
        let locate = |index: usize| -> String {
            let block = &stored.blocks[index];
            match addressing {
                Addressing::Attached { .. } => {
                    format!("attachment:{}:{}", positions[index], block.bytes.len())
                }
                // `path(@header_dir/name):0xID`. The `@header_dir` token is
                // the only relative form the grammar defines -- a bare
                // `path(name)` is neither absolute nor documented, however
                // obvious its meaning -- and the identifier goes in
                // hexadecimal, as the spec recommends.
                Addressing::Distributed { blocks_file } => {
                    format!(
                        "path({HEADER_DIR_TOKEN}/{}):{:#x}",
                        escape_attr(blocks_file),
                        block_id(index)
                    )
                }
            }
        };

        for (pending, owned) in self.images.iter().zip(&stored.owners) {
            let block = &stored.blocks[owned.data];
            let image = &pending.image;
            let mut geometry: Vec<String> = image.dimensions.iter().map(u64::to_string).collect();
            geometry.push(image.channels.to_string());

            xml.push_str("<Image geometry=\"");
            xml.push_str(&geometry.join(":"));
            xml.push_str("\" sampleFormat=\"");
            xml.push_str(image.sample_format.name());
            xml.push_str("\" colorSpace=\"");
            xml.push_str(image.color_space.name());
            xml.push_str("\" pixelStorage=\"");
            xml.push_str(image.pixel_storage.name());
            xml.push('"');

            if let Some(bounds) = image.bounds {
                xml.push_str(&format!(" bounds=\"{}:{}\"", bounds.low, bounds.high));
            }
            if let Some(id) = &image.id {
                xml.push_str(&format!(" id=\"{}\"", escape_attr(id)));
            }
            if let Some(kind) = &image.image_type {
                xml.push_str(&format!(" imageType=\"{}\"", escape_attr(kind.name())));
            }
            if let Some(uuid) = &image.uuid {
                xml.push_str(&format!(" uuid=\"{}\"", escape_attr(uuid)));
            }
            if let Some(offset) = image.offset {
                xml.push_str(&format!(" offset=\"{offset}\""));
            }
            if let Some(orientation) = image.orientation {
                xml.push_str(&format!(" orientation=\"{}\"", orientation.to_attribute()));
            }
            push_block_attrs(&mut xml, block);

            xml.push_str(&format!(" location=\"{}\">", locate(owned.data)));

            // Ancillary elements are written as children of the image they
            // belong to. The spec also allows them at the root with a `uid`
            // and a `<Reference>`, which is how a file shares one element
            // between images; a writer that owns each element outright has
            // nothing to share, so the direct form is the honest one.
            for keyword in &pending.fits_keywords {
                xml.push_str(&format!(
                    "<FITSKeyword name=\"{}\" value=\"{}\" comment=\"{}\"/>",
                    escape_attr(&keyword.name),
                    escape_attr(&keyword.value),
                    escape_attr(&keyword.comment)
                ));
            }
            if let Some(resolution) = &pending.resolution {
                xml.push_str(&format!(
                    "<Resolution horizontal=\"{}\" vertical=\"{}\" unit=\"{}\"/>",
                    resolution.horizontal,
                    resolution.vertical,
                    resolution.unit.name()
                ));
            }
            if let Some(space) = &pending.rgb_working_space {
                // Revision 1: "Encoders shall compute luminance coefficients
                // in this way." They follow from the chromaticities and the
                // D50 reference white, so writing whatever a caller happened
                // to put in the struct would produce a header that contradicts
                // itself. A set of primaries with no solution is not a valid
                // working space, and is refused rather than written.
                let luminance =
                    RgbWorkingSpace::derive_luminance(space.x, space.y).ok_or_else(|| {
                        err!(
                            InvalidArgument,
                            "the RGB working space primaries x={:?} y={:?} are degenerate, \
                             so no luminance coefficients follow from them",
                            space.x,
                            space.y
                        )
                    })?;
                xml.push_str(&format!(
                    "<RGBWorkingSpace x=\"{}\" y=\"{}\" Y=\"{}\" gamma=\"{}\"",
                    join_numbers(&space.x),
                    join_numbers(&space.y),
                    join_numbers(&luminance),
                    match space.gamma {
                        Gamma::Srgb => "sRGB".to_string(),
                        Gamma::Exponent(exponent) => exponent.to_string(),
                    }
                ));
                if let Some(name) = &space.name {
                    xml.push_str(&format!(" name=\"{}\"", escape_attr(name)));
                }
                xml.push_str("/>");
            }
            if let Some(function) = &pending.display_function {
                xml.push_str(&format!(
                    "<DisplayFunction m=\"{}\" s=\"{}\" h=\"{}\" l=\"{}\" r=\"{}\"",
                    join_numbers(&function.midtones),
                    join_numbers(&function.shadows),
                    join_numbers(&function.highlights),
                    join_numbers(&function.low_range),
                    join_numbers(&function.high_range)
                ));
                if let Some(name) = &function.name {
                    xml.push_str(&format!(" name=\"{}\"", escape_attr(name)));
                }
                xml.push_str("/>");
            }
            if let Some(cfa) = &pending.color_filter_array {
                xml.push_str(&format!(
                    "<ColorFilterArray pattern=\"{}\" width=\"{}\" height=\"{}\"",
                    cfa.pattern_string(),
                    cfa.width,
                    cfa.height
                ));
                if let Some(name) = &cfa.name {
                    xml.push_str(&format!(" name=\"{}\"", escape_attr(name)));
                }
                xml.push_str("/>");
            }
            if let Some(index) = owned.icc {
                // No `byteOrder`: an ICC profile is big-endian by its own
                // specification, and the XISF spec forbids the attribute here.
                xml.push_str("<ICCProfile");
                push_block_attrs(&mut xml, &stored.blocks[index]);
                xml.push_str(&format!(" location=\"{}\"/>", locate(index)));
            }
            if let Some(index) = owned.thumbnail {
                let thumb = &pending.thumbnail.as_ref().expect("a thumbnail block has one").image;
                let mut geometry: Vec<String> =
                    thumb.dimensions.iter().map(u64::to_string).collect();
                geometry.push(thumb.channels.to_string());
                xml.push_str(&format!(
                    "<Thumbnail geometry=\"{}\" sampleFormat=\"{}\" colorSpace=\"{}\" \
                     pixelStorage=\"{}\"",
                    geometry.join(":"),
                    thumb.sample_format.name(),
                    thumb.color_space.name(),
                    // Dropping this was a silent corruption rather than an
                    // omission: "Other than its tag name, a Thumbnail core
                    // element is identical to an Image core element" apart
                    // from a short list of restrictions that does not include
                    // pixelStorage, and the default is Planar -- so a Normal
                    // thumbnail read back with its channels interleaved
                    // wrongly, with nothing reporting it.
                    thumb.pixel_storage.name()
                ));
                if let Some(id) = &thumb.id {
                    xml.push_str(&format!(" id=\"{}\"", escape_attr(id)));
                }
                if let Some(uuid) = &thumb.uuid {
                    xml.push_str(&format!(" uuid=\"{}\"", escape_attr(uuid)));
                }
                if let Some(kind) = &thumb.image_type {
                    xml.push_str(&format!(" imageType=\"{}\"", escape_attr(kind.name())));
                }
                if let Some(offset) = thumb.offset {
                    xml.push_str(&format!(" offset=\"{offset}\""));
                }
                if let Some(orientation) = thumb.orientation
                    && !orientation.is_identity()
                {
                    xml.push_str(&format!(" orientation=\"{}\"", orientation.to_attribute()));
                }
                push_block_attrs(&mut xml, &stored.blocks[index]);
                xml.push_str(&format!(" location=\"{}\"/>", locate(index)));
            }

            for table in &pending.tables {
                push_table(&mut xml, table);
            }

            xml.push_str("</Image>");
        }

        for table in &self.tables {
            push_table(&mut xml, table);
        }

        // `<Metadata>` is required by the spec, and it *must* carry both
        // `XISF:CreationTime` and `XISF:CreatorApplication`, so neither is
        // conditional on the caller having said anything.
        xml.push_str("<Metadata>");
        xml.push_str(&format!(
            "<Property id=\"XISF:CreationTime\" type=\"TimePoint\" value=\"{}\"/>",
            match &self.creation_time {
                Some(instant) => escape_attr(instant),
                None => escape_attr(&now_iso8601()),
            }
        ));
        // "If the XISF unit contains data blocks with checksums / compressed
        // data blocks, this property should be defined to enumerate the
        // applied hashing algorithms / compression codec(s)." They are derived
        // from what was actually written rather than from what the caller
        // asked for, so they cannot disagree with the blocks they describe.
        let mut algorithms: Vec<&str> = Vec::new();
        let mut codecs: Vec<&str> = Vec::new();
        for block in &stored.blocks {
            if let Some(checksum) = &block.checksum
                && !algorithms.contains(&checksum.algorithm.name())
            {
                algorithms.push(checksum.algorithm.name());
            }
            if let Some(compression) = &block.compression
                && !codecs.contains(&compression.codec.name())
            {
                codecs.push(compression.codec.name());
            }
        }
        if !algorithms.is_empty() {
            xml.push_str(&format!(
                "<Property id=\"XISF:ChecksumAlgorithms\" type=\"String\">{}</Property>",
                escape_text(&algorithms.join(","))
            ));
        }
        if !codecs.is_empty() {
            xml.push_str(&format!(
                "<Property id=\"XISF:CompressionCodecs\" type=\"String\">{}</Property>",
                escape_text(&codecs.join(","))
            ));
        }

        for (id, kind, value) in &self.metadata {
            // A String property "shall not have a value attribute, and must
            // serialize the property value either directly in its character
            // data contents, or as an XISF data block"; every other scalar
            // carries its value in the attribute. Writing a scalar as
            // character data, or a string as an attribute, is the wrong shape
            // for both.
            if kind == "String" {
                xml.push_str(&format!(
                    "<Property id=\"{}\" type=\"String\">{}</Property>",
                    escape_attr(id),
                    escape_text(value)
                ));
            } else {
                xml.push_str(&format!(
                    "<Property id=\"{}\" type=\"{}\" value=\"{}\"/>",
                    escape_attr(id),
                    escape_attr(kind),
                    escape_attr(value)
                ));
            }
        }
        xml.push_str(&format!(
            "<Property id=\"XISF:CreatorApplication\" type=\"String\">{}</Property>",
            escape_text(self.creator.as_deref().unwrap_or("xisf-rs"))
        ));
        xml.push_str("</Metadata>");

        xml.push_str("</xisf>");
        Ok(xml)
    }
}

/// The current instant as `YYYY-MM-DDThh:mm:ssZ`, which is what a
/// `TimePoint` property holds.
///
/// Written out rather than taken from a date library: this is the only date
/// arithmetic in the workspace, and a dependency for it would be carried by
/// every user of the crate for one line of output. A clock before the epoch
/// is not something to fail a write over, so it reads as the epoch itself.
fn now_iso8601() -> String {
    let seconds = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |elapsed| elapsed.as_secs());
    iso8601_from_unix(seconds)
}

/// Format a Unix timestamp, in seconds, as an ISO 8601 instant in UTC.
fn iso8601_from_unix(seconds: u64) -> String {
    let days = (seconds / 86_400) as i64;
    let time = seconds % 86_400;
    let (year, month, day) = civil_from_days(days);
    format!(
        "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
        time / 3600,
        (time % 3600) / 60,
        time % 60
    )
}

/// The civil date `days` after 1970-01-01, by Howard Hinnant's algorithm.
///
/// It works by shifting the epoch to March 1st, which puts the leap day at
/// the end of the year and so removes February's irregular length from every
/// other calculation.
fn civil_from_days(days: i64) -> (i64, u32, u32) {
    let shifted = days + 719_468;
    let era = shifted.div_euclid(146_097);
    let day_of_era = shifted.rem_euclid(146_097);
    let year_of_era =
        (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
    let year = year_of_era + era * 400;
    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
    let shifted_month = (5 * day_of_year + 2) / 153;
    let day = (day_of_year - (153 * shifted_month + 2) / 5 + 1) as u32;
    let month = if shifted_month < 10 { shifted_month + 3 } else { shifted_month - 9 } as u32;
    (if month <= 2 { year + 1 } else { year }, month, day)
}

/// Write the `compression` and `checksum` attributes a block needs, if any.
fn push_block_attrs(xml: &mut String, block: &StoredBlock) {
    if let Some(compression) = &block.compression {
        xml.push_str(&format!(" compression=\"{}\"", compression_attr(compression)));
    }
    if let Some(checksum) = &block.checksum {
        xml.push_str(&format!(
            " checksum=\"{}:{}\"",
            checksum.algorithm.name(),
            digest_hex(&checksum.digest)
        ));
    }
}

/// The largest input a codec will take in one call.
///
/// The specification's answer to a larger block is the `subblocks` attribute,
/// which divides it into several independent streams. This writer emits one
/// stream per block, so these are the sizes past which it has to decline.
fn codec_input_limit(codec: Codec2) -> u64 {
    match codec {
        // zlib's own interface takes a 32-bit length.
        Codec2::Zlib => u64::from(u32::MAX),
        // LZ4_MAX_INPUT_SIZE, which every LZ4 implementation shares.
        Codec2::Lz4 => 0x7E00_0000,
        // Zstandard frames carry a 64-bit content size and have no practical
        // input limit of their own, so the bound is what one allocation can
        // hold rather than anything the format imposes.
        Codec2::Zstd => u64::MAX,
    }
}

/// Check a table before it is written.
///
/// Cells are positional: which field a cell belongs to is decided by nothing
/// but its place in the row. A row of the wrong length therefore has no
/// reading at all, and writing one produces a file whose every value after
/// the gap belongs to the wrong column.
fn check_table(table: &Table) -> Result<()> {
    check_property_id(&table.id)?;
    if table.structure.fields.is_empty() {
        return Err(err!(InvalidArgument, "table {:?} has no fields", table.id));
    }
    for field in &table.structure.fields {
        check_property_id(&field.id)?;
    }
    for (n, row) in table.rows.iter().enumerate() {
        if row.len() != table.structure.fields.len() {
            return Err(err!(
                InvalidArgument,
                "table {:?} row {n} has {} cells but its structure declares {} fields",
                table.id,
                row.len(),
                table.structure.fields.len()
            ));
        }
        for cell in row {
            // A cell whose value lives in a data block would need a block
            // allocated for it, which this writer does not do. Saying so
            // beats writing a `<Cell>` with no value in it.
            if cell.data.location.is_some() {
                return Err(err!(
                    Unsupported,
                    "table {:?} has a cell stored in a data block, which cannot be written yet",
                    table.id
                ));
            }
        }
    }
    Ok(())
}

/// Serialise one `<Table>` element and everything under it.
fn push_table(xml: &mut String, table: &Table) {
    xml.push_str(&format!("<Table id=\"{}\"", escape_attr(&table.id)));
    if let Some(caption) = &table.caption {
        xml.push_str(&format!(" caption=\"{}\"", escape_attr(caption)));
    }
    if let Some(comment) = &table.comment {
        xml.push_str(&format!(" comment=\"{}\"", escape_attr(comment)));
    }
    // `rows` and `columns` are optional but must agree with the data when
    // present, which is easy here and saves a reader from counting.
    xml.push_str(&format!(
        " rows=\"{}\" columns=\"{}\">",
        table.rows.len(),
        table.structure.fields.len()
    ));

    // The structure is written inline and before the rows, as the spec asks:
    // it wants sequential parsers to know the shape before the data arrives.
    xml.push_str("<Structure>");
    for field in &table.structure.fields {
        xml.push_str(&format!(
            "<Field id=\"{}\" type=\"{}\"",
            escape_attr(&field.id),
            escape_attr(&field.kind.name())
        ));
        if let Some(format) = &field.format {
            xml.push_str(&format!(" format=\"{}\"", escape_attr(format)));
        }
        if let Some(header) = &field.header {
            xml.push_str(&format!(" header=\"{}\"", escape_attr(header)));
        }
        xml.push_str("/>");
    }
    xml.push_str("</Structure>");

    for row in &table.rows {
        xml.push_str("<Row>");
        for cell in row {
            match (&cell.value, &cell.data.text) {
                (Some(value), _) => {
                    xml.push_str(&format!("<Cell value=\"{}\"/>", escape_attr(value)));
                }
                (None, Some(text)) => {
                    xml.push_str(&format!("<Cell>{}</Cell>", escape_text(text)));
                }
                // Not `<Cell value=""/>`. A String field's cell "shall not
                // have a value attribute", and Revision 1 amended the
                // specification's own table examples for exactly this -- so
                // emitting one produced the construct the revision was written
                // to forbid. The spec's corrected example uses the empty
                // element, which is valid for every field type.
                (None, None) => xml.push_str("<Cell/>"),
            }
        }
        xml.push_str("</Row>");
    }
    xml.push_str("</Table>");
}

/// Check a property identifier against the format's grammar.
///
/// An identifier is one or more colon-separated segments, each starting with
/// a letter or underscore and continuing with letters, digits or underscores.
/// The colons group properties into namespaces, which is why `XISF:` names
/// are reserved and why an identifier is the only handle a reader has on a
/// property.
///
/// A note for whoever checks this against the document: the regular
/// expression the specification prints,
/// `[_a-zA-Z][_a-zA-Z0-9]*(:([_a-zA-Z][_a-zA-Z0-9])+)*`, is wrong. Its
/// namespace group matches *pairs* of characters -- a `*` is missing inside
/// it -- so it rejects `foo:bar:Foo2_Bar3`, which the same section gives as a
/// valid example three lines later. The evident intent is implemented here,
/// since a grammar that refuses its own examples cannot be the one meant.
fn check_property_id(id: &str) -> Result<()> {
    let valid = !id.is_empty()
        && id.split(':').all(|segment| {
            let mut chars = segment.chars();
            chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
                && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
        });
    if !valid {
        return Err(err!(
            InvalidArgument,
            "{id:?} is not a valid property identifier: one or more colon-separated \
             segments, each beginning with a letter or underscore"
        ));
    }
    Ok(())
}

/// Check a FITS keyword name against the FITS 3.0 grammar the spec cites.
///
/// "The keyword name shall be a left justified, 8-character, space-filled,
/// ASCII string with no embedded spaces", using digits, upper case `A`-`Z`,
/// underscore and hyphen only. The point of a `FITSKeyword` element is to be
/// a compatibility layer with FITS, so a name FITS itself would reject makes
/// the element useless for the one job it has -- and the file is checked
/// where it is built rather than by whoever eventually reads it.
fn check_fits_name(name: &str) -> Result<()> {
    if name.len() > 8 {
        return Err(err!(
            InvalidArgument,
            "the FITS keyword {name:?} is {} characters; the limit is 8",
            name.len()
        ));
    }
    if let Some(bad) = name
        .chars()
        .find(|c| !(c.is_ascii_digit() || c.is_ascii_uppercase() || *c == '_' || *c == '-'))
    {
        return Err(err!(
            InvalidArgument,
            "the FITS keyword {name:?} contains {bad:?}; only A-Z, 0-9, underscore and \
             hyphen are permitted"
        ));
    }
    Ok(())
}

/// Colon-separated numbers, the form every multi-valued XISF attribute uses.
fn join_numbers(values: &[f64]) -> String {
    values.iter().map(f64::to_string).collect::<Vec<_>>().join(":")
}

/// Every block in a unit, and which image each one belongs to.
struct StoredBlocks {
    /// In the order they are written, which is what fixes their positions.
    blocks: Vec<StoredBlock>,
    /// One entry per image, in the order the images were added.
    owners: Vec<ImageBlocks>,
}

/// Indices into [`StoredBlocks::blocks`] for one image.
struct ImageBlocks {
    data: usize,
    icc: Option<usize>,
    thumbnail: Option<usize>,
}

/// The identifier the `n`th block is given in a data blocks file.
///
/// One-based: zero is a legal identifier, but it is also what an uninitialised
/// field reads as, so starting at one makes a mistake visible.
fn block_id(index: usize) -> u64 {
    index as u64 + 1
}

/// A block after compression, ready to be addressed and written.
struct StoredBlock {
    bytes: Vec<u8>,
    compression: Option<Compression>,
    checksum: Option<crate::block::Checksum>,
}

impl StoredBlock {
    fn prepare(data: &[u8], options: &BlockOptions) -> Result<Self> {
        let (bytes, compression) = match &options.compression {
            None => (data.to_vec(), None),
            Some(request) => {
                let uncompressed_size = data.len() as u64;

                // Shuffle first, then compress: that is the order the spec
                // fixes, and the reader undoes it the other way round.
                // An item size of one shuffles nothing, and the spec does not
                // allow `+sh:...:1` as a stored form. Rather than making every
                // caller special-case eight-bit data -- the natural thing to
                // pass is the sample width, which is 1 for UInt8 -- it is
                // treated as a request for no shuffling.
                let item_size = request.shuffle_item_size.filter(|item| *item > 1);
                let staged = match item_size {
                    None => data.to_vec(),
                    Some(item) => {
                        let item = usize::try_from(item)
                            .map_err(|_| err!(InvalidArgument, "shuffle item size is unusable"))?;
                        codec::shuffle(data, item)
                    }
                };

                // Codecs have input limits, and past them a block must be
                // split into subblocks with a `subblocks` attribute saying
                // how. This writer does not split, so it refuses rather than
                // handing a codec more than it can take: the alternative is
                // a file that looks written and cannot be read back.
                let limit = codec_input_limit(request.codec);
                if staged.len() as u64 > limit {
                    return Err(err!(
                        Unsupported,
                        "a {}-byte block exceeds the {} input limit of {limit} bytes; \
                         it would have to be split into compression subblocks, which this \
                         writer does not do",
                        staged.len(),
                        request.codec.as_codec().name()
                    ));
                }

                let compressed = compress(&staged, request.codec)?;

                // Compression that makes a block bigger is not worth writing:
                // the file grows and every reader pays to undo it. Storing it
                // plain is always legal, since `compression` is optional.
                if compressed.len() >= data.len() {
                    (data.to_vec(), None)
                } else {
                    (
                        compressed,
                        Some(Compression {
                            subblocks: Vec::new(),
                            codec: request.codec.as_codec(),
                            uncompressed_size,
                            shuffle_item_size: item_size,
                        }),
                    )
                }
            }
        };

        // The checksum covers the block as stored, so it is taken after
        // compression, matching what a reader can verify without decoding.
        let checksum = match options.checksum {
            None => None,
            Some(algorithm) => Some(checksum_of(&bytes, algorithm)?),
        };

        Ok(StoredBlock { bytes, compression, checksum })
    }
}

// As `codec::decompress`: with no codec feature enabled every arm below is
// compiled out, leaving `data` unread. That is right for such a build.
#[cfg_attr(not(any(feature = "zlib", feature = "lz4")), allow(unused_variables))]
fn compress(data: &[u8], codec: Codec2) -> Result<Vec<u8>> {
    match codec {
        #[cfg(feature = "zlib")]
        Codec2::Zlib => {
            use std::io::Write;
            let mut encoder =
                flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
            encoder.write_all(data).map_err(|e| err!(Compression, "zlib: {e}"))?;
            encoder.finish().map_err(|e| err!(Compression, "zlib: {e}"))
        }
        #[cfg(feature = "lz4")]
        Codec2::Lz4 => Ok(lz4_flex::block::compress(data)),
        // Level 3 is `zrip`'s DFast strategy: the middle of the -8..4 range it
        // implements, and a ratio comparable to zlib's default at a good deal
        // less time. Revision 1 stores Zstandard as one frame per subblock,
        // and this writer emits one stream per block, so one frame is right.
        Codec2::Zstd => zrip::compress(data, 3).map_err(|e| err!(Compression, "zstd: {e}")),
        #[allow(unreachable_patterns)]
        other => Err(err!(Unsupported, "cannot write {:?} blocks in this build", other)),
    }
}

/// Check an image identifier against the grammar the specification gives.
///
/// "image-id shall be a sequence of ASCII characters satisfying the following
/// regular expression: `[_a-zA-Z][_a-zA-Z0-9]*`". Property identifiers were
/// already checked; images were not, so the writer could emit a header the
/// schema rejects.
fn check_image_id(id: &str) -> Result<()> {
    let mut chars = id.chars();
    let valid = match chars.next() {
        Some(first) if first == '_' || first.is_ascii_alphabetic() => {
            chars.all(|c| c == '_' || c.is_ascii_alphanumeric())
        }
        _ => false,
    };
    if !valid {
        return Err(err!(
            InvalidArgument,
            "{id:?} is not a valid image identifier; it must match [_a-zA-Z][_a-zA-Z0-9]*"
        ));
    }
    Ok(())
}

/// Check a UUID against the canonical form, and that it is version 4.
///
/// "uuid must be a plain text representation of a Universally Unique
/// Identifier (UUID) in canonical form. Version 4 UUIDs must be used" --
/// Revision 1 tightened the generator requirements and replaced the obsolete
/// RFC 4122 reference with RFC 9562.
fn check_uuid(uuid: &str) -> Result<()> {
    let groups: Vec<&str> = uuid.split('-').collect();
    let shaped = groups.len() == 5
        && [8usize, 4, 4, 4, 12].iter().zip(&groups).all(|(want, group)| {
            group.len() == *want && group.chars().all(|c| c.is_ascii_hexdigit())
        });
    if !shaped {
        return Err(err!(
            InvalidArgument,
            "{uuid:?} is not a UUID in canonical 8-4-4-4-12 hexadecimal form"
        ));
    }
    // The version is the first character of the third group.
    if !groups[2].starts_with('4') {
        return Err(err!(
            InvalidArgument,
            "{uuid:?} is not a version 4 UUID, which the specification requires"
        ));
    }
    Ok(())
}

/// A scalar property value, with the XISF type it is written as.
///
/// The set is the one a baseline encoder is required to write -- "properties
/// of all 8-bit, 16-bit, 32-bit and 64-bit scalar types" -- plus Boolean,
/// which costs nothing to include and is otherwise unwritable.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum ScalarProperty {
    Boolean(bool),
    Int8(i8),
    UInt8(u8),
    Int16(i16),
    UInt16(u16),
    Int32(i32),
    UInt32(u32),
    Int64(i64),
    UInt64(u64),
    Float32(f32),
    Float64(f64),
}

impl ScalarProperty {
    /// The XISF type name and the plain text serialization of the value.
    fn serialize(self) -> (&'static str, String) {
        match self {
            // "A serialization of a Boolean value as plain text shall be one
            // of the words true and false."
            ScalarProperty::Boolean(v) => ("Boolean", v.to_string()),
            ScalarProperty::Int8(v) => ("Int8", v.to_string()),
            ScalarProperty::UInt8(v) => ("UInt8", v.to_string()),
            ScalarProperty::Int16(v) => ("Int16", v.to_string()),
            ScalarProperty::UInt16(v) => ("UInt16", v.to_string()),
            ScalarProperty::Int32(v) => ("Int32", v.to_string()),
            ScalarProperty::UInt32(v) => ("UInt32", v.to_string()),
            ScalarProperty::Int64(v) => ("Int64", v.to_string()),
            ScalarProperty::UInt64(v) => ("UInt64", v.to_string()),
            // Rust prints `NaN`, `inf` and `-inf`, all of which the
            // specification names as valid serializations of the non-finite
            // values.
            ScalarProperty::Float32(v) => ("Float32", v.to_string()),
            ScalarProperty::Float64(v) => ("Float64", v.to_string()),
        }
    }
}

/// A copy of an ICC profile with its embedded profile flag set.
///
/// The one alteration the specification permits: profiles "must store ICC
/// profile structures unaltered, except for the embedded profile flag", which
/// is bit 0 of the profile flags field -- a big-endian `u32` at byte offset 44
/// of the 128-byte profile header, per section 7.2.11 of the ICC
/// specification.
///
/// Everything else is copied byte for byte. A buffer too short to hold a
/// profile header is refused rather than written: it is not a profile, and
/// silently storing it would put something that is not an ICC profile in an
/// element that says it is one.
fn with_embedded_profile_flag(profile: &[u8]) -> Result<Vec<u8>> {
    /// The fixed size of an ICC profile header.
    const HEADER_LEN: usize = 128;
    /// Byte offset of the profile flags field within that header.
    const FLAGS_AT: usize = 44;
    /// Bit 0 of the flags field: "the profile is embedded in a file".
    const EMBEDDED: u32 = 1;

    if profile.len() < HEADER_LEN {
        return Err(err!(
            InvalidArgument,
            "an ICC profile needs at least {HEADER_LEN} bytes of header, this has {}",
            profile.len()
        ));
    }

    let mut out = profile.to_vec();
    let flags = u32::from_be_bytes(
        out[FLAGS_AT..FLAGS_AT + 4].try_into().expect("four bytes inside the header"),
    );
    out[FLAGS_AT..FLAGS_AT + 4].copy_from_slice(&(flags | EMBEDDED).to_be_bytes());
    Ok(out)
}

/// Render a `compression` attribute.
fn compression_attr(compression: &Compression) -> String {
    match compression.shuffle_item_size {
        None => format!("{}:{}", compression.codec.name(), compression.uncompressed_size),
        Some(item) => {
            format!("{}+sh:{}:{}", compression.codec.name(), compression.uncompressed_size, item)
        }
    }
}

/// Escape text for an attribute value.
fn escape_attr(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for c in text.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&apos;"),
            _ => out.push(c),
        }
    }
    out
}

/// Escape character data. Quotes need no escaping here, but `]]>` would end a
/// CDATA section, so `>` is escaped along with the two that must be.
fn escape_text(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for c in text.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            _ => out.push(c),
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Reader;
    use crate::image::{ColorSpace, PixelStorage, SampleFormat};

    fn image(width: u64, height: u64, channels: u64, format: SampleFormat) -> Image {
        Image {
            dimensions: vec![width, height],
            channels,
            sample_format: format,
            color_space: if channels >= 3 { ColorSpace::Rgb } else { ColorSpace::Gray },
            pixel_storage: PixelStorage::Planar,
            bounds: format
                .requires_bounds()
                .then_some(crate::image::Bounds { low: 0.0, high: 1.0 }),
            id: None,
            uuid: None,
            image_type: None,
            offset: None,
            orientation: None,
        }
    }

    fn sample(len: usize) -> Vec<u8> {
        (0..len).map(|i| (i * 31 + 7) as u8).collect()
    }

    fn round_trip(options: BlockOptions, format: SampleFormat) -> Vec<u8> {
        let image = image(9, 7, 1, format);
        let data = sample(image.data_size().unwrap() as usize);

        let mut writer = Writer::new().with_creator("xisf-rs tests");
        writer.add_image(PendingImage::new(image, data.clone(), options)).expect("add_image");
        let bytes = writer.to_bytes().expect("to_bytes");

        let reader = Reader::from_bytes(bytes).expect("read back");
        let written = reader.header().images()[0];
        let read = reader.block(&written.data).expect("block").to_vec();
        assert_eq!(read, data, "the pixels changed on the way through");
        reader.bytes().to_vec()
    }

    #[test]
    fn writes_a_file_that_reads_back() {
        round_trip(BlockOptions::default(), SampleFormat::UInt8);
    }

    /// Only over what this build can actually write, so the matrix stays
    /// honest under `--no-default-features` rather than asserting that an
    /// absent codec works.
    fn writable_compressions() -> Vec<Option<CompressionRequest>> {
        // Zstandard is never absent: Revision 1 makes it standard and this
        // crate compiles it in unconditionally.
        let mut out = vec![
            None,
            Some(CompressionRequest { codec: Codec2::Zstd, shuffle_item_size: None }),
            Some(CompressionRequest { codec: Codec2::Zstd, shuffle_item_size: Some(4) }),
        ];
        if cfg!(feature = "zlib") {
            out.push(Some(CompressionRequest { codec: Codec2::Zlib, shuffle_item_size: None }));
            out.push(Some(CompressionRequest { codec: Codec2::Zlib, shuffle_item_size: Some(4) }));
        }
        if cfg!(feature = "lz4") {
            out.push(Some(CompressionRequest { codec: Codec2::Lz4, shuffle_item_size: None }));
            out.push(Some(CompressionRequest { codec: Codec2::Lz4, shuffle_item_size: Some(2) }));
        }
        out
    }

    fn writable_checksums() -> Vec<Option<ChecksumAlgorithm>> {
        vec![None, Some(ChecksumAlgorithm::Sha256)]
    }

    #[test]
    fn every_option_combination_round_trips() {
        for format in [SampleFormat::UInt8, SampleFormat::UInt16, SampleFormat::Float32] {
            for compression in writable_compressions() {
                for checksum in writable_checksums() {
                    round_trip(BlockOptions { compression, checksum }, format);
                }
            }
        }
    }

    /// The positions in the header must land exactly on the bytes, with no
    /// gap and no overlap. This is the fixed point the module comment
    /// describes, and it is the thing most likely to be off by a few.
    #[test]
    fn block_positions_are_exact_and_contiguous() {
        let mut writer = Writer::new();
        for channels in [1u64, 3, 1] {
            let image = image(11, 13, channels, SampleFormat::UInt16);
            let data = sample(image.data_size().unwrap() as usize);
            writer.add_image(PendingImage::new(image, data, BlockOptions::default())).unwrap();
        }
        let bytes = writer.to_bytes().unwrap();
        let reader = Reader::from_bytes(bytes.clone()).unwrap();

        let mut expected = crate::layout::scan(&bytes).unwrap().data_start() as u64;
        for element in reader.header().images() {
            let Some(crate::block::Location::Attachment { position, size }) = element.data.location
            else {
                panic!("expected an attachment");
            };
            assert_eq!(position, expected, "a block did not begin where the last one ended");
            expected += size;
        }
        assert_eq!(expected as usize, bytes.len(), "the file has trailing bytes");
    }

    #[cfg(feature = "zlib")]
    #[test]
    fn checksums_written_are_checksums_that_verify() {
        let image = image(8, 8, 1, SampleFormat::UInt16);
        let data = sample(image.data_size().unwrap() as usize);
        let mut writer = Writer::new();
        writer
            .add_image(PendingImage::new(
                image,
                data,
                BlockOptions {
                    compression: Some(CompressionRequest {
                        codec: Codec2::Zlib,
                        shuffle_item_size: Some(2),
                    }),
                    checksum: Some(ChecksumAlgorithm::Sha512),
                },
            ))
            .unwrap();

        let reader = Reader::from_bytes(writer.to_bytes().unwrap()).unwrap();
        let written = reader.header().images()[0];
        assert_eq!(
            reader.verify(&written.data).unwrap(),
            crate::ChecksumStatus::Valid,
            "a checksum we wrote ourselves did not verify"
        );
    }

    /// Compression that makes a block larger is dropped, since storing it
    /// plain is legal and strictly better.
    #[cfg(feature = "zlib")]
    #[test]
    fn incompressible_data_is_stored_plain() {
        let image = image(4, 4, 1, SampleFormat::UInt8);
        // Bytes with no structure to exploit.
        let data: Vec<u8> = (0..16u32).map(|i| (i.wrapping_mul(2654435761) >> 24) as u8).collect();

        let mut writer = Writer::new();
        writer
            .add_image(PendingImage::new(
                image,
                data,
                BlockOptions {
                    compression: Some(CompressionRequest {
                        codec: Codec2::Zlib,
                        shuffle_item_size: None,
                    }),
                    checksum: None,
                },
            ))
            .unwrap();

        let reader = Reader::from_bytes(writer.to_bytes().unwrap()).unwrap();
        assert!(
            reader.header().images()[0].data.compression.is_none(),
            "compression that did not help should not have been recorded"
        );
    }

    #[test]
    fn data_that_does_not_match_the_geometry_is_refused() {
        let mut writer = Writer::new();
        let err = writer
            .add_image(PendingImage::new(
                image(10, 10, 1, SampleFormat::UInt16),
                vec![0; 3],
                BlockOptions::default(),
            ))
            .unwrap_err();
        assert_eq!(err.kind(), crate::ErrorKind::InvalidArgument);
    }

    #[test]
    fn special_characters_in_metadata_are_escaped() {
        let mut writer = Writer::new();
        writer.add_metadata("Test:Value", r#"a & b < c > d " e ' f"#).expect("id");
        writer
            .add_image(PendingImage::new(
                image(2, 2, 1, SampleFormat::UInt8),
                sample(4),
                BlockOptions::default(),
            ))
            .unwrap();

        // The proof is that it parses at all: unescaped `&` or `<` in
        // character data is not well-formed XML.
        let reader = Reader::from_bytes(writer.to_bytes().unwrap()).unwrap();
        let property = reader
            .header()
            .root
            .descendants()
            .into_iter()
            .find(|e| e.attr("id") == Some("Test:Value"))
            .expect("the property survived");
        assert_eq!(property.data.text.as_deref(), Some(r#"a & b < c > d " e ' f"#));
    }
}

#[cfg(test)]
mod time_tests {
    use super::iso8601_from_unix;

    /// Dates are the classic place for an off-by-one that only shows up on a
    /// leap day or a century boundary, so the cases are chosen to hit those
    /// rather than to sample a comfortable middle.
    #[test]
    fn unix_timestamps_format_as_iso8601() {
        for (seconds, expected) in [
            (0, "1970-01-01T00:00:00Z"),
            (86_399, "1970-01-01T23:59:59Z"),
            (86_400, "1970-01-02T00:00:00Z"),
            (68_169_600, "1972-02-29T00:00:00Z"),  // a leap day
            (951_782_400, "2000-02-29T00:00:00Z"), // 2000 is a leap year
            (4_107_456_000, "2100-02-28T00:00:00Z"), // 2100 is not a leap year,
            (4_107_542_400, "2100-03-01T00:00:00Z"), // so the day after is March
            (1_418_128_695, "2014-12-09T12:38:15Z"), // the spec's own example
        ] {
            assert_eq!(iso8601_from_unix(seconds), expected, "for {seconds}");
        }
    }
}