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
//! A distributed unit, end to end: header file plus data blocks file.
//!
//! The pieces are unit-tested separately; this checks they fit together, which
//! is where the interesting mistake lives. A `location="path:blocks.xisb:7"`
//! names a block by its *identifier* in the file's index, not by its position
//! and not by an ordinal — a reader that treated the whole file as the block,
//! or the number as an offset, would produce plausible-looking rubbish rather
//! than an error.

use std::path::PathBuf;

use xisf_core::distributed::PendingBlock;
use xisf_core::distributed::{parse_blocks_file, write_blocks_file};
use xisf_core::{ErrorKind, Reader};

/// A scratch directory that removes itself.
struct Scratch(PathBuf);

impl Scratch {
    fn new(name: &str) -> Self {
        let path =
            std::env::temp_dir().join(format!("xisf-distributed-{}-{name}", std::process::id()));
        let _ = std::fs::remove_dir_all(&path);
        std::fs::create_dir_all(&path).expect("scratch directory");
        Self(path)
    }

    fn join(&self, name: &str) -> PathBuf {
        self.0.join(name)
    }
}

impl Drop for Scratch {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

/// The pixel data for a 4x4 UInt16 image: deterministic, and distinguishable
/// from the signature and index bytes that surround it in the file.
fn pixels() -> Vec<u8> {
    (0..32u32).map(|i| (i * 7 + 13) as u8).collect()
}

fn header_naming(block: &str) -> String {
    format!(
        r#"<?xml version="1.0" encoding="UTF-8"?><xisf version="1.0"
xmlns="http://www.pixinsight.com/xisf"><Image geometry="4:4:1"
sampleFormat="UInt16" colorSpace="Gray" location="{block}"/></xisf>"#
    )
}

/// A header file that is not monolithic, addressing a block in a `.xisb`.
fn write_unit(scratch: &Scratch, blocks: &[(u64, Vec<u8>)], locator: &str) -> PathBuf {
    std::fs::write(
        scratch.join("data.xisb"),
        write_blocks_file(&plain_blocks(blocks)).expect("blocks file"),
    )
    .expect("write blocks");

    // The reader resolves `path:` relative to the file it came from, so the
    // header has to be a real file on disk beside the blocks.
    let header = scratch.join("unit.xish");
    std::fs::write(&header, header_naming(locator)).expect("write header");
    header
}

/// A header file carrying the given `location`.
///
/// It must be a header file rather than a monolithic wrapper: "External XISF
/// data blocks shall not occur in a monolithic XISF file", so a `.xisf`
/// naming a `path(...)` or `url(...)` block is refused. `Reader::open` takes
/// either form -- it decides by looking at the bytes rather than at the
/// suffix -- so a bare XML document is all this needs to be.
fn header_file_naming(scratch: &Scratch, locator: &str) -> PathBuf {
    let path = scratch.join("unit.xish");
    std::fs::write(&path, header_naming(locator)).expect("write");
    path
}

#[test]
fn a_block_is_read_out_of_a_data_blocks_file_by_identifier() {
    let scratch = Scratch::new("by-id");
    let data = pixels();

    // Three blocks, with the wanted one neither first nor last, so an
    // implementation that ignored the identifier would pick the wrong bytes.
    let blocks = vec![(1u64, vec![0xAA; 16]), (7u64, data.clone()), (9u64, vec![0xBB; 8])];
    std::fs::write(scratch.join("data.xisb"), write_blocks_file(&plain_blocks(&blocks)).unwrap())
        .unwrap();

    let path = header_file_naming(&scratch, "path(data.xisb):7");
    let reader = Reader::open(&path).expect("open");
    let image = reader.header().images()[0];

    let read = reader.block(&image.data).expect("block");
    assert_eq!(&*read, &data[..], "the wrong block was read");
}

/// A blocks file addressed without an identifier is ambiguous, and guessing
/// would hand back the signature and index as pixel data.
#[test]
fn a_blocks_file_must_be_addressed_by_identifier() {
    let scratch = Scratch::new("no-id");
    std::fs::write(
        scratch.join("data.xisb"),
        write_blocks_file(&plain_blocks(&[(1, pixels())])).unwrap(),
    )
    .unwrap();

    let path = header_file_naming(&scratch, "path(data.xisb)");
    let reader = Reader::open(&path).expect("open");
    let err = reader.block(&reader.header().images()[0].data).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::BadAttribute);
    assert!(err.message().contains("must name a block"), "{}", err.message());
}

/// A plain external file is the whole block, which is the other legal shape.
#[test]
fn a_plain_external_file_is_the_whole_block() {
    let scratch = Scratch::new("plain");
    let data = pixels();
    std::fs::write(scratch.join("raw.dat"), &data).unwrap();

    let path = header_file_naming(&scratch, "path(raw.dat)");
    let reader = Reader::open(&path).expect("open");
    let read = reader.block(&reader.header().images()[0].data).expect("block");
    assert_eq!(&*read, &data[..]);
}

/// ...and naming a block inside one is a mistake worth reporting.
#[test]
fn a_plain_file_may_not_be_addressed_by_identifier() {
    let scratch = Scratch::new("plain-id");
    std::fs::write(scratch.join("raw.dat"), pixels()).unwrap();

    let path = header_file_naming(&scratch, "path(raw.dat):3");
    let reader = Reader::open(&path).expect("open");
    let err = reader.block(&reader.header().images()[0].data).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::BadAttribute);
}

#[test]
fn an_unknown_identifier_is_reported() {
    let scratch = Scratch::new("unknown-id");
    std::fs::write(
        scratch.join("data.xisb"),
        write_blocks_file(&plain_blocks(&[(1, pixels())])).unwrap(),
    )
    .unwrap();

    let path = header_file_naming(&scratch, "path(data.xisb):42");
    let reader = Reader::open(&path).expect("open");
    let err = reader.block(&reader.header().images()[0].data).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
}

/// The header file half of a distributed unit parses on its own.
#[test]
fn a_header_file_parses_and_names_its_blocks() {
    let scratch = Scratch::new("header-file");
    let header_path = write_unit(&scratch, &[(3, pixels())], "path(data.xisb):3");

    let bytes = std::fs::read(&header_path).expect("read");
    let header = xisf_core::distributed::parse_header_file(&bytes).expect("parse");

    let images = header.images();
    assert_eq!(images.len(), 1);
    assert_eq!(
        images[0].data.location,
        Some(xisf_core::block::Location::Path { path: "data.xisb".into(), index: Some(3) })
    );
}

/// The index survives a round trip through the file format, positions
/// included -- the thing most likely to be off by the size of a header.
#[test]
fn index_positions_address_the_blocks_they_name() {
    let blocks: Vec<(u64, Vec<u8>)> =
        (0..5u64).map(|i| (i * 3 + 1, vec![i as u8; (i as usize + 1) * 10])).collect();
    let bytes = write_blocks_file(&plain_blocks(&blocks)).expect("write");
    let index = parse_blocks_file(&bytes).expect("parse");

    assert_eq!(index.elements.len(), blocks.len());
    for (id, expected) in &blocks {
        let element = index.get(*id).unwrap_or_else(|| panic!("block {id} is missing"));
        let start = element.position as usize;
        let end = start + element.length as usize;
        assert_eq!(&bytes[start..end], &expected[..], "block {id} is not where the index says");
    }
}

// ---- Writing --------------------------------------------------------

/// The round trip that matters: write a distributed unit, save both halves,
/// and read the pixels back through the ordinary reader.
#[test]
fn a_distributed_unit_written_here_reads_back() {
    use xisf_core::image::{ColorSpace, Image, PixelStorage, SampleFormat};
    use xisf_core::writer::{BlockOptions, PendingImage, Writer};

    let scratch = Scratch::new("write-roundtrip");

    let mut writer = Writer::new().with_creator("xisf-rs");
    let mut expected = Vec::new();
    for (index, channels) in [1u64, 3, 1].into_iter().enumerate() {
        let image = Image {
            dimensions: vec![6, 5],
            channels,
            sample_format: SampleFormat::UInt16,
            color_space: if channels >= 3 { ColorSpace::Rgb } else { ColorSpace::Gray },
            pixel_storage: PixelStorage::Planar,
            bounds: None,
            id: None,
            uuid: None,
            image_type: None,
            offset: None,
            orientation: None,
        };
        let size = image.data_size().unwrap() as usize;
        let data: Vec<u8> = (0..size).map(|i| (i * 13 + index * 7) as u8).collect();
        expected.push(data.clone());
        writer
            .add_image(PendingImage::new(image, data, BlockOptions::default()))
            .expect("add_image");
    }

    let unit = writer.to_distributed("data.xisb").expect("to_distributed");
    std::fs::write(scratch.join("unit.xish"), &unit.header).unwrap();
    std::fs::write(scratch.join(&unit.blocks_file_name), &unit.blocks).unwrap();

    // The header file is XML and nothing else: no signature, no preamble.
    assert!(unit.header.starts_with(b"<?xml"), "a header file starts with its XML");
    assert!(unit.blocks.starts_with(b"XISB0100"), "a blocks file starts with XISB");

    // Read it back the way a consumer would.
    let header = xisf_core::distributed::parse_header_file(&unit.header).expect("parse header");
    assert_eq!(header.images().len(), 3);

    // And the blocks resolve. The reader needs a file on disk to resolve
    // `path(...)` relative to, so this goes through a monolithic wrapper
    // carrying the same locators.
    let index = parse_blocks_file(&unit.blocks).expect("parse blocks");
    assert_eq!(index.occupied().count(), 3);

    for (n, image) in header.images().iter().enumerate() {
        let Some(xisf_core::block::Location::Path { path, index: id }) = &image.data.location
        else {
            panic!("image {n} is not addressed by path");
        };
        // The spec's own relative form: `@header_dir` is a literal token
        // meaning "the directory holding the header", not a directory name.
        assert_eq!(path, "@header_dir/data.xisb");
        let element = index.get(id.expect("an identifier")).expect("the block is indexed");

        let start = element.position as usize;
        let end = start + element.length as usize;
        assert_eq!(&unit.blocks[start..end], &expected[n][..], "image {n} has the wrong bytes");
    }
}

/// Reading it through the ordinary `Reader`, which is what a consumer
/// actually does, rather than only through the pieces. Compressed on
/// purpose, so the block is not merely a copy of the input -- which needs a
/// codec compiled in.
#[cfg(feature = "zlib")]
#[test]
fn the_reader_resolves_a_written_distributed_unit() {
    use xisf_core::image::{ColorSpace, Image, PixelStorage, SampleFormat};
    use xisf_core::writer::{BlockOptions, CompressionRequest, PendingImage, Writer};

    let scratch = Scratch::new("reader-resolves");
    let image = Image {
        dimensions: vec![8, 4],
        channels: 1,
        sample_format: SampleFormat::UInt16,
        color_space: ColorSpace::Gray,
        pixel_storage: PixelStorage::Planar,
        bounds: None,
        id: None,
        uuid: None,
        image_type: None,
        offset: None,
        orientation: None,
    };
    let size = image.data_size().unwrap() as usize;
    let data: Vec<u8> = (0..size).map(|i| (i * 5 + 1) as u8).collect();

    let mut writer = Writer::new();
    writer
        .add_image(PendingImage::new(
            image,
            data.clone(),
            BlockOptions {
                // Compressed, so the block is not merely a copy of the input.
                compression: Some(CompressionRequest {
                    codec: xisf_core::writer::Codec2::Zlib,
                    shuffle_item_size: Some(2),
                }),
                checksum: None,
            },
        ))
        .unwrap();

    let unit = writer.to_distributed("blocks.xisb").expect("to_distributed");
    std::fs::write(scratch.join(&unit.blocks_file_name), &unit.blocks).unwrap();

    // The header file as the writer produced it. Wrapping it in a monolithic
    // container would be the wrong shape as well as the wrong test: external
    // blocks may not occur in a monolithic file, and `Reader::open` takes a
    // header file directly.
    let path = scratch.join("unit.xish");
    std::fs::write(&path, &unit.header).unwrap();

    let reader = Reader::open(&path).expect("open");
    let read = reader.block(&reader.header().images()[0].data).expect("block");
    assert_eq!(&*read, &data[..], "the pixels did not survive the round trip");
}

#[test]
fn a_blocks_file_name_must_be_a_plain_name() {
    use xisf_core::writer::Writer;
    for name in ["", "sub/dir.xisb", "/absolute.xisb"] {
        assert!(Writer::new().to_distributed(name).is_err(), "{name:?} should have been refused");
    }
}

/// A distributed unit's header file opens directly.
///
/// A `.xish` is XML with no signature, so it used to be rejected outright and
/// the only way to read one was to wrap it in a monolithic file by hand. The
/// writer produces these, which made them a form the library could emit but
/// not read back.
#[test]
fn a_header_file_opens_without_being_wrapped() {
    let scratch = Scratch::new("xish-open");
    let data = pixels();
    let blocks = vec![(1u64, data.clone())];
    std::fs::write(scratch.join("data.xisb"), write_blocks_file(&plain_blocks(&blocks)).unwrap())
        .unwrap();

    let path = scratch.join("unit.xish");
    std::fs::write(&path, header_naming("path(data.xisb):0x1")).unwrap();

    let reader = Reader::open(&path).expect("a .xish should open");
    let image = reader.header().images()[0];
    assert_eq!(&*reader.block(&image.data).expect("block"), &data[..]);
}

/// Detection is by content, not by suffix, and the two forms cannot collide:
/// an XML document cannot begin with the eight signature bytes.
#[test]
fn the_two_file_forms_are_told_apart_by_what_they_contain() {
    let scratch = Scratch::new("forms");
    let xml = header_naming("inline:base64");

    // A header file under the wrong name still opens...
    let odd = scratch.join("unit.xisf");
    std::fs::write(&odd, &xml).unwrap();
    assert!(Reader::open(&odd).is_ok(), "a header file was refused for its name");

    // ...a leading byte order mark is tolerated, since UTF-8 XML may carry
    // one and it is not part of the document...
    let bom = scratch.join("bom.xish");
    let mut bytes = vec![0xEF, 0xBB, 0xBF];
    bytes.extend_from_slice(xml.as_bytes());
    std::fs::write(&bom, &bytes).unwrap();
    assert!(Reader::open(&bom).is_ok(), "a byte order mark was not skipped");

    // ...and something that is neither is still refused as neither.
    let junk = scratch.join("junk.xisf");
    std::fs::write(&junk, b"not xisf and not xml either").unwrap();
    let err = Reader::open(&junk).expect_err("arbitrary bytes were accepted");
    assert_eq!(err.kind(), xisf_core::ErrorKind::NotXisf);
}

/// `@header_dir` is the only relative `path()` form the grammar defines, and
/// a unit written per the spec's own examples has to open. It failed before:
/// the token was looked for as a literal directory of that name.
#[test]
fn the_header_dir_token_resolves_beside_the_header() {
    let scratch = Scratch::new("header-dir");
    let data = pixels();
    std::fs::create_dir_all(scratch.join("astrometry")).unwrap();
    std::fs::write(scratch.join("plain.bin"), &data).unwrap();
    std::fs::write(scratch.join("astrometry/solution.dat"), &data).unwrap();

    // The spec's two worked examples: a file beside the header, and one in a
    // sub-directory of it. Plus the bare relative form, which the grammar
    // does not define but which files in the wild use.
    for locator in [
        "path(@header_dir/plain.bin)",
        "path(@header_dir/astrometry/solution.dat)",
        "path(plain.bin)",
    ] {
        let path = header_file_naming(&scratch, locator);
        let reader = Reader::open(&path).unwrap_or_else(|e| panic!("{locator}: {e}"));
        let image = reader.header().images()[0];
        assert_eq!(
            &*reader.block(&image.data).unwrap_or_else(|e| panic!("{locator}: {e}")),
            &data[..],
            "{locator}"
        );
    }
}

/// The token is a prefix, not an exemption: everything after it is still a
/// relative path that has to stay inside the header's directory.
#[test]
fn the_header_dir_token_cannot_be_used_to_climb_out() {
    let scratch = Scratch::new("header-dir-escape");
    std::fs::create_dir_all(scratch.join("unit")).unwrap();
    std::fs::write(scratch.join("secret.txt"), b"secret").unwrap();
    std::fs::write(scratch.join("unit/plain.bin"), pixels()).unwrap();

    for locator in [
        "path(@header_dir/../secret.txt)",
        "path(@header_dir/a/../../secret.txt)",
        "path(@header_dir//etc/hostname)",
        "path(@header_dir)",
    ] {
        let xml = header_naming(locator);
        let mut bytes = Vec::from(*b"XISF0100");
        bytes.extend_from_slice(&(xml.len() as u32).to_le_bytes());
        bytes.extend_from_slice(&[0u8; 4]);
        bytes.extend_from_slice(xml.as_bytes());
        let path = scratch.join("unit/unit.xisf");
        std::fs::write(&path, bytes).unwrap();

        let reader = Reader::open(&path).expect("open");
        let image = reader.header().images()[0];
        assert!(reader.block(&image.data).is_err(), "{locator} was followed");
    }
}

/// Blocks stored as they are, which is what these tests care about; the
/// uncompressed length only matters for a block that was compressed.
fn plain_blocks(blocks: &[(u64, Vec<u8>)]) -> Vec<PendingBlock> {
    blocks
        .iter()
        .map(|(id, bytes)| PendingBlock {
            id: *id,
            bytes: bytes.clone(),
            uncompressed_length: None,
        })
        .collect()
}