Skip to main content

xisf_core/
writer.rs

1//! Writing monolithic XISF files.
2//!
3//! # The positioning problem
4//!
5//! An attached block is addressed by `location="attachment:position:size"`,
6//! where the position is an *absolute* file offset. But the header sits before
7//! the blocks, so a block's position depends on how long the header is -- and
8//! the header's length depends on how many digits those positions take. A
9//! naive encoder either leaves a gap or writes a position that is wrong by the
10//! width of a number.
11//!
12//! Both PixInsight and libXISF place the first block immediately after the
13//! header with no padding, so the addressing here does the same, by iterating
14//! to a fixed point: render the header assuming a length, see what length it
15//! actually came out, and render again if it changed. It converges because a
16//! longer header can only push positions further out, which can only add
17//! digits, and adding digits only lengthens the header -- a monotonic climb
18//! that stops as soon as no number gains a digit. In practice that is one or
19//! two rounds.
20
21use crate::block::{ChecksumAlgorithm, Codec, Compression, HEADER_DIR_TOKEN};
22use crate::codec;
23use crate::err;
24use crate::error::Result;
25use crate::image::{ColorFilterArray, DisplayFunction, Gamma, Image, Resolution, RgbWorkingSpace};
26use crate::layout::{PREAMBLE_LEN, SIGNATURE};
27use crate::reader::{checksum_of, digest_hex};
28use crate::table::Table;
29
30/// How a block should be stored.
31#[derive(Clone, Debug, Default)]
32pub struct BlockOptions {
33    /// Codec and shuffling to apply, or `None` to store the bytes as they are.
34    pub compression: Option<CompressionRequest>,
35    /// Hash to record, or `None` for no checksum.
36    pub checksum: Option<ChecksumAlgorithm>,
37}
38
39/// A request to compress, before the compressed size is known.
40#[derive(Clone, Copy, PartialEq, Eq, Debug)]
41pub struct CompressionRequest {
42    pub codec: Codec2,
43    /// Byte-shuffle in items of this width first. `None` for no shuffling.
44    ///
45    /// Shuffling only helps when the item width matches the data's element
46    /// size, which is why this is chosen by the caller rather than guessed.
47    pub shuffle_item_size: Option<u64>,
48}
49
50/// The codecs this crate can *write*.
51///
52/// Narrower than [`Codec`], deliberately: [`Codec`] also names LZ4_HC, which
53/// is an encoder setting rather than a stream format and which this writer
54/// does not offer, and the codecs a future file might use that this build
55/// cannot produce. A separate type makes that a compile-time fact rather than
56/// a runtime surprise.
57#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
58pub enum Codec2 {
59    /// Zstandard, which Revision 1 makes the recommended codec. It is the
60    /// default here for that reason.
61    #[default]
62    Zstd,
63    Zlib,
64    Lz4,
65}
66
67impl Codec2 {
68    fn as_codec(self) -> Codec {
69        match self {
70            Codec2::Zstd => Codec::Zstd,
71            Codec2::Zlib => Codec::Zlib,
72            Codec2::Lz4 => Codec::Lz4,
73        }
74    }
75}
76
77/// How the header names its blocks.
78///
79/// The two XISF forms differ in exactly this and nothing else, so the header
80/// is rendered once and told how to address rather than written twice.
81#[derive(Clone, Copy, Debug)]
82enum Addressing<'a> {
83    /// Monolithic: `attachment:position:size`, an absolute offset into the
84    /// same file. Needs the position the data begins at, which is what makes
85    /// the fixed-point loop necessary.
86    Attached { data_at: usize },
87    /// Distributed: `path(name.xisb):0xID`, naming a block in a separate data
88    /// blocks file by its index identifier. No positions appear in the
89    /// header, so nothing has to converge.
90    Distributed { blocks_file: &'a str },
91}
92
93/// A distributed unit: an XISF header file and the data blocks file it names.
94#[derive(Clone, Debug)]
95pub struct DistributedUnit {
96    /// The `.xish` header file's contents: the XML header and nothing else.
97    pub header: Vec<u8>,
98    /// The `.xisb` data blocks file's contents.
99    pub blocks: Vec<u8>,
100    /// The blocks file's name, as the header refers to it.
101    pub blocks_file_name: String,
102}
103
104/// An image to write, with its pixel data and whatever is attached to it.
105///
106/// The ancillary elements are what a reader loses if a writer cannot produce
107/// them: a read-modify-write cycle through a writer that only knows about
108/// pixels drops the colour profile, the preview and the mosaic pattern
109/// without saying so.
110#[derive(Clone, Debug)]
111pub struct PendingImage {
112    pub image: Image,
113    pub data: Vec<u8>,
114    pub options: BlockOptions,
115    /// Pixels per unit of length.
116    pub resolution: Option<Resolution>,
117    /// The colour space the pixel values are expressed in.
118    pub rgb_working_space: Option<RgbWorkingSpace>,
119    /// How the image should be displayed, which is not how it is stored.
120    pub display_function: Option<DisplayFunction>,
121    /// The mosaic pattern, for an image straight off a colour sensor.
122    pub color_filter_array: Option<ColorFilterArray>,
123    /// A raw ICC profile, written to its own data block.
124    pub icc_profile: Option<Vec<u8>>,
125    /// A preview of this image, written to its own data block.
126    pub thumbnail: Option<PendingThumbnail>,
127    /// FITS keywords, in the order they should appear.
128    pub fits_keywords: Vec<FitsKeyword>,
129    /// Table properties belonging to this image.
130    pub tables: Vec<Table>,
131}
132
133/// A preview image attached to another image.
134#[derive(Clone, Debug)]
135pub struct PendingThumbnail {
136    pub image: Image,
137    pub data: Vec<u8>,
138    pub options: BlockOptions,
139}
140
141/// One `<FITSKeyword>` element.
142#[derive(Clone, Debug, Default, PartialEq, Eq)]
143pub struct FitsKeyword {
144    pub name: String,
145    pub value: String,
146    pub comment: String,
147}
148
149impl PendingImage {
150    /// An image with pixel data and nothing attached to it.
151    pub fn new(image: Image, data: Vec<u8>, options: BlockOptions) -> Self {
152        PendingImage {
153            image,
154            data,
155            options,
156            resolution: None,
157            rgb_working_space: None,
158            display_function: None,
159            color_filter_array: None,
160            icc_profile: None,
161            thumbnail: None,
162            fits_keywords: Vec::new(),
163            tables: Vec::new(),
164        }
165    }
166
167    pub fn with_resolution(mut self, resolution: Resolution) -> Self {
168        self.resolution = Some(resolution);
169        self
170    }
171
172    pub fn with_rgb_working_space(mut self, space: RgbWorkingSpace) -> Self {
173        self.rgb_working_space = Some(space);
174        self
175    }
176
177    pub fn with_display_function(mut self, function: DisplayFunction) -> Self {
178        self.display_function = Some(function);
179        self
180    }
181
182    pub fn with_color_filter_array(mut self, cfa: ColorFilterArray) -> Self {
183        self.color_filter_array = Some(cfa);
184        self
185    }
186
187    /// Attach a raw ICC profile.
188    ///
189    /// The bytes are written as given but for one bit. The specification
190    /// requires a profile to be stored "unaltered, except for the embedded
191    /// profile flag, which must be set", and that flag "must be set to one to
192    /// signify that the profile has been embedded in a file" -- a profile
193    /// taken straight off disk normally has it clear, so writing it verbatim
194    /// produces an embedded profile advertising that it is not embedded, and
195    /// a colour-managed reader may substitute the display profile and shift
196    /// every colour in the image.
197    ///
198    /// An ICC profile is defined as big-endian by its own specification, so
199    /// the spec forbids a `byteOrder` attribute on this block and none is
200    /// written.
201    pub fn with_icc_profile(mut self, profile: Vec<u8>) -> Self {
202        self.icc_profile = Some(profile);
203        self
204    }
205
206    /// Attach a preview image.
207    ///
208    /// A thumbnail must be a two-dimensional 8- or 16-bit image, which is
209    /// checked when the file is written rather than here, so a caller building
210    /// one up can do it in any order.
211    pub fn with_thumbnail(mut self, thumbnail: PendingThumbnail) -> Self {
212        self.thumbnail = Some(thumbnail);
213        self
214    }
215
216    /// Attach a table property to this image.
217    pub fn with_table(mut self, table: Table) -> Self {
218        self.tables.push(table);
219        self
220    }
221
222    pub fn with_fits_keyword(
223        mut self,
224        name: impl Into<String>,
225        value: impl Into<String>,
226        comment: impl Into<String>,
227    ) -> Self {
228        self.fits_keywords.push(FitsKeyword {
229            name: name.into(),
230            value: value.into(),
231            comment: comment.into(),
232        });
233        self
234    }
235}
236
237impl PendingThumbnail {
238    pub fn new(image: Image, data: Vec<u8>, options: BlockOptions) -> Self {
239        PendingThumbnail { image, data, options }
240    }
241}
242
243/// Builds a monolithic XISF file.
244#[derive(Clone, Debug, Default)]
245pub struct Writer {
246    images: Vec<PendingImage>,
247    /// Extra `<Property>` elements for the `<Metadata>` block.
248    metadata: Vec<(String, String, String)>,
249    creator: Option<String>,
250    /// `XISF:CreationTime`, as an ISO 8601 instant. `None` means "now",
251    /// resolved when the file is rendered.
252    creation_time: Option<String>,
253    /// Standalone `<Table>` elements, belonging to the unit rather than to
254    /// any one image.
255    tables: Vec<Table>,
256}
257
258impl Writer {
259    pub fn new() -> Self {
260        Self::default()
261    }
262
263    /// Name the software that produced the file. Written as
264    /// `XISF:CreatorApplication`, which is the property the spec reserves.
265    pub fn with_creator(mut self, creator: impl Into<String>) -> Self {
266        self.creator = Some(creator.into());
267        self
268    }
269
270    /// Set `XISF:CreationTime` rather than taking it from the clock.
271    ///
272    /// The spec requires the property, so it is always written; this exists
273    /// because a timestamp makes output non-reproducible, and a caller
274    /// rebuilding a file or comparing two runs needs to be able to pin it.
275    /// The value is written as given, so it must be a valid ISO 8601 instant.
276    pub fn with_creation_time(mut self, instant: impl Into<String>) -> Self {
277        self.creation_time = Some(instant.into());
278        self
279    }
280
281    /// Add a string property to the file's `<Metadata>`.
282    ///
283    /// The identifier must satisfy the format's grammar, since a property
284    /// nothing can look up by name is not a property.
285    pub fn add_metadata(&mut self, id: impl Into<String>, value: impl Into<String>) -> Result<()> {
286        let id = id.into();
287        check_property_id(&id)?;
288        self.metadata.push((id, "String".into(), value.into()));
289        Ok(())
290    }
291
292    /// Add a scalar property to the file's `<Metadata>`.
293    ///
294    /// A baseline encoder must "write properties of all 8-bit, 16-bit, 32-bit
295    /// and 64-bit scalar types", and until this existed the only property this
296    /// writer could emit was a string -- so a caller had no way to record an
297    /// exposure time as a `Float32` or a gain as an `Int32` without writing
298    /// the number out as text under a type that says it is text.
299    ///
300    /// The value is serialized as the specification's plain text for its type,
301    /// and is checked against the declared type before it is accepted, so a
302    /// value that does not fit is refused here rather than read back as a
303    /// different number.
304    pub fn add_scalar_property(
305        &mut self,
306        id: impl Into<String>,
307        value: ScalarProperty,
308    ) -> Result<()> {
309        let id = id.into();
310        check_property_id(&id)?;
311        let (kind, text) = value.serialize();
312        self.metadata.push((id, kind.into(), text));
313        Ok(())
314    }
315
316    /// Add a table property describing the unit as a whole.
317    pub fn add_table(&mut self, table: Table) -> Result<()> {
318        check_table(&table)?;
319        self.tables.push(table);
320        Ok(())
321    }
322
323    /// Add an image, checking that its data matches the geometry it declares.
324    pub fn add_image(&mut self, pending: PendingImage) -> Result<()> {
325        // Revision 1: "The id attribute of an Image core element must be
326        // unique within the XISF unit." An id is how a caller asks for one
327        // image out of several, so a duplicate does not merely break a rule --
328        // it makes the question "which image is `Light`?" unanswerable, and
329        // the writer is the last place that can still refuse to pose it.
330        if let Some(id) = &pending.image.id
331            && self.images.iter().any(|existing| existing.image.id.as_ref() == Some(id))
332        {
333            return Err(err!(
334                InvalidArgument,
335                "two images share the id {id:?}, which must be unique within the unit"
336            ));
337        }
338
339        // "The bounds attribute is required for floating point real images."
340        // Without it a reader has no black and white point and must guess --
341        // PixInsight assumes [0,1], a pipeline working in ADU assumes
342        // [0,65535] -- so the pixels survive and every statistic taken from
343        // them is wrong by a factor nothing reports.
344        if pending.image.sample_format.requires_bounds() && pending.image.bounds.is_none() {
345            return Err(err!(
346                InvalidArgument,
347                "a {} image must declare its bounds; there is no default \
348                 representable range for floating point real pixel data",
349                pending.image.sample_format.name()
350            ));
351        }
352
353        if let Some(id) = &pending.image.id {
354            check_image_id(id)?;
355        }
356        if let Some(uuid) = &pending.image.uuid {
357            check_uuid(uuid)?;
358        }
359
360        let expected = pending
361            .image
362            .data_size()
363            .ok_or_else(|| err!(InvalidArgument, "the image's geometry overflows"))?;
364        if pending.data.len() as u64 != expected {
365            return Err(err!(
366                InvalidArgument,
367                "the image declares {expected} bytes of pixel data but {} were given",
368                pending.data.len()
369            ));
370        }
371        // A thumbnail is a preview meant to be cheap to display, so the spec
372        // restricts it to two dimensions and to 8- or 16-bit samples. Writing
373        // one that breaks those rules produces a file readers may reject, and
374        // the writer is the last place that can still say so usefully.
375        if let Some(thumbnail) = &pending.thumbnail {
376            let expected = thumbnail
377                .image
378                .data_size()
379                .ok_or_else(|| err!(InvalidArgument, "the thumbnail's geometry overflows"))?;
380            if thumbnail.data.len() as u64 != expected {
381                return Err(err!(
382                    InvalidArgument,
383                    "the thumbnail declares {expected} bytes but {} were given",
384                    thumbnail.data.len()
385                ));
386            }
387            if thumbnail.image.dimensions.len() != 2 {
388                return Err(err!(
389                    InvalidArgument,
390                    "a thumbnail must be two-dimensional, got {} dimension(s)",
391                    thumbnail.image.dimensions.len()
392                ));
393            }
394            if !matches!(
395                thumbnail.image.sample_format,
396                crate::image::SampleFormat::UInt8 | crate::image::SampleFormat::UInt16
397            ) {
398                return Err(err!(
399                    InvalidArgument,
400                    "a thumbnail must be UInt8 or UInt16, got {}",
401                    thumbnail.image.sample_format.name()
402                ));
403            }
404            // The spec forbids `bounds` on a thumbnail outright: its range is
405            // always the full width of its integer type, so a bounds
406            // attribute would be either redundant or a contradiction.
407            if thumbnail.image.bounds.is_some() {
408                return Err(err!(
409                    InvalidArgument,
410                    "a thumbnail must not declare bounds; its range is its sample format's"
411                ));
412            }
413            if !matches!(
414                thumbnail.image.color_space,
415                crate::image::ColorSpace::Gray | crate::image::ColorSpace::Rgb
416            ) {
417                return Err(err!(
418                    InvalidArgument,
419                    "a thumbnail must be grayscale or RGB, got {}",
420                    thumbnail.image.color_space.name()
421                ));
422            }
423        }
424
425        for keyword in &pending.fits_keywords {
426            check_fits_name(&keyword.name)?;
427        }
428        for table in &pending.tables {
429            check_table(table)?;
430        }
431
432        self.images.push(pending);
433        Ok(())
434    }
435
436    /// Serialise the whole file.
437    pub fn to_bytes(&self) -> Result<Vec<u8>> {
438        // Each block is compressed once, up front: the stored bytes decide
439        // both the sizes in the header and the checksums, so doing it inside
440        // the positioning loop would be wasted work and, worse, would let a
441        // non-deterministic codec change sizes between rounds.
442        let stored = self.prepare_blocks()?;
443
444        // Fixed point on the header length; see the module comment.
445        let mut assumed =
446            self.render(&stored, Addressing::Attached { data_at: PREAMBLE_LEN })?.len();
447        let header = loop {
448            let header =
449                self.render(&stored, Addressing::Attached { data_at: PREAMBLE_LEN + assumed })?;
450            if header.len() == assumed {
451                break header;
452            }
453            // Monotonic: a longer header only ever pushes positions outward.
454            assumed = header.len();
455        };
456
457        let mut out = Vec::with_capacity(
458            PREAMBLE_LEN
459                + header.len()
460                + stored.blocks.iter().map(|b| b.bytes.len()).sum::<usize>(),
461        );
462        out.extend_from_slice(SIGNATURE);
463        out.extend_from_slice(
464            &(u32::try_from(header.len()).map_err(|_| {
465                err!(Unsupported, "the header is larger than the format's 32-bit length field")
466            })?)
467            .to_le_bytes(),
468        );
469        out.extend_from_slice(&[0; 4]);
470        out.extend_from_slice(header.as_bytes());
471        for block in &stored.blocks {
472            out.extend_from_slice(&block.bytes);
473        }
474        Ok(out)
475    }
476
477    /// Serialise as a *distributed* unit: a header file and a blocks file.
478    ///
479    /// `blocks_file_name` is what the header will name, so it must be the
480    /// name the blocks file is actually saved under, and the two must end up
481    /// in the same directory. The reader resolves a relative locator beside
482    /// the file that named it.
483    ///
484    /// Unlike the monolithic form this needs no fixed point: the header names
485    /// blocks by identifier rather than by position, so its length does not
486    /// feed back into its contents.
487    pub fn to_distributed(&self, blocks_file_name: &str) -> Result<DistributedUnit> {
488        if blocks_file_name.is_empty() || blocks_file_name.contains('/') {
489            return Err(err!(
490                InvalidArgument,
491                "the blocks file name must be a plain file name, got {blocks_file_name:?}"
492            ));
493        }
494
495        let stored = self.prepare_blocks()?;
496
497        let blocks: Vec<crate::distributed::PendingBlock> = stored
498            .blocks
499            .iter()
500            .enumerate()
501            .map(|(index, block)| crate::distributed::PendingBlock {
502                id: block_id(index),
503                bytes: block.bytes.clone(),
504                // The index element records the size before compression, and
505                // zero for a block stored as it is.
506                uncompressed_length: block
507                    .compression
508                    .as_ref()
509                    .map(|compression| compression.uncompressed_size),
510            })
511            .collect();
512
513        let header =
514            self.render(&stored, Addressing::Distributed { blocks_file: blocks_file_name })?;
515        Ok(DistributedUnit {
516            header: header.into_bytes(),
517            blocks: crate::distributed::write_blocks_file(&blocks)?,
518            blocks_file_name: blocks_file_name.to_string(),
519        })
520    }
521
522    /// Compress every block once, and record which belongs to which image.
523    ///
524    /// An image can own three blocks -- its pixels, an ICC profile and a
525    /// thumbnail -- so blocks are no longer one per image and the mapping has
526    /// to be kept rather than inferred from a position in the list.
527    fn prepare_blocks(&self) -> Result<StoredBlocks> {
528        let mut blocks = Vec::new();
529        let mut owners = Vec::with_capacity(self.images.len());
530
531        let mut push = |data: &[u8], options: &BlockOptions| -> Result<usize> {
532            blocks.push(StoredBlock::prepare(data, options)?);
533            Ok(blocks.len() - 1)
534        };
535
536        for pending in &self.images {
537            // The order here is the order the blocks are written in, and the
538            // positions are derived from it, so it must not drift from the
539            // order used when the file is assembled.
540            let data = push(&pending.data, &pending.options)?;
541            let icc = match &pending.icc_profile {
542                None => None,
543                Some(profile) => {
544                    Some(push(&with_embedded_profile_flag(profile)?, &BlockOptions::default())?)
545                }
546            };
547            let thumbnail = match &pending.thumbnail {
548                None => None,
549                Some(thumb) => Some(push(&thumb.data, &thumb.options)?),
550            };
551            owners.push(ImageBlocks { data, icc, thumbnail });
552        }
553        Ok(StoredBlocks { blocks, owners })
554    }
555
556    /// Render the XML header, naming blocks as `addressing` says.
557    fn render(&self, stored: &StoredBlocks, addressing: Addressing<'_>) -> Result<String> {
558        let mut xml = String::from(r#"<?xml version="1.0" encoding="UTF-8"?>"#);
559        xml.push_str(r#"<xisf version="1.0" xmlns="http://www.pixinsight.com/xisf" "#);
560        xml.push_str(r#"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" "#);
561        xml.push_str(
562            r#"xsi:schemaLocation="http://www.pixinsight.com/xisf http://pixinsight.com/xisf/xisf-1.0.xsd">"#,
563        );
564
565        // Every block's position is settled before anything is emitted, so
566        // the order elements are written in cannot drift from the order the
567        // blocks are laid down in. Getting that wrong silently points an
568        // element at another element's bytes.
569        let base = match addressing {
570            Addressing::Attached { data_at } => data_at,
571            Addressing::Distributed { .. } => 0,
572        };
573        let mut positions = Vec::with_capacity(stored.blocks.len());
574        let mut cursor = base;
575        for block in &stored.blocks {
576            positions.push(cursor);
577            cursor += block.bytes.len();
578        }
579
580        // How one block is addressed, whichever form the unit takes.
581        let locate = |index: usize| -> String {
582            let block = &stored.blocks[index];
583            match addressing {
584                Addressing::Attached { .. } => {
585                    format!("attachment:{}:{}", positions[index], block.bytes.len())
586                }
587                // `path(@header_dir/name):0xID`. The `@header_dir` token is
588                // the only relative form the grammar defines -- a bare
589                // `path(name)` is neither absolute nor documented, however
590                // obvious its meaning -- and the identifier goes in
591                // hexadecimal, as the spec recommends.
592                Addressing::Distributed { blocks_file } => {
593                    format!(
594                        "path({HEADER_DIR_TOKEN}/{}):{:#x}",
595                        escape_attr(blocks_file),
596                        block_id(index)
597                    )
598                }
599            }
600        };
601
602        for (pending, owned) in self.images.iter().zip(&stored.owners) {
603            let block = &stored.blocks[owned.data];
604            let image = &pending.image;
605            let mut geometry: Vec<String> = image.dimensions.iter().map(u64::to_string).collect();
606            geometry.push(image.channels.to_string());
607
608            xml.push_str("<Image geometry=\"");
609            xml.push_str(&geometry.join(":"));
610            xml.push_str("\" sampleFormat=\"");
611            xml.push_str(image.sample_format.name());
612            xml.push_str("\" colorSpace=\"");
613            xml.push_str(image.color_space.name());
614            xml.push_str("\" pixelStorage=\"");
615            xml.push_str(image.pixel_storage.name());
616            xml.push('"');
617
618            if let Some(bounds) = image.bounds {
619                xml.push_str(&format!(" bounds=\"{}:{}\"", bounds.low, bounds.high));
620            }
621            if let Some(id) = &image.id {
622                xml.push_str(&format!(" id=\"{}\"", escape_attr(id)));
623            }
624            if let Some(kind) = &image.image_type {
625                xml.push_str(&format!(" imageType=\"{}\"", escape_attr(kind.name())));
626            }
627            if let Some(uuid) = &image.uuid {
628                xml.push_str(&format!(" uuid=\"{}\"", escape_attr(uuid)));
629            }
630            if let Some(offset) = image.offset {
631                xml.push_str(&format!(" offset=\"{offset}\""));
632            }
633            if let Some(orientation) = image.orientation {
634                xml.push_str(&format!(" orientation=\"{}\"", orientation.to_attribute()));
635            }
636            push_block_attrs(&mut xml, block);
637
638            xml.push_str(&format!(" location=\"{}\">", locate(owned.data)));
639
640            // Ancillary elements are written as children of the image they
641            // belong to. The spec also allows them at the root with a `uid`
642            // and a `<Reference>`, which is how a file shares one element
643            // between images; a writer that owns each element outright has
644            // nothing to share, so the direct form is the honest one.
645            for keyword in &pending.fits_keywords {
646                xml.push_str(&format!(
647                    "<FITSKeyword name=\"{}\" value=\"{}\" comment=\"{}\"/>",
648                    escape_attr(&keyword.name),
649                    escape_attr(&keyword.value),
650                    escape_attr(&keyword.comment)
651                ));
652            }
653            if let Some(resolution) = &pending.resolution {
654                xml.push_str(&format!(
655                    "<Resolution horizontal=\"{}\" vertical=\"{}\" unit=\"{}\"/>",
656                    resolution.horizontal,
657                    resolution.vertical,
658                    resolution.unit.name()
659                ));
660            }
661            if let Some(space) = &pending.rgb_working_space {
662                // Revision 1: "Encoders shall compute luminance coefficients
663                // in this way." They follow from the chromaticities and the
664                // D50 reference white, so writing whatever a caller happened
665                // to put in the struct would produce a header that contradicts
666                // itself. A set of primaries with no solution is not a valid
667                // working space, and is refused rather than written.
668                let luminance =
669                    RgbWorkingSpace::derive_luminance(space.x, space.y).ok_or_else(|| {
670                        err!(
671                            InvalidArgument,
672                            "the RGB working space primaries x={:?} y={:?} are degenerate, \
673                             so no luminance coefficients follow from them",
674                            space.x,
675                            space.y
676                        )
677                    })?;
678                xml.push_str(&format!(
679                    "<RGBWorkingSpace x=\"{}\" y=\"{}\" Y=\"{}\" gamma=\"{}\"",
680                    join_numbers(&space.x),
681                    join_numbers(&space.y),
682                    join_numbers(&luminance),
683                    match space.gamma {
684                        Gamma::Srgb => "sRGB".to_string(),
685                        Gamma::Exponent(exponent) => exponent.to_string(),
686                    }
687                ));
688                if let Some(name) = &space.name {
689                    xml.push_str(&format!(" name=\"{}\"", escape_attr(name)));
690                }
691                xml.push_str("/>");
692            }
693            if let Some(function) = &pending.display_function {
694                xml.push_str(&format!(
695                    "<DisplayFunction m=\"{}\" s=\"{}\" h=\"{}\" l=\"{}\" r=\"{}\"",
696                    join_numbers(&function.midtones),
697                    join_numbers(&function.shadows),
698                    join_numbers(&function.highlights),
699                    join_numbers(&function.low_range),
700                    join_numbers(&function.high_range)
701                ));
702                if let Some(name) = &function.name {
703                    xml.push_str(&format!(" name=\"{}\"", escape_attr(name)));
704                }
705                xml.push_str("/>");
706            }
707            if let Some(cfa) = &pending.color_filter_array {
708                xml.push_str(&format!(
709                    "<ColorFilterArray pattern=\"{}\" width=\"{}\" height=\"{}\"",
710                    cfa.pattern_string(),
711                    cfa.width,
712                    cfa.height
713                ));
714                if let Some(name) = &cfa.name {
715                    xml.push_str(&format!(" name=\"{}\"", escape_attr(name)));
716                }
717                xml.push_str("/>");
718            }
719            if let Some(index) = owned.icc {
720                // No `byteOrder`: an ICC profile is big-endian by its own
721                // specification, and the XISF spec forbids the attribute here.
722                xml.push_str("<ICCProfile");
723                push_block_attrs(&mut xml, &stored.blocks[index]);
724                xml.push_str(&format!(" location=\"{}\"/>", locate(index)));
725            }
726            if let Some(index) = owned.thumbnail {
727                let thumb = &pending.thumbnail.as_ref().expect("a thumbnail block has one").image;
728                let mut geometry: Vec<String> =
729                    thumb.dimensions.iter().map(u64::to_string).collect();
730                geometry.push(thumb.channels.to_string());
731                xml.push_str(&format!(
732                    "<Thumbnail geometry=\"{}\" sampleFormat=\"{}\" colorSpace=\"{}\" \
733                     pixelStorage=\"{}\"",
734                    geometry.join(":"),
735                    thumb.sample_format.name(),
736                    thumb.color_space.name(),
737                    // Dropping this was a silent corruption rather than an
738                    // omission: "Other than its tag name, a Thumbnail core
739                    // element is identical to an Image core element" apart
740                    // from a short list of restrictions that does not include
741                    // pixelStorage, and the default is Planar -- so a Normal
742                    // thumbnail read back with its channels interleaved
743                    // wrongly, with nothing reporting it.
744                    thumb.pixel_storage.name()
745                ));
746                if let Some(id) = &thumb.id {
747                    xml.push_str(&format!(" id=\"{}\"", escape_attr(id)));
748                }
749                if let Some(uuid) = &thumb.uuid {
750                    xml.push_str(&format!(" uuid=\"{}\"", escape_attr(uuid)));
751                }
752                if let Some(kind) = &thumb.image_type {
753                    xml.push_str(&format!(" imageType=\"{}\"", escape_attr(kind.name())));
754                }
755                if let Some(offset) = thumb.offset {
756                    xml.push_str(&format!(" offset=\"{offset}\""));
757                }
758                if let Some(orientation) = thumb.orientation
759                    && !orientation.is_identity()
760                {
761                    xml.push_str(&format!(" orientation=\"{}\"", orientation.to_attribute()));
762                }
763                push_block_attrs(&mut xml, &stored.blocks[index]);
764                xml.push_str(&format!(" location=\"{}\"/>", locate(index)));
765            }
766
767            for table in &pending.tables {
768                push_table(&mut xml, table);
769            }
770
771            xml.push_str("</Image>");
772        }
773
774        for table in &self.tables {
775            push_table(&mut xml, table);
776        }
777
778        // `<Metadata>` is required by the spec, and it *must* carry both
779        // `XISF:CreationTime` and `XISF:CreatorApplication`, so neither is
780        // conditional on the caller having said anything.
781        xml.push_str("<Metadata>");
782        xml.push_str(&format!(
783            "<Property id=\"XISF:CreationTime\" type=\"TimePoint\" value=\"{}\"/>",
784            match &self.creation_time {
785                Some(instant) => escape_attr(instant),
786                None => escape_attr(&now_iso8601()),
787            }
788        ));
789        // "If the XISF unit contains data blocks with checksums / compressed
790        // data blocks, this property should be defined to enumerate the
791        // applied hashing algorithms / compression codec(s)." They are derived
792        // from what was actually written rather than from what the caller
793        // asked for, so they cannot disagree with the blocks they describe.
794        let mut algorithms: Vec<&str> = Vec::new();
795        let mut codecs: Vec<&str> = Vec::new();
796        for block in &stored.blocks {
797            if let Some(checksum) = &block.checksum
798                && !algorithms.contains(&checksum.algorithm.name())
799            {
800                algorithms.push(checksum.algorithm.name());
801            }
802            if let Some(compression) = &block.compression
803                && !codecs.contains(&compression.codec.name())
804            {
805                codecs.push(compression.codec.name());
806            }
807        }
808        if !algorithms.is_empty() {
809            xml.push_str(&format!(
810                "<Property id=\"XISF:ChecksumAlgorithms\" type=\"String\">{}</Property>",
811                escape_text(&algorithms.join(","))
812            ));
813        }
814        if !codecs.is_empty() {
815            xml.push_str(&format!(
816                "<Property id=\"XISF:CompressionCodecs\" type=\"String\">{}</Property>",
817                escape_text(&codecs.join(","))
818            ));
819        }
820
821        for (id, kind, value) in &self.metadata {
822            // A String property "shall not have a value attribute, and must
823            // serialize the property value either directly in its character
824            // data contents, or as an XISF data block"; every other scalar
825            // carries its value in the attribute. Writing a scalar as
826            // character data, or a string as an attribute, is the wrong shape
827            // for both.
828            if kind == "String" {
829                xml.push_str(&format!(
830                    "<Property id=\"{}\" type=\"String\">{}</Property>",
831                    escape_attr(id),
832                    escape_text(value)
833                ));
834            } else {
835                xml.push_str(&format!(
836                    "<Property id=\"{}\" type=\"{}\" value=\"{}\"/>",
837                    escape_attr(id),
838                    escape_attr(kind),
839                    escape_attr(value)
840                ));
841            }
842        }
843        xml.push_str(&format!(
844            "<Property id=\"XISF:CreatorApplication\" type=\"String\">{}</Property>",
845            escape_text(self.creator.as_deref().unwrap_or("xisf-rs"))
846        ));
847        xml.push_str("</Metadata>");
848
849        xml.push_str("</xisf>");
850        Ok(xml)
851    }
852}
853
854/// The current instant as `YYYY-MM-DDThh:mm:ssZ`, which is what a
855/// `TimePoint` property holds.
856///
857/// Written out rather than taken from a date library: this is the only date
858/// arithmetic in the workspace, and a dependency for it would be carried by
859/// every user of the crate for one line of output. A clock before the epoch
860/// is not something to fail a write over, so it reads as the epoch itself.
861fn now_iso8601() -> String {
862    let seconds = std::time::SystemTime::now()
863        .duration_since(std::time::UNIX_EPOCH)
864        .map_or(0, |elapsed| elapsed.as_secs());
865    iso8601_from_unix(seconds)
866}
867
868/// Format a Unix timestamp, in seconds, as an ISO 8601 instant in UTC.
869fn iso8601_from_unix(seconds: u64) -> String {
870    let days = (seconds / 86_400) as i64;
871    let time = seconds % 86_400;
872    let (year, month, day) = civil_from_days(days);
873    format!(
874        "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
875        time / 3600,
876        (time % 3600) / 60,
877        time % 60
878    )
879}
880
881/// The civil date `days` after 1970-01-01, by Howard Hinnant's algorithm.
882///
883/// It works by shifting the epoch to March 1st, which puts the leap day at
884/// the end of the year and so removes February's irregular length from every
885/// other calculation.
886fn civil_from_days(days: i64) -> (i64, u32, u32) {
887    let shifted = days + 719_468;
888    let era = shifted.div_euclid(146_097);
889    let day_of_era = shifted.rem_euclid(146_097);
890    let year_of_era =
891        (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
892    let year = year_of_era + era * 400;
893    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
894    let shifted_month = (5 * day_of_year + 2) / 153;
895    let day = (day_of_year - (153 * shifted_month + 2) / 5 + 1) as u32;
896    let month = if shifted_month < 10 { shifted_month + 3 } else { shifted_month - 9 } as u32;
897    (if month <= 2 { year + 1 } else { year }, month, day)
898}
899
900/// Write the `compression` and `checksum` attributes a block needs, if any.
901fn push_block_attrs(xml: &mut String, block: &StoredBlock) {
902    if let Some(compression) = &block.compression {
903        xml.push_str(&format!(" compression=\"{}\"", compression_attr(compression)));
904    }
905    if let Some(checksum) = &block.checksum {
906        xml.push_str(&format!(
907            " checksum=\"{}:{}\"",
908            checksum.algorithm.name(),
909            digest_hex(&checksum.digest)
910        ));
911    }
912}
913
914/// The largest input a codec will take in one call.
915///
916/// The specification's answer to a larger block is the `subblocks` attribute,
917/// which divides it into several independent streams. This writer emits one
918/// stream per block, so these are the sizes past which it has to decline.
919fn codec_input_limit(codec: Codec2) -> u64 {
920    match codec {
921        // zlib's own interface takes a 32-bit length.
922        Codec2::Zlib => u64::from(u32::MAX),
923        // LZ4_MAX_INPUT_SIZE, which every LZ4 implementation shares.
924        Codec2::Lz4 => 0x7E00_0000,
925        // Zstandard frames carry a 64-bit content size and have no practical
926        // input limit of their own, so the bound is what one allocation can
927        // hold rather than anything the format imposes.
928        Codec2::Zstd => u64::MAX,
929    }
930}
931
932/// Check a table before it is written.
933///
934/// Cells are positional: which field a cell belongs to is decided by nothing
935/// but its place in the row. A row of the wrong length therefore has no
936/// reading at all, and writing one produces a file whose every value after
937/// the gap belongs to the wrong column.
938fn check_table(table: &Table) -> Result<()> {
939    check_property_id(&table.id)?;
940    if table.structure.fields.is_empty() {
941        return Err(err!(InvalidArgument, "table {:?} has no fields", table.id));
942    }
943    for field in &table.structure.fields {
944        check_property_id(&field.id)?;
945    }
946    for (n, row) in table.rows.iter().enumerate() {
947        if row.len() != table.structure.fields.len() {
948            return Err(err!(
949                InvalidArgument,
950                "table {:?} row {n} has {} cells but its structure declares {} fields",
951                table.id,
952                row.len(),
953                table.structure.fields.len()
954            ));
955        }
956        for cell in row {
957            // A cell whose value lives in a data block would need a block
958            // allocated for it, which this writer does not do. Saying so
959            // beats writing a `<Cell>` with no value in it.
960            if cell.data.location.is_some() {
961                return Err(err!(
962                    Unsupported,
963                    "table {:?} has a cell stored in a data block, which cannot be written yet",
964                    table.id
965                ));
966            }
967        }
968    }
969    Ok(())
970}
971
972/// Serialise one `<Table>` element and everything under it.
973fn push_table(xml: &mut String, table: &Table) {
974    xml.push_str(&format!("<Table id=\"{}\"", escape_attr(&table.id)));
975    if let Some(caption) = &table.caption {
976        xml.push_str(&format!(" caption=\"{}\"", escape_attr(caption)));
977    }
978    if let Some(comment) = &table.comment {
979        xml.push_str(&format!(" comment=\"{}\"", escape_attr(comment)));
980    }
981    // `rows` and `columns` are optional but must agree with the data when
982    // present, which is easy here and saves a reader from counting.
983    xml.push_str(&format!(
984        " rows=\"{}\" columns=\"{}\">",
985        table.rows.len(),
986        table.structure.fields.len()
987    ));
988
989    // The structure is written inline and before the rows, as the spec asks:
990    // it wants sequential parsers to know the shape before the data arrives.
991    xml.push_str("<Structure>");
992    for field in &table.structure.fields {
993        xml.push_str(&format!(
994            "<Field id=\"{}\" type=\"{}\"",
995            escape_attr(&field.id),
996            escape_attr(&field.kind.name())
997        ));
998        if let Some(format) = &field.format {
999            xml.push_str(&format!(" format=\"{}\"", escape_attr(format)));
1000        }
1001        if let Some(header) = &field.header {
1002            xml.push_str(&format!(" header=\"{}\"", escape_attr(header)));
1003        }
1004        xml.push_str("/>");
1005    }
1006    xml.push_str("</Structure>");
1007
1008    for row in &table.rows {
1009        xml.push_str("<Row>");
1010        for cell in row {
1011            match (&cell.value, &cell.data.text) {
1012                (Some(value), _) => {
1013                    xml.push_str(&format!("<Cell value=\"{}\"/>", escape_attr(value)));
1014                }
1015                (None, Some(text)) => {
1016                    xml.push_str(&format!("<Cell>{}</Cell>", escape_text(text)));
1017                }
1018                // Not `<Cell value=""/>`. A String field's cell "shall not
1019                // have a value attribute", and Revision 1 amended the
1020                // specification's own table examples for exactly this -- so
1021                // emitting one produced the construct the revision was written
1022                // to forbid. The spec's corrected example uses the empty
1023                // element, which is valid for every field type.
1024                (None, None) => xml.push_str("<Cell/>"),
1025            }
1026        }
1027        xml.push_str("</Row>");
1028    }
1029    xml.push_str("</Table>");
1030}
1031
1032/// Check a property identifier against the format's grammar.
1033///
1034/// An identifier is one or more colon-separated segments, each starting with
1035/// a letter or underscore and continuing with letters, digits or underscores.
1036/// The colons group properties into namespaces, which is why `XISF:` names
1037/// are reserved and why an identifier is the only handle a reader has on a
1038/// property.
1039///
1040/// A note for whoever checks this against the document: the regular
1041/// expression the specification prints,
1042/// `[_a-zA-Z][_a-zA-Z0-9]*(:([_a-zA-Z][_a-zA-Z0-9])+)*`, is wrong. Its
1043/// namespace group matches *pairs* of characters -- a `*` is missing inside
1044/// it -- so it rejects `foo:bar:Foo2_Bar3`, which the same section gives as a
1045/// valid example three lines later. The evident intent is implemented here,
1046/// since a grammar that refuses its own examples cannot be the one meant.
1047fn check_property_id(id: &str) -> Result<()> {
1048    let valid = !id.is_empty()
1049        && id.split(':').all(|segment| {
1050            let mut chars = segment.chars();
1051            chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
1052                && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
1053        });
1054    if !valid {
1055        return Err(err!(
1056            InvalidArgument,
1057            "{id:?} is not a valid property identifier: one or more colon-separated \
1058             segments, each beginning with a letter or underscore"
1059        ));
1060    }
1061    Ok(())
1062}
1063
1064/// Check a FITS keyword name against the FITS 3.0 grammar the spec cites.
1065///
1066/// "The keyword name shall be a left justified, 8-character, space-filled,
1067/// ASCII string with no embedded spaces", using digits, upper case `A`-`Z`,
1068/// underscore and hyphen only. The point of a `FITSKeyword` element is to be
1069/// a compatibility layer with FITS, so a name FITS itself would reject makes
1070/// the element useless for the one job it has -- and the file is checked
1071/// where it is built rather than by whoever eventually reads it.
1072fn check_fits_name(name: &str) -> Result<()> {
1073    if name.len() > 8 {
1074        return Err(err!(
1075            InvalidArgument,
1076            "the FITS keyword {name:?} is {} characters; the limit is 8",
1077            name.len()
1078        ));
1079    }
1080    if let Some(bad) = name
1081        .chars()
1082        .find(|c| !(c.is_ascii_digit() || c.is_ascii_uppercase() || *c == '_' || *c == '-'))
1083    {
1084        return Err(err!(
1085            InvalidArgument,
1086            "the FITS keyword {name:?} contains {bad:?}; only A-Z, 0-9, underscore and \
1087             hyphen are permitted"
1088        ));
1089    }
1090    Ok(())
1091}
1092
1093/// Colon-separated numbers, the form every multi-valued XISF attribute uses.
1094fn join_numbers(values: &[f64]) -> String {
1095    values.iter().map(f64::to_string).collect::<Vec<_>>().join(":")
1096}
1097
1098/// Every block in a unit, and which image each one belongs to.
1099struct StoredBlocks {
1100    /// In the order they are written, which is what fixes their positions.
1101    blocks: Vec<StoredBlock>,
1102    /// One entry per image, in the order the images were added.
1103    owners: Vec<ImageBlocks>,
1104}
1105
1106/// Indices into [`StoredBlocks::blocks`] for one image.
1107struct ImageBlocks {
1108    data: usize,
1109    icc: Option<usize>,
1110    thumbnail: Option<usize>,
1111}
1112
1113/// The identifier the `n`th block is given in a data blocks file.
1114///
1115/// One-based: zero is a legal identifier, but it is also what an uninitialised
1116/// field reads as, so starting at one makes a mistake visible.
1117fn block_id(index: usize) -> u64 {
1118    index as u64 + 1
1119}
1120
1121/// A block after compression, ready to be addressed and written.
1122struct StoredBlock {
1123    bytes: Vec<u8>,
1124    compression: Option<Compression>,
1125    checksum: Option<crate::block::Checksum>,
1126}
1127
1128impl StoredBlock {
1129    fn prepare(data: &[u8], options: &BlockOptions) -> Result<Self> {
1130        let (bytes, compression) = match &options.compression {
1131            None => (data.to_vec(), None),
1132            Some(request) => {
1133                let uncompressed_size = data.len() as u64;
1134
1135                // Shuffle first, then compress: that is the order the spec
1136                // fixes, and the reader undoes it the other way round.
1137                // An item size of one shuffles nothing, and the spec does not
1138                // allow `+sh:...:1` as a stored form. Rather than making every
1139                // caller special-case eight-bit data -- the natural thing to
1140                // pass is the sample width, which is 1 for UInt8 -- it is
1141                // treated as a request for no shuffling.
1142                let item_size = request.shuffle_item_size.filter(|item| *item > 1);
1143                let staged = match item_size {
1144                    None => data.to_vec(),
1145                    Some(item) => {
1146                        let item = usize::try_from(item)
1147                            .map_err(|_| err!(InvalidArgument, "shuffle item size is unusable"))?;
1148                        codec::shuffle(data, item)
1149                    }
1150                };
1151
1152                // Codecs have input limits, and past them a block must be
1153                // split into subblocks with a `subblocks` attribute saying
1154                // how. This writer does not split, so it refuses rather than
1155                // handing a codec more than it can take: the alternative is
1156                // a file that looks written and cannot be read back.
1157                let limit = codec_input_limit(request.codec);
1158                if staged.len() as u64 > limit {
1159                    return Err(err!(
1160                        Unsupported,
1161                        "a {}-byte block exceeds the {} input limit of {limit} bytes; \
1162                         it would have to be split into compression subblocks, which this \
1163                         writer does not do",
1164                        staged.len(),
1165                        request.codec.as_codec().name()
1166                    ));
1167                }
1168
1169                let compressed = compress(&staged, request.codec)?;
1170
1171                // Compression that makes a block bigger is not worth writing:
1172                // the file grows and every reader pays to undo it. Storing it
1173                // plain is always legal, since `compression` is optional.
1174                if compressed.len() >= data.len() {
1175                    (data.to_vec(), None)
1176                } else {
1177                    (
1178                        compressed,
1179                        Some(Compression {
1180                            subblocks: Vec::new(),
1181                            codec: request.codec.as_codec(),
1182                            uncompressed_size,
1183                            shuffle_item_size: item_size,
1184                        }),
1185                    )
1186                }
1187            }
1188        };
1189
1190        // The checksum covers the block as stored, so it is taken after
1191        // compression, matching what a reader can verify without decoding.
1192        let checksum = match options.checksum {
1193            None => None,
1194            Some(algorithm) => Some(checksum_of(&bytes, algorithm)?),
1195        };
1196
1197        Ok(StoredBlock { bytes, compression, checksum })
1198    }
1199}
1200
1201// As `codec::decompress`: with no codec feature enabled every arm below is
1202// compiled out, leaving `data` unread. That is right for such a build.
1203#[cfg_attr(not(any(feature = "zlib", feature = "lz4")), allow(unused_variables))]
1204fn compress(data: &[u8], codec: Codec2) -> Result<Vec<u8>> {
1205    match codec {
1206        #[cfg(feature = "zlib")]
1207        Codec2::Zlib => {
1208            use std::io::Write;
1209            let mut encoder =
1210                flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
1211            encoder.write_all(data).map_err(|e| err!(Compression, "zlib: {e}"))?;
1212            encoder.finish().map_err(|e| err!(Compression, "zlib: {e}"))
1213        }
1214        #[cfg(feature = "lz4")]
1215        Codec2::Lz4 => Ok(lz4_flex::block::compress(data)),
1216        // Level 3 is `zrip`'s DFast strategy: the middle of the -8..4 range it
1217        // implements, and a ratio comparable to zlib's default at a good deal
1218        // less time. Revision 1 stores Zstandard as one frame per subblock,
1219        // and this writer emits one stream per block, so one frame is right.
1220        Codec2::Zstd => zrip::compress(data, 3).map_err(|e| err!(Compression, "zstd: {e}")),
1221        #[allow(unreachable_patterns)]
1222        other => Err(err!(Unsupported, "cannot write {:?} blocks in this build", other)),
1223    }
1224}
1225
1226/// Check an image identifier against the grammar the specification gives.
1227///
1228/// "image-id shall be a sequence of ASCII characters satisfying the following
1229/// regular expression: `[_a-zA-Z][_a-zA-Z0-9]*`". Property identifiers were
1230/// already checked; images were not, so the writer could emit a header the
1231/// schema rejects.
1232fn check_image_id(id: &str) -> Result<()> {
1233    let mut chars = id.chars();
1234    let valid = match chars.next() {
1235        Some(first) if first == '_' || first.is_ascii_alphabetic() => {
1236            chars.all(|c| c == '_' || c.is_ascii_alphanumeric())
1237        }
1238        _ => false,
1239    };
1240    if !valid {
1241        return Err(err!(
1242            InvalidArgument,
1243            "{id:?} is not a valid image identifier; it must match [_a-zA-Z][_a-zA-Z0-9]*"
1244        ));
1245    }
1246    Ok(())
1247}
1248
1249/// Check a UUID against the canonical form, and that it is version 4.
1250///
1251/// "uuid must be a plain text representation of a Universally Unique
1252/// Identifier (UUID) in canonical form. Version 4 UUIDs must be used" --
1253/// Revision 1 tightened the generator requirements and replaced the obsolete
1254/// RFC 4122 reference with RFC 9562.
1255fn check_uuid(uuid: &str) -> Result<()> {
1256    let groups: Vec<&str> = uuid.split('-').collect();
1257    let shaped = groups.len() == 5
1258        && [8usize, 4, 4, 4, 12].iter().zip(&groups).all(|(want, group)| {
1259            group.len() == *want && group.chars().all(|c| c.is_ascii_hexdigit())
1260        });
1261    if !shaped {
1262        return Err(err!(
1263            InvalidArgument,
1264            "{uuid:?} is not a UUID in canonical 8-4-4-4-12 hexadecimal form"
1265        ));
1266    }
1267    // The version is the first character of the third group.
1268    if !groups[2].starts_with('4') {
1269        return Err(err!(
1270            InvalidArgument,
1271            "{uuid:?} is not a version 4 UUID, which the specification requires"
1272        ));
1273    }
1274    Ok(())
1275}
1276
1277/// A scalar property value, with the XISF type it is written as.
1278///
1279/// The set is the one a baseline encoder is required to write -- "properties
1280/// of all 8-bit, 16-bit, 32-bit and 64-bit scalar types" -- plus Boolean,
1281/// which costs nothing to include and is otherwise unwritable.
1282#[derive(Clone, Copy, PartialEq, Debug)]
1283pub enum ScalarProperty {
1284    Boolean(bool),
1285    Int8(i8),
1286    UInt8(u8),
1287    Int16(i16),
1288    UInt16(u16),
1289    Int32(i32),
1290    UInt32(u32),
1291    Int64(i64),
1292    UInt64(u64),
1293    Float32(f32),
1294    Float64(f64),
1295}
1296
1297impl ScalarProperty {
1298    /// The XISF type name and the plain text serialization of the value.
1299    fn serialize(self) -> (&'static str, String) {
1300        match self {
1301            // "A serialization of a Boolean value as plain text shall be one
1302            // of the words true and false."
1303            ScalarProperty::Boolean(v) => ("Boolean", v.to_string()),
1304            ScalarProperty::Int8(v) => ("Int8", v.to_string()),
1305            ScalarProperty::UInt8(v) => ("UInt8", v.to_string()),
1306            ScalarProperty::Int16(v) => ("Int16", v.to_string()),
1307            ScalarProperty::UInt16(v) => ("UInt16", v.to_string()),
1308            ScalarProperty::Int32(v) => ("Int32", v.to_string()),
1309            ScalarProperty::UInt32(v) => ("UInt32", v.to_string()),
1310            ScalarProperty::Int64(v) => ("Int64", v.to_string()),
1311            ScalarProperty::UInt64(v) => ("UInt64", v.to_string()),
1312            // Rust prints `NaN`, `inf` and `-inf`, all of which the
1313            // specification names as valid serializations of the non-finite
1314            // values.
1315            ScalarProperty::Float32(v) => ("Float32", v.to_string()),
1316            ScalarProperty::Float64(v) => ("Float64", v.to_string()),
1317        }
1318    }
1319}
1320
1321/// A copy of an ICC profile with its embedded profile flag set.
1322///
1323/// The one alteration the specification permits: profiles "must store ICC
1324/// profile structures unaltered, except for the embedded profile flag", which
1325/// is bit 0 of the profile flags field -- a big-endian `u32` at byte offset 44
1326/// of the 128-byte profile header, per section 7.2.11 of the ICC
1327/// specification.
1328///
1329/// Everything else is copied byte for byte. A buffer too short to hold a
1330/// profile header is refused rather than written: it is not a profile, and
1331/// silently storing it would put something that is not an ICC profile in an
1332/// element that says it is one.
1333fn with_embedded_profile_flag(profile: &[u8]) -> Result<Vec<u8>> {
1334    /// The fixed size of an ICC profile header.
1335    const HEADER_LEN: usize = 128;
1336    /// Byte offset of the profile flags field within that header.
1337    const FLAGS_AT: usize = 44;
1338    /// Bit 0 of the flags field: "the profile is embedded in a file".
1339    const EMBEDDED: u32 = 1;
1340
1341    if profile.len() < HEADER_LEN {
1342        return Err(err!(
1343            InvalidArgument,
1344            "an ICC profile needs at least {HEADER_LEN} bytes of header, this has {}",
1345            profile.len()
1346        ));
1347    }
1348
1349    let mut out = profile.to_vec();
1350    let flags = u32::from_be_bytes(
1351        out[FLAGS_AT..FLAGS_AT + 4].try_into().expect("four bytes inside the header"),
1352    );
1353    out[FLAGS_AT..FLAGS_AT + 4].copy_from_slice(&(flags | EMBEDDED).to_be_bytes());
1354    Ok(out)
1355}
1356
1357/// Render a `compression` attribute.
1358fn compression_attr(compression: &Compression) -> String {
1359    match compression.shuffle_item_size {
1360        None => format!("{}:{}", compression.codec.name(), compression.uncompressed_size),
1361        Some(item) => {
1362            format!("{}+sh:{}:{}", compression.codec.name(), compression.uncompressed_size, item)
1363        }
1364    }
1365}
1366
1367/// Escape text for an attribute value.
1368fn escape_attr(text: &str) -> String {
1369    let mut out = String::with_capacity(text.len());
1370    for c in text.chars() {
1371        match c {
1372            '&' => out.push_str("&amp;"),
1373            '<' => out.push_str("&lt;"),
1374            '>' => out.push_str("&gt;"),
1375            '"' => out.push_str("&quot;"),
1376            '\'' => out.push_str("&apos;"),
1377            _ => out.push(c),
1378        }
1379    }
1380    out
1381}
1382
1383/// Escape character data. Quotes need no escaping here, but `]]>` would end a
1384/// CDATA section, so `>` is escaped along with the two that must be.
1385fn escape_text(text: &str) -> String {
1386    let mut out = String::with_capacity(text.len());
1387    for c in text.chars() {
1388        match c {
1389            '&' => out.push_str("&amp;"),
1390            '<' => out.push_str("&lt;"),
1391            '>' => out.push_str("&gt;"),
1392            _ => out.push(c),
1393        }
1394    }
1395    out
1396}
1397
1398#[cfg(test)]
1399mod tests {
1400    use super::*;
1401    use crate::Reader;
1402    use crate::image::{ColorSpace, PixelStorage, SampleFormat};
1403
1404    fn image(width: u64, height: u64, channels: u64, format: SampleFormat) -> Image {
1405        Image {
1406            dimensions: vec![width, height],
1407            channels,
1408            sample_format: format,
1409            color_space: if channels >= 3 { ColorSpace::Rgb } else { ColorSpace::Gray },
1410            pixel_storage: PixelStorage::Planar,
1411            bounds: format
1412                .requires_bounds()
1413                .then_some(crate::image::Bounds { low: 0.0, high: 1.0 }),
1414            id: None,
1415            uuid: None,
1416            image_type: None,
1417            offset: None,
1418            orientation: None,
1419        }
1420    }
1421
1422    fn sample(len: usize) -> Vec<u8> {
1423        (0..len).map(|i| (i * 31 + 7) as u8).collect()
1424    }
1425
1426    fn round_trip(options: BlockOptions, format: SampleFormat) -> Vec<u8> {
1427        let image = image(9, 7, 1, format);
1428        let data = sample(image.data_size().unwrap() as usize);
1429
1430        let mut writer = Writer::new().with_creator("xisf-rs tests");
1431        writer.add_image(PendingImage::new(image, data.clone(), options)).expect("add_image");
1432        let bytes = writer.to_bytes().expect("to_bytes");
1433
1434        let reader = Reader::from_bytes(bytes).expect("read back");
1435        let written = reader.header().images()[0];
1436        let read = reader.block(&written.data).expect("block").to_vec();
1437        assert_eq!(read, data, "the pixels changed on the way through");
1438        reader.bytes().to_vec()
1439    }
1440
1441    #[test]
1442    fn writes_a_file_that_reads_back() {
1443        round_trip(BlockOptions::default(), SampleFormat::UInt8);
1444    }
1445
1446    /// Only over what this build can actually write, so the matrix stays
1447    /// honest under `--no-default-features` rather than asserting that an
1448    /// absent codec works.
1449    fn writable_compressions() -> Vec<Option<CompressionRequest>> {
1450        // Zstandard is never absent: Revision 1 makes it standard and this
1451        // crate compiles it in unconditionally.
1452        let mut out = vec![
1453            None,
1454            Some(CompressionRequest { codec: Codec2::Zstd, shuffle_item_size: None }),
1455            Some(CompressionRequest { codec: Codec2::Zstd, shuffle_item_size: Some(4) }),
1456        ];
1457        if cfg!(feature = "zlib") {
1458            out.push(Some(CompressionRequest { codec: Codec2::Zlib, shuffle_item_size: None }));
1459            out.push(Some(CompressionRequest { codec: Codec2::Zlib, shuffle_item_size: Some(4) }));
1460        }
1461        if cfg!(feature = "lz4") {
1462            out.push(Some(CompressionRequest { codec: Codec2::Lz4, shuffle_item_size: None }));
1463            out.push(Some(CompressionRequest { codec: Codec2::Lz4, shuffle_item_size: Some(2) }));
1464        }
1465        out
1466    }
1467
1468    fn writable_checksums() -> Vec<Option<ChecksumAlgorithm>> {
1469        vec![None, Some(ChecksumAlgorithm::Sha256)]
1470    }
1471
1472    #[test]
1473    fn every_option_combination_round_trips() {
1474        for format in [SampleFormat::UInt8, SampleFormat::UInt16, SampleFormat::Float32] {
1475            for compression in writable_compressions() {
1476                for checksum in writable_checksums() {
1477                    round_trip(BlockOptions { compression, checksum }, format);
1478                }
1479            }
1480        }
1481    }
1482
1483    /// The positions in the header must land exactly on the bytes, with no
1484    /// gap and no overlap. This is the fixed point the module comment
1485    /// describes, and it is the thing most likely to be off by a few.
1486    #[test]
1487    fn block_positions_are_exact_and_contiguous() {
1488        let mut writer = Writer::new();
1489        for channels in [1u64, 3, 1] {
1490            let image = image(11, 13, channels, SampleFormat::UInt16);
1491            let data = sample(image.data_size().unwrap() as usize);
1492            writer.add_image(PendingImage::new(image, data, BlockOptions::default())).unwrap();
1493        }
1494        let bytes = writer.to_bytes().unwrap();
1495        let reader = Reader::from_bytes(bytes.clone()).unwrap();
1496
1497        let mut expected = crate::layout::scan(&bytes).unwrap().data_start() as u64;
1498        for element in reader.header().images() {
1499            let Some(crate::block::Location::Attachment { position, size }) = element.data.location
1500            else {
1501                panic!("expected an attachment");
1502            };
1503            assert_eq!(position, expected, "a block did not begin where the last one ended");
1504            expected += size;
1505        }
1506        assert_eq!(expected as usize, bytes.len(), "the file has trailing bytes");
1507    }
1508
1509    #[cfg(feature = "zlib")]
1510    #[test]
1511    fn checksums_written_are_checksums_that_verify() {
1512        let image = image(8, 8, 1, SampleFormat::UInt16);
1513        let data = sample(image.data_size().unwrap() as usize);
1514        let mut writer = Writer::new();
1515        writer
1516            .add_image(PendingImage::new(
1517                image,
1518                data,
1519                BlockOptions {
1520                    compression: Some(CompressionRequest {
1521                        codec: Codec2::Zlib,
1522                        shuffle_item_size: Some(2),
1523                    }),
1524                    checksum: Some(ChecksumAlgorithm::Sha512),
1525                },
1526            ))
1527            .unwrap();
1528
1529        let reader = Reader::from_bytes(writer.to_bytes().unwrap()).unwrap();
1530        let written = reader.header().images()[0];
1531        assert_eq!(
1532            reader.verify(&written.data).unwrap(),
1533            crate::ChecksumStatus::Valid,
1534            "a checksum we wrote ourselves did not verify"
1535        );
1536    }
1537
1538    /// Compression that makes a block larger is dropped, since storing it
1539    /// plain is legal and strictly better.
1540    #[cfg(feature = "zlib")]
1541    #[test]
1542    fn incompressible_data_is_stored_plain() {
1543        let image = image(4, 4, 1, SampleFormat::UInt8);
1544        // Bytes with no structure to exploit.
1545        let data: Vec<u8> = (0..16u32).map(|i| (i.wrapping_mul(2654435761) >> 24) as u8).collect();
1546
1547        let mut writer = Writer::new();
1548        writer
1549            .add_image(PendingImage::new(
1550                image,
1551                data,
1552                BlockOptions {
1553                    compression: Some(CompressionRequest {
1554                        codec: Codec2::Zlib,
1555                        shuffle_item_size: None,
1556                    }),
1557                    checksum: None,
1558                },
1559            ))
1560            .unwrap();
1561
1562        let reader = Reader::from_bytes(writer.to_bytes().unwrap()).unwrap();
1563        assert!(
1564            reader.header().images()[0].data.compression.is_none(),
1565            "compression that did not help should not have been recorded"
1566        );
1567    }
1568
1569    #[test]
1570    fn data_that_does_not_match_the_geometry_is_refused() {
1571        let mut writer = Writer::new();
1572        let err = writer
1573            .add_image(PendingImage::new(
1574                image(10, 10, 1, SampleFormat::UInt16),
1575                vec![0; 3],
1576                BlockOptions::default(),
1577            ))
1578            .unwrap_err();
1579        assert_eq!(err.kind(), crate::ErrorKind::InvalidArgument);
1580    }
1581
1582    #[test]
1583    fn special_characters_in_metadata_are_escaped() {
1584        let mut writer = Writer::new();
1585        writer.add_metadata("Test:Value", r#"a & b < c > d " e ' f"#).expect("id");
1586        writer
1587            .add_image(PendingImage::new(
1588                image(2, 2, 1, SampleFormat::UInt8),
1589                sample(4),
1590                BlockOptions::default(),
1591            ))
1592            .unwrap();
1593
1594        // The proof is that it parses at all: unescaped `&` or `<` in
1595        // character data is not well-formed XML.
1596        let reader = Reader::from_bytes(writer.to_bytes().unwrap()).unwrap();
1597        let property = reader
1598            .header()
1599            .root
1600            .descendants()
1601            .into_iter()
1602            .find(|e| e.attr("id") == Some("Test:Value"))
1603            .expect("the property survived");
1604        assert_eq!(property.data.text.as_deref(), Some(r#"a & b < c > d " e ' f"#));
1605    }
1606}
1607
1608#[cfg(test)]
1609mod time_tests {
1610    use super::iso8601_from_unix;
1611
1612    /// Dates are the classic place for an off-by-one that only shows up on a
1613    /// leap day or a century boundary, so the cases are chosen to hit those
1614    /// rather than to sample a comfortable middle.
1615    #[test]
1616    fn unix_timestamps_format_as_iso8601() {
1617        for (seconds, expected) in [
1618            (0, "1970-01-01T00:00:00Z"),
1619            (86_399, "1970-01-01T23:59:59Z"),
1620            (86_400, "1970-01-02T00:00:00Z"),
1621            (68_169_600, "1972-02-29T00:00:00Z"),  // a leap day
1622            (951_782_400, "2000-02-29T00:00:00Z"), // 2000 is a leap year
1623            (4_107_456_000, "2100-02-28T00:00:00Z"), // 2100 is not a leap year,
1624            (4_107_542_400, "2100-03-01T00:00:00Z"), // so the day after is March
1625            (1_418_128_695, "2014-12-09T12:38:15Z"), // the spec's own example
1626        ] {
1627            assert_eq!(iso8601_from_unix(seconds), expected, "for {seconds}");
1628        }
1629    }
1630}