1use 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#[derive(Clone, Debug, Default)]
32pub struct BlockOptions {
33 pub compression: Option<CompressionRequest>,
35 pub checksum: Option<ChecksumAlgorithm>,
37}
38
39#[derive(Clone, Copy, PartialEq, Eq, Debug)]
41pub struct CompressionRequest {
42 pub codec: Codec2,
43 pub shuffle_item_size: Option<u64>,
48}
49
50#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
58pub enum Codec2 {
59 #[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#[derive(Clone, Copy, Debug)]
82enum Addressing<'a> {
83 Attached { data_at: usize },
87 Distributed { blocks_file: &'a str },
91}
92
93#[derive(Clone, Debug)]
95pub struct DistributedUnit {
96 pub header: Vec<u8>,
98 pub blocks: Vec<u8>,
100 pub blocks_file_name: String,
102}
103
104#[derive(Clone, Debug)]
111pub struct PendingImage {
112 pub image: Image,
113 pub data: Vec<u8>,
114 pub options: BlockOptions,
115 pub resolution: Option<Resolution>,
117 pub rgb_working_space: Option<RgbWorkingSpace>,
119 pub display_function: Option<DisplayFunction>,
121 pub color_filter_array: Option<ColorFilterArray>,
123 pub icc_profile: Option<Vec<u8>>,
125 pub thumbnail: Option<PendingThumbnail>,
127 pub fits_keywords: Vec<FitsKeyword>,
129 pub tables: Vec<Table>,
131}
132
133#[derive(Clone, Debug)]
135pub struct PendingThumbnail {
136 pub image: Image,
137 pub data: Vec<u8>,
138 pub options: BlockOptions,
139}
140
141#[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 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 pub fn with_icc_profile(mut self, profile: Vec<u8>) -> Self {
202 self.icc_profile = Some(profile);
203 self
204 }
205
206 pub fn with_thumbnail(mut self, thumbnail: PendingThumbnail) -> Self {
212 self.thumbnail = Some(thumbnail);
213 self
214 }
215
216 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#[derive(Clone, Debug, Default)]
245pub struct Writer {
246 images: Vec<PendingImage>,
247 metadata: Vec<(String, String, String)>,
249 creator: Option<String>,
250 creation_time: Option<String>,
253 tables: Vec<Table>,
256}
257
258impl Writer {
259 pub fn new() -> Self {
260 Self::default()
261 }
262
263 pub fn with_creator(mut self, creator: impl Into<String>) -> Self {
266 self.creator = Some(creator.into());
267 self
268 }
269
270 pub fn with_creation_time(mut self, instant: impl Into<String>) -> Self {
277 self.creation_time = Some(instant.into());
278 self
279 }
280
281 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 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 pub fn add_table(&mut self, table: Table) -> Result<()> {
318 check_table(&table)?;
319 self.tables.push(table);
320 Ok(())
321 }
322
323 pub fn add_image(&mut self, pending: PendingImage) -> Result<()> {
325 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 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 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 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 pub fn to_bytes(&self) -> Result<Vec<u8>> {
438 let stored = self.prepare_blocks()?;
443
444 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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
854fn 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
868fn 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
881fn 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
900fn 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
914fn codec_input_limit(codec: Codec2) -> u64 {
920 match codec {
921 Codec2::Zlib => u64::from(u32::MAX),
923 Codec2::Lz4 => 0x7E00_0000,
925 Codec2::Zstd => u64::MAX,
929 }
930}
931
932fn 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 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
972fn 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 xml.push_str(&format!(
984 " rows=\"{}\" columns=\"{}\">",
985 table.rows.len(),
986 table.structure.fields.len()
987 ));
988
989 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 (None, None) => xml.push_str("<Cell/>"),
1025 }
1026 }
1027 xml.push_str("</Row>");
1028 }
1029 xml.push_str("</Table>");
1030}
1031
1032fn 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
1064fn 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
1093fn join_numbers(values: &[f64]) -> String {
1095 values.iter().map(f64::to_string).collect::<Vec<_>>().join(":")
1096}
1097
1098struct StoredBlocks {
1100 blocks: Vec<StoredBlock>,
1102 owners: Vec<ImageBlocks>,
1104}
1105
1106struct ImageBlocks {
1108 data: usize,
1109 icc: Option<usize>,
1110 thumbnail: Option<usize>,
1111}
1112
1113fn block_id(index: usize) -> u64 {
1118 index as u64 + 1
1119}
1120
1121struct 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 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 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 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 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#[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 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
1226fn 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
1249fn 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 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#[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 fn serialize(self) -> (&'static str, String) {
1300 match self {
1301 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 ScalarProperty::Float32(v) => ("Float32", v.to_string()),
1316 ScalarProperty::Float64(v) => ("Float64", v.to_string()),
1317 }
1318 }
1319}
1320
1321fn with_embedded_profile_flag(profile: &[u8]) -> Result<Vec<u8>> {
1334 const HEADER_LEN: usize = 128;
1336 const FLAGS_AT: usize = 44;
1338 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
1357fn 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
1367fn 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("&"),
1373 '<' => out.push_str("<"),
1374 '>' => out.push_str(">"),
1375 '"' => out.push_str("""),
1376 '\'' => out.push_str("'"),
1377 _ => out.push(c),
1378 }
1379 }
1380 out
1381}
1382
1383fn 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("&"),
1390 '<' => out.push_str("<"),
1391 '>' => out.push_str(">"),
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 fn writable_compressions() -> Vec<Option<CompressionRequest>> {
1450 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 #[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 #[cfg(feature = "zlib")]
1541 #[test]
1542 fn incompressible_data_is_stored_plain() {
1543 let image = image(4, 4, 1, SampleFormat::UInt8);
1544 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 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 #[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"), (951_782_400, "2000-02-29T00:00:00Z"), (4_107_456_000, "2100-02-28T00:00:00Z"), (4_107_542_400, "2100-03-01T00:00:00Z"), (1_418_128_695, "2014-12-09T12:38:15Z"), ] {
1627 assert_eq!(iso8601_from_unix(seconds), expected, "for {seconds}");
1628 }
1629 }
1630}