Skip to main content

xisf_core/
block.rs

1//! The attributes that say where a data block is, and what has been done to it.
2//!
3//! Three attributes travel together on every element that carries data, and
4//! each has its own small grammar. They are parsed here rather than at the
5//! call sites, because getting them wrong is how a reader ends up addressing
6//! bytes that are not there.
7/// The token a relative `path(...)` locator begins with.
8///
9/// The specification defines exactly two `path()` forms: an absolute path,
10/// and `path(@header_dir/rel-path)` for one relative to the directory holding
11/// the header. The token is literal -- it is not a directory named
12/// `@header_dir`.
13pub const HEADER_DIR_TOKEN: &str = "@header_dir";
14
15use crate::err;
16use crate::error::{ErrorKind, Result};
17
18/// Where a data block's bytes are.
19#[derive(Clone, PartialEq, Eq, Debug)]
20pub enum Location {
21    /// In the element's own character data, text-encoded.
22    Inline { encoding: TextEncoding },
23    /// In a child `<Data>` element.
24    ///
25    /// The spec gives this its own form rather than folding it into `inline`
26    /// because an element that may have child elements cannot also carry
27    /// character data unambiguously.
28    ///
29    /// The encoding is the `<Data>` element's own `encoding` attribute, which
30    /// the schema makes required and which may be `hex` as well as `base64`.
31    /// It is carried here rather than assumed, because assuming base64 turns
32    /// a legal hex block into a decoding error.
33    Embedded { encoding: TextEncoding },
34    /// A byte range of this file, after the header.
35    Attachment { position: u64, size: u64 },
36    /// Another file, named by a path relative to this one.
37    Path { path: String, index: Option<u64> },
38    /// Another resource, named by a URL.
39    Url { url: String, index: Option<u64> },
40}
41
42/// How a text-encoded block is spelled.
43#[derive(Clone, Copy, PartialEq, Eq, Debug)]
44pub enum TextEncoding {
45    /// RFC 4648 Base64.
46    Base64,
47    /// RFC 4648 Base16, which the spec calls `hex`.
48    Hex,
49}
50
51impl Location {
52    /// Parse a `location` attribute.
53    ///
54    /// ```text
55    /// location="inline:base64"                 (or :hex)
56    /// location="embedded"
57    /// location="attachment:1234:5678"          position:size
58    /// location="path(/data/blocks.xisb)"       optionally ):0x7a73...
59    /// location="url(http://host/f.xisb)"       optionally ):0x7a73...
60    /// ```
61    ///
62    /// Note the shapes differ: `inline` and `attachment` take colon-separated
63    /// fields, while `path` and `url` **parenthesise** their locator. That is
64    /// what lets a URL contain colons and slashes without ambiguity, and it
65    /// means a parser that assumed one form throughout gets the other wrong.
66    /// A literal parenthesis inside a URL is XML-escaped by the writer, so it
67    /// has already been unescaped by the time it arrives here -- which is why
68    /// the closing parenthesis is found from the *end*.
69    ///
70    /// The optional trailing identifier names a block within an XISF data
71    /// blocks file. The specification says it should be written in
72    /// hexadecimal, and real files use `0x`-prefixed values, but it defines
73    /// the field as an unsigned integer, so plain decimal is accepted too.
74    pub fn parse(text: &str) -> Result<Self> {
75        let text = text.trim();
76        if let Some(location) = Self::parse_parenthesised(text)? {
77            return Ok(location);
78        }
79
80        let (scheme, rest) = match text.split_once(':') {
81            Some((scheme, rest)) => (scheme, Some(rest)),
82            None => (text, None),
83        };
84
85        match scheme {
86            // The encoding lives on the child `<Data>` element, which the
87            // parser fills in once it reaches it; base64 is the default for
88            // a file that omits the attribute the schema requires.
89            "embedded" => {
90                // The grammar is the bare word. Accepting a suffix would read
91                // `embedded:hex` -- a plausible mistake, since `inline` does
92                // take an encoding -- as base64 and hand back garbage.
93                if let Some(rest) = rest {
94                    return Err(err!(
95                        BadAttribute,
96                        "an embedded location takes no parameters, got {rest:?}; \
97                         the encoding belongs on the <Data> element"
98                    ));
99                }
100                Ok(Location::Embedded { encoding: TextEncoding::Base64 })
101            }
102            "inline" => {
103                let encoding = match rest {
104                    Some("base64") => TextEncoding::Base64,
105                    Some("hex") => TextEncoding::Hex,
106                    other => {
107                        return Err(err!(
108                            BadAttribute,
109                            "inline encoding must be base64 or hex, got {:?}",
110                            other.unwrap_or("")
111                        ));
112                    }
113                };
114                Ok(Location::Inline { encoding })
115            }
116            "attachment" => {
117                let rest = rest.unwrap_or("");
118                let (position, size) = rest.split_once(':').ok_or_else(|| {
119                    err!(BadAttribute, "attachment needs position:size, got {rest:?}")
120                })?;
121                Ok(Location::Attachment {
122                    position: parse_u64(position, "attachment position")?,
123                    size: parse_u64(size, "attachment size")?,
124                })
125            }
126            other => Err(err!(BadAttribute, "unknown location scheme {other:?}")),
127        }
128    }
129
130    /// Parse the parenthesised `path(...)` and `url(...)` forms.
131    fn parse_parenthesised(text: &str) -> Result<Option<Self>> {
132        let (scheme, rest) = match text.strip_prefix("path(") {
133            Some(rest) => ("path", rest),
134            None => match text.strip_prefix("url(") {
135                Some(rest) => ("url", rest),
136                None => return Ok(None),
137            },
138        };
139
140        // From the end, so a locator containing its own parentheses -- legal,
141        // once XML-unescaped -- does not truncate here.
142        let close = rest.rfind(')').ok_or_else(|| {
143            err!(BadAttribute, "{scheme}(...) is missing its closing parenthesis")
144        })?;
145        let locator = rest[..close].trim();
146        if locator.is_empty() {
147            return Err(err!(BadAttribute, "{scheme}(...) has an empty locator"));
148        }
149
150        let index = match rest[close + 1..].trim() {
151            "" => None,
152            tail => {
153                let digits = tail
154                    .strip_prefix(':')
155                    .ok_or_else(|| err!(BadAttribute, "unexpected {tail:?} after {scheme}(...)"))?;
156                Some(parse_block_id(digits.trim())?)
157            }
158        };
159
160        Ok(Some(if scheme == "path" {
161            Location::Path { path: locator.to_string(), index }
162        } else {
163            Location::Url { url: locator.to_string(), index }
164        }))
165    }
166
167    /// Whether the bytes live outside the file that named them.
168    pub fn is_external(&self) -> bool {
169        matches!(self, Location::Path { .. } | Location::Url { .. })
170    }
171}
172
173/// The byte order a data block's multi-byte values are stored in.
174///
175/// The spec makes the attribute optional and little-endian the default, so a
176/// block with no `byteOrder` is little-endian regardless of the host. It also
177/// says the attribute is unnecessary for blocks with no multi-byte structure
178/// -- byte vectors, UTF-8 strings, 8-bit images -- and must never appear on an
179/// `ICCProfile`, whose own specification fixes it as big-endian.
180#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
181pub enum ByteOrder {
182    #[default]
183    Little,
184    Big,
185}
186
187impl ByteOrder {
188    pub fn parse(name: &str) -> Result<Self> {
189        Ok(match name {
190            "little" => ByteOrder::Little,
191            "big" => ByteOrder::Big,
192            other => return Err(err!(BadAttribute, "unknown byteOrder {other:?}")),
193        })
194    }
195
196    pub fn name(self) -> &'static str {
197        match self {
198            ByteOrder::Little => "little",
199            ByteOrder::Big => "big",
200        }
201    }
202
203    /// Whether this is the order this machine uses, in which case multi-byte
204    /// values need no swapping.
205    pub fn is_native(self) -> bool {
206        (self == ByteOrder::Little) == cfg!(target_endian = "little")
207    }
208}
209
210/// A compression codec.
211#[derive(Clone, PartialEq, Eq, Debug)]
212pub enum Codec {
213    /// RFC 1950 zlib.
214    Zlib,
215    /// LZ4 block format.
216    Lz4,
217    /// LZ4 block format, high-compression encoder. Decodes as [`Codec::Lz4`].
218    Lz4Hc,
219    /// Zstandard. Revision 1 of the specification adds `zstd` and `zstd+sh`
220    /// to the standard codecs and makes Zstandard the recommended one, so a
221    /// decoder claiming conformance must support it.
222    Zstd,
223    /// A codec this build cannot decode, kept by name.
224    ///
225    /// Revision 1 names zlib, LZ4, LZ4HC and Zstandard as the standard
226    /// codecs, but an encoder may write others. A file containing one such
227    /// block is still a readable file: its header parses, its other blocks
228    /// decode, and only *this* block fails, at the point something asks for
229    /// its bytes. That is what the specification requires -- "a decoder that
230    /// does not support the codec of a compressed data block shall treat the
231    /// block as unavailable and keep the rest of the XISF unit accessible" --
232    /// and refusing the whole file at parse time would make its metadata
233    /// unreachable for no reason.
234    Other(String),
235}
236
237impl Codec {
238    pub fn name(&self) -> &str {
239        match self {
240            Codec::Zlib => "zlib",
241            Codec::Lz4 => "lz4",
242            Codec::Lz4Hc => "lz4hc",
243            Codec::Zstd => "zstd",
244            Codec::Other(name) => name,
245        }
246    }
247
248    /// Whether this build can decode the codec.
249    pub fn is_supported(&self) -> bool {
250        !matches!(self, Codec::Other(_))
251    }
252}
253
254/// A parsed `compression` attribute.
255#[derive(Clone, PartialEq, Eq, Debug)]
256pub struct Compression {
257    pub codec: Codec,
258    /// The size the block decompresses to. The spec requires it, so a decoder
259    /// never has to guess how much to allocate.
260    pub uncompressed_size: u64,
261    /// Element size for byte unshuffling, or `None` when not shuffled.
262    ///
263    /// Shuffling stores all the first bytes of each element, then all the
264    /// second bytes, and so on, which makes the codecs' job much easier on
265    /// numeric data. An item size of 1 is a no-op and the spec forbids it as
266    /// a shuffled form.
267    pub shuffle_item_size: Option<u64>,
268    /// Compression subblocks, as `(compressed, uncompressed)` byte counts.
269    ///
270    /// Empty means the block is one compressed stream, which is the ordinary
271    /// case. When present, the stored bytes are that many *independent*
272    /// streams laid end to end, each decompressing to its own length -- so a
273    /// decoder that fed the whole buffer to one codec call would recover
274    /// only the first subblock.
275    ///
276    /// They exist because codecs have input limits -- zlib cannot compress
277    /// more than 4GiB at once -- and because splitting a block lets an
278    /// encoder compress the pieces in parallel.
279    pub subblocks: Vec<(u64, u64)>,
280}
281
282impl Compression {
283    /// Parse a `subblocks` attribute: `c1,u1:c2,u2:...:cN,uN`.
284    pub fn parse_subblocks(text: &str) -> Result<Vec<(u64, u64)>> {
285        text.split(':')
286            .map(|pair| {
287                let (compressed, uncompressed) = pair.trim().split_once(',').ok_or_else(|| {
288                    err!(BadAttribute, "a subblock must be `compressed,uncompressed`, got {pair:?}")
289                })?;
290                let number = |field: &str| -> Result<u64> {
291                    field.trim().parse::<u64>().map_err(|_| {
292                        err!(BadAttribute, "a subblock length must be an integer, got {field:?}")
293                    })
294                };
295                Ok((number(compressed)?, number(uncompressed)?))
296            })
297            .collect()
298    }
299
300    /// Parse a `compression` attribute.
301    ///
302    /// ```text
303    /// compression="zlib:30000"
304    /// compression="zlib+sh:30000:4"
305    /// ```
306    pub fn parse(text: &str) -> Result<Self> {
307        let mut fields = text.split(':');
308        let method = fields.next().unwrap_or("");
309        let (name, shuffled) = match method.strip_suffix("+sh") {
310            Some(name) => (name, true),
311            None => (method, false),
312        };
313
314        let codec = match name {
315            "zlib" => Codec::Zlib,
316            "lz4" => Codec::Lz4,
317            "lz4hc" => Codec::Lz4Hc,
318            "zstd" => Codec::Zstd,
319            other => Codec::Other(other.to_string()),
320        };
321
322        let uncompressed_size = fields
323            .next()
324            .ok_or_else(|| err!(BadAttribute, "compression needs an uncompressed size"))
325            .and_then(|s| parse_u64(s, "uncompressed size"))?;
326
327        // Nothing may follow. A `compression="zlib:30000:4"` -- a `+sh` lost
328        // from `zlib+sh:30000:4` -- otherwise parsed as unshuffled and handed
329        // back still-shuffled bytes as pixel data, with no error anywhere.
330        let mut fields = fields.peekable();
331        let shuffle_item_size = match (shuffled, fields.next()) {
332            (true, Some(item)) => {
333                let size = parse_u64(item, "shuffle item size")?;
334                // An item size of 1 is legal: the specification calls the
335                // algorithm "obviously a no-op for 8-bit data" rather than
336                // forbidding it, and an encoder that passes the sample width
337                // of a UInt8 image emits exactly that. Refusing it rejected a
338                // schema-valid file. `unshuffle` already treats it as a no-op.
339                Some(size)
340            }
341            (true, None) => {
342                return Err(err!(BadAttribute, "a shuffled block must state its item size"));
343            }
344            // Nothing may follow the uncompressed size when the codec is not
345            // shuffled. A `+sh` lost from `zlib+sh:30000:4` leaves exactly
346            // this shape, and letting it through returned still-shuffled
347            // bytes as pixel data with no error anywhere.
348            (false, Some(extra)) => {
349                return Err(err!(
350                    BadAttribute,
351                    "a compression attribute has trailing field {extra:?}; \
352                     byte shuffling is requested with a +sh suffix on the codec"
353                ));
354            }
355            (false, None) => None,
356        };
357
358        if let Some(extra) = fields.next() {
359            return Err(err!(
360                BadAttribute,
361                "a compression attribute has trailing field {extra:?}; \
362                 byte shuffling is requested with a +sh suffix on the codec"
363            ));
364        }
365
366        Ok(Compression { codec, uncompressed_size, shuffle_item_size, subblocks: Vec::new() })
367    }
368}
369
370/// A hash algorithm the spec allows for block checksums.
371#[derive(Clone, Copy, PartialEq, Eq, Debug)]
372pub enum ChecksumAlgorithm {
373    Sha1,
374    Sha256,
375    Sha512,
376    Sha3_256,
377    Sha3_512,
378}
379
380impl ChecksumAlgorithm {
381    /// The spec gives each algorithm a preferred spelling and an alternate
382    /// one (`sha-1` and `sha1`); both are accepted.
383    pub fn parse(name: &str) -> Result<Self> {
384        Ok(match name {
385            "sha-1" | "sha1" => ChecksumAlgorithm::Sha1,
386            "sha-256" | "sha256" => ChecksumAlgorithm::Sha256,
387            "sha-512" | "sha512" => ChecksumAlgorithm::Sha512,
388            "sha3-256" => ChecksumAlgorithm::Sha3_256,
389            "sha3-512" => ChecksumAlgorithm::Sha3_512,
390            other => return Err(err!(Unsupported, "unknown checksum algorithm {other:?}")),
391        })
392    }
393
394    /// The preferred spelling, which is what we emit.
395    pub fn name(self) -> &'static str {
396        match self {
397            ChecksumAlgorithm::Sha1 => "sha-1",
398            ChecksumAlgorithm::Sha256 => "sha-256",
399            ChecksumAlgorithm::Sha512 => "sha-512",
400            ChecksumAlgorithm::Sha3_256 => "sha3-256",
401            ChecksumAlgorithm::Sha3_512 => "sha3-512",
402        }
403    }
404
405    /// Digest length in bytes.
406    pub fn digest_len(self) -> usize {
407        match self {
408            ChecksumAlgorithm::Sha1 => 20,
409            ChecksumAlgorithm::Sha256 | ChecksumAlgorithm::Sha3_256 => 32,
410            ChecksumAlgorithm::Sha512 | ChecksumAlgorithm::Sha3_512 => 64,
411        }
412    }
413}
414
415/// A parsed `checksum` attribute.
416#[derive(Clone, PartialEq, Eq, Debug)]
417pub struct Checksum {
418    pub algorithm: ChecksumAlgorithm,
419    pub digest: Vec<u8>,
420}
421
422impl Checksum {
423    /// Parse a `checksum` attribute, `algorithm:hexdigest`.
424    ///
425    /// The checksum is over the block as *stored* — compressed, if it is
426    /// compressed — so it can be verified without decompressing.
427    pub fn parse(text: &str) -> Result<Self> {
428        let (name, digest) = text
429            .split_once(':')
430            .ok_or_else(|| err!(BadAttribute, "checksum needs algorithm:digest, got {text:?}"))?;
431        let algorithm = ChecksumAlgorithm::parse(name)?;
432
433        if digest.len() != algorithm.digest_len() * 2 {
434            return Err(err!(
435                BadAttribute,
436                "{} needs {} hex digits, got {}",
437                algorithm.name(),
438                algorithm.digest_len() * 2,
439                digest.len()
440            ));
441        }
442        let bytes = decode_hex(digest.as_bytes())
443            .ok_or_else(|| err!(BadAttribute, "checksum digest is not hexadecimal"))?;
444
445        Ok(Checksum { algorithm, digest: bytes })
446    }
447}
448
449/// Parse a block index identifier, which the specification says should be
450/// hexadecimal but defines as an unsigned integer.
451fn parse_block_id(text: &str) -> Result<u64> {
452    let (digits, radix) = match text.strip_prefix("0x").or_else(|| text.strip_prefix("0X")) {
453        Some(hex) => (hex, 16),
454        None => (text, 10),
455    };
456    if digits.is_empty() {
457        return Err(err!(BadAttribute, "a block identifier is empty"));
458    }
459    u64::from_str_radix(digits, radix)
460        .map_err(|_| err!(BadAttribute, "{text:?} is not a block identifier"))
461}
462
463/// The value of one hexadecimal digit.
464///
465/// Both cases are accepted although the specification says a digest "shall be
466/// encoded in Base16 using the lowercase hexadecimal digits": this is the read
467/// path, and refusing a file over the case of a digit it is about to verify
468/// anyway helps nobody. The writer emits lowercase.
469fn hex_digit(byte: u8) -> Option<u8> {
470    match byte {
471        b'0'..=b'9' => Some(byte - b'0'),
472        b'a'..=b'f' => Some(byte - b'a' + 10),
473        b'A'..=b'F' => Some(byte - b'A' + 10),
474        _ => None,
475    }
476}
477
478/// Decode an even-length run of hexadecimal digits.
479///
480/// Operates on bytes rather than on `&str`. Slicing a `&str` at `i..i + 2`
481/// assumes every character is one byte wide, and *panics* rather than erroring
482/// when one is not -- which a header is free to contain, so the panic was
483/// reachable from any file. A non-ASCII byte is not a hex digit, so it is
484/// rejected here the way any other non-digit is.
485pub(crate) fn decode_hex(digits: &[u8]) -> Option<Vec<u8>> {
486    if !digits.len().is_multiple_of(2) {
487        return None;
488    }
489    digits
490        .as_chunks::<2>()
491        .0
492        .iter()
493        .map(|pair| Some(hex_digit(pair[0])? << 4 | hex_digit(pair[1])?))
494        .collect()
495}
496
497fn parse_u64(text: &str, what: &str) -> Result<u64> {
498    text.parse::<u64>().map_err(|_| {
499        crate::error::Error::new(
500            ErrorKind::BadAttribute,
501            format!("{what} must be a decimal integer, got {text:?}"),
502        )
503    })
504}
505
506#[cfg(test)]
507mod tests {
508    use super::*;
509    use crate::ErrorKind;
510
511    #[test]
512    fn locations_parse() {
513        assert_eq!(
514            Location::parse("inline:base64").unwrap(),
515            Location::Inline { encoding: TextEncoding::Base64 }
516        );
517        assert_eq!(
518            Location::parse("inline:hex").unwrap(),
519            Location::Inline { encoding: TextEncoding::Hex }
520        );
521        assert_eq!(
522            Location::parse("embedded").unwrap(),
523            Location::Embedded { encoding: TextEncoding::Base64 }
524        );
525        assert_eq!(
526            Location::parse("attachment:9869:23042").unwrap(),
527            Location::Attachment { position: 9869, size: 23042 }
528        );
529    }
530
531    /// `path` and `url` parenthesise their locator, unlike `inline` and
532    /// `attachment`, which are colon-separated. Assuming one form throughout
533    /// gets the other wrong.
534    #[test]
535    fn path_and_url_are_parenthesised() {
536        assert_eq!(
537            Location::parse("url(file://host/blocks.xisb)").unwrap(),
538            Location::Url { url: "file://host/blocks.xisb".into(), index: None }
539        );
540        assert_eq!(
541            Location::parse("path(/data/blocks.xisb)").unwrap(),
542            Location::Path { path: "/data/blocks.xisb".into(), index: None }
543        );
544        // A URL is full of colons and slashes; none of them ends the locator.
545        assert_eq!(
546            Location::parse("url(http://host:8080/a/b?c=d&e=f)").unwrap(),
547            Location::Url { url: "http://host:8080/a/b?c=d&e=f".into(), index: None }
548        );
549    }
550
551    /// The identifier is written in hexadecimal in practice, but defined as
552    /// an unsigned integer, so both spellings are accepted.
553    #[test]
554    fn block_identifiers_may_be_hexadecimal_or_decimal() {
555        assert_eq!(
556            Location::parse("path(/d/b.xisb):0x7a73526b584c6167").unwrap(),
557            Location::Path { path: "/d/b.xisb".into(), index: Some(0x7a73_526b_584c_6167) }
558        );
559        assert_eq!(
560            Location::parse("url(file:///d/b.xisb):0").unwrap(),
561            Location::Url { url: "file:///d/b.xisb".into(), index: Some(0) }
562        );
563        assert_eq!(
564            Location::parse("path(/d/b.xisb):42").unwrap(),
565            Location::Path { path: "/d/b.xisb".into(), index: Some(42) }
566        );
567    }
568
569    /// A locator may contain parentheses of its own once XML-unescaped, which
570    /// is why the closing one is found from the end.
571    #[test]
572    fn a_locator_may_contain_parentheses() {
573        assert_eq!(
574            Location::parse("url(ftp://ftp.example.com/public/example(2016).dat)").unwrap(),
575            Location::Url {
576                url: "ftp://ftp.example.com/public/example(2016).dat".into(),
577                index: None
578            }
579        );
580    }
581
582    #[test]
583    fn bad_locations_are_rejected() {
584        for text in [
585            "",
586            "inline",
587            "inline:utf8",
588            "attachment",
589            "attachment:1",
590            "wat",
591            "path(",  // no closing parenthesis
592            "path()", // empty locator
593            "url()",
594            "path(/a):",    // an empty identifier
595            "path(/a):zz",  // not a number
596            "path(/a)junk", // trailing rubbish
597        ] {
598            assert!(Location::parse(text).is_err(), "{text:?} should not parse");
599        }
600    }
601
602    #[test]
603    fn byte_order_defaults_to_little_endian() {
604        // The spec's default, which is a property of the format rather than
605        // of the machine reading it.
606        assert_eq!(ByteOrder::default(), ByteOrder::Little);
607        assert_eq!(ByteOrder::parse("little").unwrap(), ByteOrder::Little);
608        assert_eq!(ByteOrder::parse("big").unwrap(), ByteOrder::Big);
609        assert!(ByteOrder::parse("network").is_err());
610        assert!(ByteOrder::parse("Little").is_err(), "the spelling is lower case");
611    }
612
613    #[test]
614    fn compression_parses_with_and_without_shuffling() {
615        assert_eq!(
616            Compression::parse("zlib:30000").unwrap(),
617            Compression {
618                codec: Codec::Zlib,
619                uncompressed_size: 30000,
620                shuffle_item_size: None,
621                subblocks: Vec::new(),
622            }
623        );
624        assert_eq!(
625            Compression::parse("zlib+sh:30000:4").unwrap(),
626            Compression {
627                codec: Codec::Zlib,
628                uncompressed_size: 30000,
629                shuffle_item_size: Some(4),
630                subblocks: Vec::new(),
631            }
632        );
633        assert_eq!(Compression::parse("lz4hc+sh:100:2").unwrap().codec, Codec::Lz4Hc);
634    }
635
636    #[test]
637    fn a_shuffled_block_must_say_how_wide_its_items_are() {
638        assert!(Compression::parse("zlib+sh:30000").is_err());
639    }
640
641    /// An item size of 1 is legal. The specification calls the algorithm
642    /// "obviously a no-op for 8-bit data" rather than forbidding it, and an
643    /// encoder that passes the sample width of a UInt8 image emits exactly
644    /// that -- so refusing it rejected a schema-valid file.
645    #[test]
646    fn an_item_size_of_one_is_a_no_op_rather_than_an_error() {
647        let parsed = Compression::parse("zlib+sh:30000:1").expect("item size 1 is legal");
648        assert_eq!(parsed.shuffle_item_size, Some(1));
649        // And it must behave as the no-op the spec says it is.
650        assert_eq!(crate::codec::unshuffle(&[1, 2, 3, 4, 5], 1), vec![1, 2, 3, 4, 5]);
651    }
652
653    /// A `+sh` lost from `zlib+sh:30000:4` leaves `zlib:30000:4`, which used
654    /// to parse as unshuffled and hand back still-shuffled bytes as pixel
655    /// data. Nothing may follow the uncompressed size.
656    #[test]
657    fn a_trailing_field_after_the_uncompressed_size_is_refused() {
658        assert_eq!(Compression::parse("zlib:30000").unwrap().shuffle_item_size, None);
659        for bad in ["zlib:30000:4", "zstd:100:4:9", "lz4:1:2"] {
660            let err = Compression::parse(bad).unwrap_err();
661            assert_eq!(err.kind(), ErrorKind::BadAttribute, "{bad} was accepted");
662            assert!(err.message().contains("+sh"), "{}", err.message());
663        }
664    }
665
666    /// `embedded` is the bare word. `embedded:hex` is a plausible mistake --
667    /// `inline` does take an encoding -- and reading it as base64 returns
668    /// garbage rather than an error.
669    #[test]
670    fn an_embedded_location_takes_no_parameters() {
671        assert!(Location::parse("embedded:hex").is_err());
672        assert!(Location::parse("embedded:").is_err());
673        assert!(Location::parse("embedded").is_ok());
674    }
675
676    #[test]
677    fn checksums_parse_both_spellings() {
678        let digest = "d60477d1c651b6bc42a8aa938a6132006257d76f229a2d7481db84d23dea8b96";
679        let c = Checksum::parse(&format!("sha256:{digest}")).unwrap();
680        assert_eq!(c.algorithm, ChecksumAlgorithm::Sha256);
681        assert_eq!(c.digest.len(), 32);
682        assert_eq!(c.digest[0], 0xd6);
683        assert_eq!(Checksum::parse(&format!("sha-256:{digest}")).unwrap(), c);
684    }
685
686    #[test]
687    fn a_digest_of_the_wrong_length_is_rejected() {
688        assert!(Checksum::parse("sha256:abcd").is_err());
689        assert!(Checksum::parse("sha256:zz").is_err());
690        assert!(Checksum::parse("md5:00112233445566778899aabbccddeeff").is_err());
691    }
692}