1pub const HEADER_DIR_TOKEN: &str = "@header_dir";
14
15use crate::err;
16use crate::error::{ErrorKind, Result};
17
18#[derive(Clone, PartialEq, Eq, Debug)]
20pub enum Location {
21 Inline { encoding: TextEncoding },
23 Embedded { encoding: TextEncoding },
34 Attachment { position: u64, size: u64 },
36 Path { path: String, index: Option<u64> },
38 Url { url: String, index: Option<u64> },
40}
41
42#[derive(Clone, Copy, PartialEq, Eq, Debug)]
44pub enum TextEncoding {
45 Base64,
47 Hex,
49}
50
51impl Location {
52 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 "embedded" => {
90 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 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 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 pub fn is_external(&self) -> bool {
169 matches!(self, Location::Path { .. } | Location::Url { .. })
170 }
171}
172
173#[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 pub fn is_native(self) -> bool {
206 (self == ByteOrder::Little) == cfg!(target_endian = "little")
207 }
208}
209
210#[derive(Clone, PartialEq, Eq, Debug)]
212pub enum Codec {
213 Zlib,
215 Lz4,
217 Lz4Hc,
219 Zstd,
223 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 pub fn is_supported(&self) -> bool {
250 !matches!(self, Codec::Other(_))
251 }
252}
253
254#[derive(Clone, PartialEq, Eq, Debug)]
256pub struct Compression {
257 pub codec: Codec,
258 pub uncompressed_size: u64,
261 pub shuffle_item_size: Option<u64>,
268 pub subblocks: Vec<(u64, u64)>,
280}
281
282impl Compression {
283 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 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 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 Some(size)
340 }
341 (true, None) => {
342 return Err(err!(BadAttribute, "a shuffled block must state its item size"));
343 }
344 (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#[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 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 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 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#[derive(Clone, PartialEq, Eq, Debug)]
417pub struct Checksum {
418 pub algorithm: ChecksumAlgorithm,
419 pub digest: Vec<u8>,
420}
421
422impl Checksum {
423 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
449fn 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
463fn 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
478pub(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 #[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 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 #[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 #[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(", "path()", "url()",
594 "path(/a):", "path(/a):zz", "path(/a)junk", ] {
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 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 #[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 assert_eq!(crate::codec::unshuffle(&[1, 2, 3, 4, 5], 1), vec![1, 2, 3, 4, 5]);
651 }
652
653 #[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 #[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}