use crate::block::{ChecksumAlgorithm, Codec, Compression, HEADER_DIR_TOKEN};
use crate::codec;
use crate::err;
use crate::error::Result;
use crate::image::{ColorFilterArray, DisplayFunction, Gamma, Image, Resolution, RgbWorkingSpace};
use crate::layout::{PREAMBLE_LEN, SIGNATURE};
use crate::reader::{checksum_of, digest_hex};
use crate::table::Table;
#[derive(Clone, Debug, Default)]
pub struct BlockOptions {
pub compression: Option<CompressionRequest>,
pub checksum: Option<ChecksumAlgorithm>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct CompressionRequest {
pub codec: Codec2,
pub shuffle_item_size: Option<u64>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Codec2 {
#[default]
Zstd,
Zlib,
Lz4,
}
impl Codec2 {
fn as_codec(self) -> Codec {
match self {
Codec2::Zstd => Codec::Zstd,
Codec2::Zlib => Codec::Zlib,
Codec2::Lz4 => Codec::Lz4,
}
}
}
#[derive(Clone, Copy, Debug)]
enum Addressing<'a> {
Attached { data_at: usize },
Distributed { blocks_file: &'a str },
}
#[derive(Clone, Debug)]
pub struct DistributedUnit {
pub header: Vec<u8>,
pub blocks: Vec<u8>,
pub blocks_file_name: String,
}
#[derive(Clone, Debug)]
pub struct PendingImage {
pub image: Image,
pub data: Vec<u8>,
pub options: BlockOptions,
pub resolution: Option<Resolution>,
pub rgb_working_space: Option<RgbWorkingSpace>,
pub display_function: Option<DisplayFunction>,
pub color_filter_array: Option<ColorFilterArray>,
pub icc_profile: Option<Vec<u8>>,
pub thumbnail: Option<PendingThumbnail>,
pub fits_keywords: Vec<FitsKeyword>,
pub tables: Vec<Table>,
}
#[derive(Clone, Debug)]
pub struct PendingThumbnail {
pub image: Image,
pub data: Vec<u8>,
pub options: BlockOptions,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FitsKeyword {
pub name: String,
pub value: String,
pub comment: String,
}
impl PendingImage {
pub fn new(image: Image, data: Vec<u8>, options: BlockOptions) -> Self {
PendingImage {
image,
data,
options,
resolution: None,
rgb_working_space: None,
display_function: None,
color_filter_array: None,
icc_profile: None,
thumbnail: None,
fits_keywords: Vec::new(),
tables: Vec::new(),
}
}
pub fn with_resolution(mut self, resolution: Resolution) -> Self {
self.resolution = Some(resolution);
self
}
pub fn with_rgb_working_space(mut self, space: RgbWorkingSpace) -> Self {
self.rgb_working_space = Some(space);
self
}
pub fn with_display_function(mut self, function: DisplayFunction) -> Self {
self.display_function = Some(function);
self
}
pub fn with_color_filter_array(mut self, cfa: ColorFilterArray) -> Self {
self.color_filter_array = Some(cfa);
self
}
pub fn with_icc_profile(mut self, profile: Vec<u8>) -> Self {
self.icc_profile = Some(profile);
self
}
pub fn with_thumbnail(mut self, thumbnail: PendingThumbnail) -> Self {
self.thumbnail = Some(thumbnail);
self
}
pub fn with_table(mut self, table: Table) -> Self {
self.tables.push(table);
self
}
pub fn with_fits_keyword(
mut self,
name: impl Into<String>,
value: impl Into<String>,
comment: impl Into<String>,
) -> Self {
self.fits_keywords.push(FitsKeyword {
name: name.into(),
value: value.into(),
comment: comment.into(),
});
self
}
}
impl PendingThumbnail {
pub fn new(image: Image, data: Vec<u8>, options: BlockOptions) -> Self {
PendingThumbnail { image, data, options }
}
}
#[derive(Clone, Debug, Default)]
pub struct Writer {
images: Vec<PendingImage>,
metadata: Vec<(String, String, String)>,
creator: Option<String>,
creation_time: Option<String>,
tables: Vec<Table>,
}
impl Writer {
pub fn new() -> Self {
Self::default()
}
pub fn with_creator(mut self, creator: impl Into<String>) -> Self {
self.creator = Some(creator.into());
self
}
pub fn with_creation_time(mut self, instant: impl Into<String>) -> Self {
self.creation_time = Some(instant.into());
self
}
pub fn add_metadata(&mut self, id: impl Into<String>, value: impl Into<String>) -> Result<()> {
let id = id.into();
check_property_id(&id)?;
self.metadata.push((id, "String".into(), value.into()));
Ok(())
}
pub fn add_scalar_property(
&mut self,
id: impl Into<String>,
value: ScalarProperty,
) -> Result<()> {
let id = id.into();
check_property_id(&id)?;
let (kind, text) = value.serialize();
self.metadata.push((id, kind.into(), text));
Ok(())
}
pub fn add_table(&mut self, table: Table) -> Result<()> {
check_table(&table)?;
self.tables.push(table);
Ok(())
}
pub fn add_image(&mut self, pending: PendingImage) -> Result<()> {
if let Some(id) = &pending.image.id
&& self.images.iter().any(|existing| existing.image.id.as_ref() == Some(id))
{
return Err(err!(
InvalidArgument,
"two images share the id {id:?}, which must be unique within the unit"
));
}
if pending.image.sample_format.requires_bounds() && pending.image.bounds.is_none() {
return Err(err!(
InvalidArgument,
"a {} image must declare its bounds; there is no default \
representable range for floating point real pixel data",
pending.image.sample_format.name()
));
}
if let Some(id) = &pending.image.id {
check_image_id(id)?;
}
if let Some(uuid) = &pending.image.uuid {
check_uuid(uuid)?;
}
let expected = pending
.image
.data_size()
.ok_or_else(|| err!(InvalidArgument, "the image's geometry overflows"))?;
if pending.data.len() as u64 != expected {
return Err(err!(
InvalidArgument,
"the image declares {expected} bytes of pixel data but {} were given",
pending.data.len()
));
}
if let Some(thumbnail) = &pending.thumbnail {
let expected = thumbnail
.image
.data_size()
.ok_or_else(|| err!(InvalidArgument, "the thumbnail's geometry overflows"))?;
if thumbnail.data.len() as u64 != expected {
return Err(err!(
InvalidArgument,
"the thumbnail declares {expected} bytes but {} were given",
thumbnail.data.len()
));
}
if thumbnail.image.dimensions.len() != 2 {
return Err(err!(
InvalidArgument,
"a thumbnail must be two-dimensional, got {} dimension(s)",
thumbnail.image.dimensions.len()
));
}
if !matches!(
thumbnail.image.sample_format,
crate::image::SampleFormat::UInt8 | crate::image::SampleFormat::UInt16
) {
return Err(err!(
InvalidArgument,
"a thumbnail must be UInt8 or UInt16, got {}",
thumbnail.image.sample_format.name()
));
}
if thumbnail.image.bounds.is_some() {
return Err(err!(
InvalidArgument,
"a thumbnail must not declare bounds; its range is its sample format's"
));
}
if !matches!(
thumbnail.image.color_space,
crate::image::ColorSpace::Gray | crate::image::ColorSpace::Rgb
) {
return Err(err!(
InvalidArgument,
"a thumbnail must be grayscale or RGB, got {}",
thumbnail.image.color_space.name()
));
}
}
for keyword in &pending.fits_keywords {
check_fits_name(&keyword.name)?;
}
for table in &pending.tables {
check_table(table)?;
}
self.images.push(pending);
Ok(())
}
pub fn to_bytes(&self) -> Result<Vec<u8>> {
let stored = self.prepare_blocks()?;
let mut assumed =
self.render(&stored, Addressing::Attached { data_at: PREAMBLE_LEN })?.len();
let header = loop {
let header =
self.render(&stored, Addressing::Attached { data_at: PREAMBLE_LEN + assumed })?;
if header.len() == assumed {
break header;
}
assumed = header.len();
};
let mut out = Vec::with_capacity(
PREAMBLE_LEN
+ header.len()
+ stored.blocks.iter().map(|b| b.bytes.len()).sum::<usize>(),
);
out.extend_from_slice(SIGNATURE);
out.extend_from_slice(
&(u32::try_from(header.len()).map_err(|_| {
err!(Unsupported, "the header is larger than the format's 32-bit length field")
})?)
.to_le_bytes(),
);
out.extend_from_slice(&[0; 4]);
out.extend_from_slice(header.as_bytes());
for block in &stored.blocks {
out.extend_from_slice(&block.bytes);
}
Ok(out)
}
pub fn to_distributed(&self, blocks_file_name: &str) -> Result<DistributedUnit> {
if blocks_file_name.is_empty() || blocks_file_name.contains('/') {
return Err(err!(
InvalidArgument,
"the blocks file name must be a plain file name, got {blocks_file_name:?}"
));
}
let stored = self.prepare_blocks()?;
let blocks: Vec<crate::distributed::PendingBlock> = stored
.blocks
.iter()
.enumerate()
.map(|(index, block)| crate::distributed::PendingBlock {
id: block_id(index),
bytes: block.bytes.clone(),
uncompressed_length: block
.compression
.as_ref()
.map(|compression| compression.uncompressed_size),
})
.collect();
let header =
self.render(&stored, Addressing::Distributed { blocks_file: blocks_file_name })?;
Ok(DistributedUnit {
header: header.into_bytes(),
blocks: crate::distributed::write_blocks_file(&blocks)?,
blocks_file_name: blocks_file_name.to_string(),
})
}
fn prepare_blocks(&self) -> Result<StoredBlocks> {
let mut blocks = Vec::new();
let mut owners = Vec::with_capacity(self.images.len());
let mut push = |data: &[u8], options: &BlockOptions| -> Result<usize> {
blocks.push(StoredBlock::prepare(data, options)?);
Ok(blocks.len() - 1)
};
for pending in &self.images {
let data = push(&pending.data, &pending.options)?;
let icc = match &pending.icc_profile {
None => None,
Some(profile) => {
Some(push(&with_embedded_profile_flag(profile)?, &BlockOptions::default())?)
}
};
let thumbnail = match &pending.thumbnail {
None => None,
Some(thumb) => Some(push(&thumb.data, &thumb.options)?),
};
owners.push(ImageBlocks { data, icc, thumbnail });
}
Ok(StoredBlocks { blocks, owners })
}
fn render(&self, stored: &StoredBlocks, addressing: Addressing<'_>) -> Result<String> {
let mut xml = String::from(r#"<?xml version="1.0" encoding="UTF-8"?>"#);
xml.push_str(r#"<xisf version="1.0" xmlns="http://www.pixinsight.com/xisf" "#);
xml.push_str(r#"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" "#);
xml.push_str(
r#"xsi:schemaLocation="http://www.pixinsight.com/xisf http://pixinsight.com/xisf/xisf-1.0.xsd">"#,
);
let base = match addressing {
Addressing::Attached { data_at } => data_at,
Addressing::Distributed { .. } => 0,
};
let mut positions = Vec::with_capacity(stored.blocks.len());
let mut cursor = base;
for block in &stored.blocks {
positions.push(cursor);
cursor += block.bytes.len();
}
let locate = |index: usize| -> String {
let block = &stored.blocks[index];
match addressing {
Addressing::Attached { .. } => {
format!("attachment:{}:{}", positions[index], block.bytes.len())
}
Addressing::Distributed { blocks_file } => {
format!(
"path({HEADER_DIR_TOKEN}/{}):{:#x}",
escape_attr(blocks_file),
block_id(index)
)
}
}
};
for (pending, owned) in self.images.iter().zip(&stored.owners) {
let block = &stored.blocks[owned.data];
let image = &pending.image;
let mut geometry: Vec<String> = image.dimensions.iter().map(u64::to_string).collect();
geometry.push(image.channels.to_string());
xml.push_str("<Image geometry=\"");
xml.push_str(&geometry.join(":"));
xml.push_str("\" sampleFormat=\"");
xml.push_str(image.sample_format.name());
xml.push_str("\" colorSpace=\"");
xml.push_str(image.color_space.name());
xml.push_str("\" pixelStorage=\"");
xml.push_str(image.pixel_storage.name());
xml.push('"');
if let Some(bounds) = image.bounds {
xml.push_str(&format!(" bounds=\"{}:{}\"", bounds.low, bounds.high));
}
if let Some(id) = &image.id {
xml.push_str(&format!(" id=\"{}\"", escape_attr(id)));
}
if let Some(kind) = &image.image_type {
xml.push_str(&format!(" imageType=\"{}\"", escape_attr(kind.name())));
}
if let Some(uuid) = &image.uuid {
xml.push_str(&format!(" uuid=\"{}\"", escape_attr(uuid)));
}
if let Some(offset) = image.offset {
xml.push_str(&format!(" offset=\"{offset}\""));
}
if let Some(orientation) = image.orientation {
xml.push_str(&format!(" orientation=\"{}\"", orientation.to_attribute()));
}
push_block_attrs(&mut xml, block);
xml.push_str(&format!(" location=\"{}\">", locate(owned.data)));
for keyword in &pending.fits_keywords {
xml.push_str(&format!(
"<FITSKeyword name=\"{}\" value=\"{}\" comment=\"{}\"/>",
escape_attr(&keyword.name),
escape_attr(&keyword.value),
escape_attr(&keyword.comment)
));
}
if let Some(resolution) = &pending.resolution {
xml.push_str(&format!(
"<Resolution horizontal=\"{}\" vertical=\"{}\" unit=\"{}\"/>",
resolution.horizontal,
resolution.vertical,
resolution.unit.name()
));
}
if let Some(space) = &pending.rgb_working_space {
let luminance =
RgbWorkingSpace::derive_luminance(space.x, space.y).ok_or_else(|| {
err!(
InvalidArgument,
"the RGB working space primaries x={:?} y={:?} are degenerate, \
so no luminance coefficients follow from them",
space.x,
space.y
)
})?;
xml.push_str(&format!(
"<RGBWorkingSpace x=\"{}\" y=\"{}\" Y=\"{}\" gamma=\"{}\"",
join_numbers(&space.x),
join_numbers(&space.y),
join_numbers(&luminance),
match space.gamma {
Gamma::Srgb => "sRGB".to_string(),
Gamma::Exponent(exponent) => exponent.to_string(),
}
));
if let Some(name) = &space.name {
xml.push_str(&format!(" name=\"{}\"", escape_attr(name)));
}
xml.push_str("/>");
}
if let Some(function) = &pending.display_function {
xml.push_str(&format!(
"<DisplayFunction m=\"{}\" s=\"{}\" h=\"{}\" l=\"{}\" r=\"{}\"",
join_numbers(&function.midtones),
join_numbers(&function.shadows),
join_numbers(&function.highlights),
join_numbers(&function.low_range),
join_numbers(&function.high_range)
));
if let Some(name) = &function.name {
xml.push_str(&format!(" name=\"{}\"", escape_attr(name)));
}
xml.push_str("/>");
}
if let Some(cfa) = &pending.color_filter_array {
xml.push_str(&format!(
"<ColorFilterArray pattern=\"{}\" width=\"{}\" height=\"{}\"",
cfa.pattern_string(),
cfa.width,
cfa.height
));
if let Some(name) = &cfa.name {
xml.push_str(&format!(" name=\"{}\"", escape_attr(name)));
}
xml.push_str("/>");
}
if let Some(index) = owned.icc {
xml.push_str("<ICCProfile");
push_block_attrs(&mut xml, &stored.blocks[index]);
xml.push_str(&format!(" location=\"{}\"/>", locate(index)));
}
if let Some(index) = owned.thumbnail {
let thumb = &pending.thumbnail.as_ref().expect("a thumbnail block has one").image;
let mut geometry: Vec<String> =
thumb.dimensions.iter().map(u64::to_string).collect();
geometry.push(thumb.channels.to_string());
xml.push_str(&format!(
"<Thumbnail geometry=\"{}\" sampleFormat=\"{}\" colorSpace=\"{}\" \
pixelStorage=\"{}\"",
geometry.join(":"),
thumb.sample_format.name(),
thumb.color_space.name(),
thumb.pixel_storage.name()
));
if let Some(id) = &thumb.id {
xml.push_str(&format!(" id=\"{}\"", escape_attr(id)));
}
if let Some(uuid) = &thumb.uuid {
xml.push_str(&format!(" uuid=\"{}\"", escape_attr(uuid)));
}
if let Some(kind) = &thumb.image_type {
xml.push_str(&format!(" imageType=\"{}\"", escape_attr(kind.name())));
}
if let Some(offset) = thumb.offset {
xml.push_str(&format!(" offset=\"{offset}\""));
}
if let Some(orientation) = thumb.orientation
&& !orientation.is_identity()
{
xml.push_str(&format!(" orientation=\"{}\"", orientation.to_attribute()));
}
push_block_attrs(&mut xml, &stored.blocks[index]);
xml.push_str(&format!(" location=\"{}\"/>", locate(index)));
}
for table in &pending.tables {
push_table(&mut xml, table);
}
xml.push_str("</Image>");
}
for table in &self.tables {
push_table(&mut xml, table);
}
xml.push_str("<Metadata>");
xml.push_str(&format!(
"<Property id=\"XISF:CreationTime\" type=\"TimePoint\" value=\"{}\"/>",
match &self.creation_time {
Some(instant) => escape_attr(instant),
None => escape_attr(&now_iso8601()),
}
));
let mut algorithms: Vec<&str> = Vec::new();
let mut codecs: Vec<&str> = Vec::new();
for block in &stored.blocks {
if let Some(checksum) = &block.checksum
&& !algorithms.contains(&checksum.algorithm.name())
{
algorithms.push(checksum.algorithm.name());
}
if let Some(compression) = &block.compression
&& !codecs.contains(&compression.codec.name())
{
codecs.push(compression.codec.name());
}
}
if !algorithms.is_empty() {
xml.push_str(&format!(
"<Property id=\"XISF:ChecksumAlgorithms\" type=\"String\">{}</Property>",
escape_text(&algorithms.join(","))
));
}
if !codecs.is_empty() {
xml.push_str(&format!(
"<Property id=\"XISF:CompressionCodecs\" type=\"String\">{}</Property>",
escape_text(&codecs.join(","))
));
}
for (id, kind, value) in &self.metadata {
if kind == "String" {
xml.push_str(&format!(
"<Property id=\"{}\" type=\"String\">{}</Property>",
escape_attr(id),
escape_text(value)
));
} else {
xml.push_str(&format!(
"<Property id=\"{}\" type=\"{}\" value=\"{}\"/>",
escape_attr(id),
escape_attr(kind),
escape_attr(value)
));
}
}
xml.push_str(&format!(
"<Property id=\"XISF:CreatorApplication\" type=\"String\">{}</Property>",
escape_text(self.creator.as_deref().unwrap_or("xisf-rs"))
));
xml.push_str("</Metadata>");
xml.push_str("</xisf>");
Ok(xml)
}
}
fn now_iso8601() -> String {
let seconds = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_secs());
iso8601_from_unix(seconds)
}
fn iso8601_from_unix(seconds: u64) -> String {
let days = (seconds / 86_400) as i64;
let time = seconds % 86_400;
let (year, month, day) = civil_from_days(days);
format!(
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
time / 3600,
(time % 3600) / 60,
time % 60
)
}
fn civil_from_days(days: i64) -> (i64, u32, u32) {
let shifted = days + 719_468;
let era = shifted.div_euclid(146_097);
let day_of_era = shifted.rem_euclid(146_097);
let year_of_era =
(day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let year = year_of_era + era * 400;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let shifted_month = (5 * day_of_year + 2) / 153;
let day = (day_of_year - (153 * shifted_month + 2) / 5 + 1) as u32;
let month = if shifted_month < 10 { shifted_month + 3 } else { shifted_month - 9 } as u32;
(if month <= 2 { year + 1 } else { year }, month, day)
}
fn push_block_attrs(xml: &mut String, block: &StoredBlock) {
if let Some(compression) = &block.compression {
xml.push_str(&format!(" compression=\"{}\"", compression_attr(compression)));
}
if let Some(checksum) = &block.checksum {
xml.push_str(&format!(
" checksum=\"{}:{}\"",
checksum.algorithm.name(),
digest_hex(&checksum.digest)
));
}
}
fn codec_input_limit(codec: Codec2) -> u64 {
match codec {
Codec2::Zlib => u64::from(u32::MAX),
Codec2::Lz4 => 0x7E00_0000,
Codec2::Zstd => u64::MAX,
}
}
fn check_table(table: &Table) -> Result<()> {
check_property_id(&table.id)?;
if table.structure.fields.is_empty() {
return Err(err!(InvalidArgument, "table {:?} has no fields", table.id));
}
for field in &table.structure.fields {
check_property_id(&field.id)?;
}
for (n, row) in table.rows.iter().enumerate() {
if row.len() != table.structure.fields.len() {
return Err(err!(
InvalidArgument,
"table {:?} row {n} has {} cells but its structure declares {} fields",
table.id,
row.len(),
table.structure.fields.len()
));
}
for cell in row {
if cell.data.location.is_some() {
return Err(err!(
Unsupported,
"table {:?} has a cell stored in a data block, which cannot be written yet",
table.id
));
}
}
}
Ok(())
}
fn push_table(xml: &mut String, table: &Table) {
xml.push_str(&format!("<Table id=\"{}\"", escape_attr(&table.id)));
if let Some(caption) = &table.caption {
xml.push_str(&format!(" caption=\"{}\"", escape_attr(caption)));
}
if let Some(comment) = &table.comment {
xml.push_str(&format!(" comment=\"{}\"", escape_attr(comment)));
}
xml.push_str(&format!(
" rows=\"{}\" columns=\"{}\">",
table.rows.len(),
table.structure.fields.len()
));
xml.push_str("<Structure>");
for field in &table.structure.fields {
xml.push_str(&format!(
"<Field id=\"{}\" type=\"{}\"",
escape_attr(&field.id),
escape_attr(&field.kind.name())
));
if let Some(format) = &field.format {
xml.push_str(&format!(" format=\"{}\"", escape_attr(format)));
}
if let Some(header) = &field.header {
xml.push_str(&format!(" header=\"{}\"", escape_attr(header)));
}
xml.push_str("/>");
}
xml.push_str("</Structure>");
for row in &table.rows {
xml.push_str("<Row>");
for cell in row {
match (&cell.value, &cell.data.text) {
(Some(value), _) => {
xml.push_str(&format!("<Cell value=\"{}\"/>", escape_attr(value)));
}
(None, Some(text)) => {
xml.push_str(&format!("<Cell>{}</Cell>", escape_text(text)));
}
(None, None) => xml.push_str("<Cell/>"),
}
}
xml.push_str("</Row>");
}
xml.push_str("</Table>");
}
fn check_property_id(id: &str) -> Result<()> {
let valid = !id.is_empty()
&& id.split(':').all(|segment| {
let mut chars = segment.chars();
chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
});
if !valid {
return Err(err!(
InvalidArgument,
"{id:?} is not a valid property identifier: one or more colon-separated \
segments, each beginning with a letter or underscore"
));
}
Ok(())
}
fn check_fits_name(name: &str) -> Result<()> {
if name.len() > 8 {
return Err(err!(
InvalidArgument,
"the FITS keyword {name:?} is {} characters; the limit is 8",
name.len()
));
}
if let Some(bad) = name
.chars()
.find(|c| !(c.is_ascii_digit() || c.is_ascii_uppercase() || *c == '_' || *c == '-'))
{
return Err(err!(
InvalidArgument,
"the FITS keyword {name:?} contains {bad:?}; only A-Z, 0-9, underscore and \
hyphen are permitted"
));
}
Ok(())
}
fn join_numbers(values: &[f64]) -> String {
values.iter().map(f64::to_string).collect::<Vec<_>>().join(":")
}
struct StoredBlocks {
blocks: Vec<StoredBlock>,
owners: Vec<ImageBlocks>,
}
struct ImageBlocks {
data: usize,
icc: Option<usize>,
thumbnail: Option<usize>,
}
fn block_id(index: usize) -> u64 {
index as u64 + 1
}
struct StoredBlock {
bytes: Vec<u8>,
compression: Option<Compression>,
checksum: Option<crate::block::Checksum>,
}
impl StoredBlock {
fn prepare(data: &[u8], options: &BlockOptions) -> Result<Self> {
let (bytes, compression) = match &options.compression {
None => (data.to_vec(), None),
Some(request) => {
let uncompressed_size = data.len() as u64;
let item_size = request.shuffle_item_size.filter(|item| *item > 1);
let staged = match item_size {
None => data.to_vec(),
Some(item) => {
let item = usize::try_from(item)
.map_err(|_| err!(InvalidArgument, "shuffle item size is unusable"))?;
codec::shuffle(data, item)
}
};
let limit = codec_input_limit(request.codec);
if staged.len() as u64 > limit {
return Err(err!(
Unsupported,
"a {}-byte block exceeds the {} input limit of {limit} bytes; \
it would have to be split into compression subblocks, which this \
writer does not do",
staged.len(),
request.codec.as_codec().name()
));
}
let compressed = compress(&staged, request.codec)?;
if compressed.len() >= data.len() {
(data.to_vec(), None)
} else {
(
compressed,
Some(Compression {
subblocks: Vec::new(),
codec: request.codec.as_codec(),
uncompressed_size,
shuffle_item_size: item_size,
}),
)
}
}
};
let checksum = match options.checksum {
None => None,
Some(algorithm) => Some(checksum_of(&bytes, algorithm)?),
};
Ok(StoredBlock { bytes, compression, checksum })
}
}
#[cfg_attr(not(any(feature = "zlib", feature = "lz4")), allow(unused_variables))]
fn compress(data: &[u8], codec: Codec2) -> Result<Vec<u8>> {
match codec {
#[cfg(feature = "zlib")]
Codec2::Zlib => {
use std::io::Write;
let mut encoder =
flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
encoder.write_all(data).map_err(|e| err!(Compression, "zlib: {e}"))?;
encoder.finish().map_err(|e| err!(Compression, "zlib: {e}"))
}
#[cfg(feature = "lz4")]
Codec2::Lz4 => Ok(lz4_flex::block::compress(data)),
Codec2::Zstd => zrip::compress(data, 3).map_err(|e| err!(Compression, "zstd: {e}")),
#[allow(unreachable_patterns)]
other => Err(err!(Unsupported, "cannot write {:?} blocks in this build", other)),
}
}
fn check_image_id(id: &str) -> Result<()> {
let mut chars = id.chars();
let valid = match chars.next() {
Some(first) if first == '_' || first.is_ascii_alphabetic() => {
chars.all(|c| c == '_' || c.is_ascii_alphanumeric())
}
_ => false,
};
if !valid {
return Err(err!(
InvalidArgument,
"{id:?} is not a valid image identifier; it must match [_a-zA-Z][_a-zA-Z0-9]*"
));
}
Ok(())
}
fn check_uuid(uuid: &str) -> Result<()> {
let groups: Vec<&str> = uuid.split('-').collect();
let shaped = groups.len() == 5
&& [8usize, 4, 4, 4, 12].iter().zip(&groups).all(|(want, group)| {
group.len() == *want && group.chars().all(|c| c.is_ascii_hexdigit())
});
if !shaped {
return Err(err!(
InvalidArgument,
"{uuid:?} is not a UUID in canonical 8-4-4-4-12 hexadecimal form"
));
}
if !groups[2].starts_with('4') {
return Err(err!(
InvalidArgument,
"{uuid:?} is not a version 4 UUID, which the specification requires"
));
}
Ok(())
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum ScalarProperty {
Boolean(bool),
Int8(i8),
UInt8(u8),
Int16(i16),
UInt16(u16),
Int32(i32),
UInt32(u32),
Int64(i64),
UInt64(u64),
Float32(f32),
Float64(f64),
}
impl ScalarProperty {
fn serialize(self) -> (&'static str, String) {
match self {
ScalarProperty::Boolean(v) => ("Boolean", v.to_string()),
ScalarProperty::Int8(v) => ("Int8", v.to_string()),
ScalarProperty::UInt8(v) => ("UInt8", v.to_string()),
ScalarProperty::Int16(v) => ("Int16", v.to_string()),
ScalarProperty::UInt16(v) => ("UInt16", v.to_string()),
ScalarProperty::Int32(v) => ("Int32", v.to_string()),
ScalarProperty::UInt32(v) => ("UInt32", v.to_string()),
ScalarProperty::Int64(v) => ("Int64", v.to_string()),
ScalarProperty::UInt64(v) => ("UInt64", v.to_string()),
ScalarProperty::Float32(v) => ("Float32", v.to_string()),
ScalarProperty::Float64(v) => ("Float64", v.to_string()),
}
}
}
fn with_embedded_profile_flag(profile: &[u8]) -> Result<Vec<u8>> {
const HEADER_LEN: usize = 128;
const FLAGS_AT: usize = 44;
const EMBEDDED: u32 = 1;
if profile.len() < HEADER_LEN {
return Err(err!(
InvalidArgument,
"an ICC profile needs at least {HEADER_LEN} bytes of header, this has {}",
profile.len()
));
}
let mut out = profile.to_vec();
let flags = u32::from_be_bytes(
out[FLAGS_AT..FLAGS_AT + 4].try_into().expect("four bytes inside the header"),
);
out[FLAGS_AT..FLAGS_AT + 4].copy_from_slice(&(flags | EMBEDDED).to_be_bytes());
Ok(out)
}
fn compression_attr(compression: &Compression) -> String {
match compression.shuffle_item_size {
None => format!("{}:{}", compression.codec.name(), compression.uncompressed_size),
Some(item) => {
format!("{}+sh:{}:{}", compression.codec.name(), compression.uncompressed_size, item)
}
}
}
fn escape_attr(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for c in text.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
_ => out.push(c),
}
}
out
}
fn escape_text(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for c in text.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
_ => out.push(c),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Reader;
use crate::image::{ColorSpace, PixelStorage, SampleFormat};
fn image(width: u64, height: u64, channels: u64, format: SampleFormat) -> Image {
Image {
dimensions: vec![width, height],
channels,
sample_format: format,
color_space: if channels >= 3 { ColorSpace::Rgb } else { ColorSpace::Gray },
pixel_storage: PixelStorage::Planar,
bounds: format
.requires_bounds()
.then_some(crate::image::Bounds { low: 0.0, high: 1.0 }),
id: None,
uuid: None,
image_type: None,
offset: None,
orientation: None,
}
}
fn sample(len: usize) -> Vec<u8> {
(0..len).map(|i| (i * 31 + 7) as u8).collect()
}
fn round_trip(options: BlockOptions, format: SampleFormat) -> Vec<u8> {
let image = image(9, 7, 1, format);
let data = sample(image.data_size().unwrap() as usize);
let mut writer = Writer::new().with_creator("xisf-rs tests");
writer.add_image(PendingImage::new(image, data.clone(), options)).expect("add_image");
let bytes = writer.to_bytes().expect("to_bytes");
let reader = Reader::from_bytes(bytes).expect("read back");
let written = reader.header().images()[0];
let read = reader.block(&written.data).expect("block").to_vec();
assert_eq!(read, data, "the pixels changed on the way through");
reader.bytes().to_vec()
}
#[test]
fn writes_a_file_that_reads_back() {
round_trip(BlockOptions::default(), SampleFormat::UInt8);
}
fn writable_compressions() -> Vec<Option<CompressionRequest>> {
let mut out = vec![
None,
Some(CompressionRequest { codec: Codec2::Zstd, shuffle_item_size: None }),
Some(CompressionRequest { codec: Codec2::Zstd, shuffle_item_size: Some(4) }),
];
if cfg!(feature = "zlib") {
out.push(Some(CompressionRequest { codec: Codec2::Zlib, shuffle_item_size: None }));
out.push(Some(CompressionRequest { codec: Codec2::Zlib, shuffle_item_size: Some(4) }));
}
if cfg!(feature = "lz4") {
out.push(Some(CompressionRequest { codec: Codec2::Lz4, shuffle_item_size: None }));
out.push(Some(CompressionRequest { codec: Codec2::Lz4, shuffle_item_size: Some(2) }));
}
out
}
fn writable_checksums() -> Vec<Option<ChecksumAlgorithm>> {
vec![None, Some(ChecksumAlgorithm::Sha256)]
}
#[test]
fn every_option_combination_round_trips() {
for format in [SampleFormat::UInt8, SampleFormat::UInt16, SampleFormat::Float32] {
for compression in writable_compressions() {
for checksum in writable_checksums() {
round_trip(BlockOptions { compression, checksum }, format);
}
}
}
}
#[test]
fn block_positions_are_exact_and_contiguous() {
let mut writer = Writer::new();
for channels in [1u64, 3, 1] {
let image = image(11, 13, channels, SampleFormat::UInt16);
let data = sample(image.data_size().unwrap() as usize);
writer.add_image(PendingImage::new(image, data, BlockOptions::default())).unwrap();
}
let bytes = writer.to_bytes().unwrap();
let reader = Reader::from_bytes(bytes.clone()).unwrap();
let mut expected = crate::layout::scan(&bytes).unwrap().data_start() as u64;
for element in reader.header().images() {
let Some(crate::block::Location::Attachment { position, size }) = element.data.location
else {
panic!("expected an attachment");
};
assert_eq!(position, expected, "a block did not begin where the last one ended");
expected += size;
}
assert_eq!(expected as usize, bytes.len(), "the file has trailing bytes");
}
#[cfg(feature = "zlib")]
#[test]
fn checksums_written_are_checksums_that_verify() {
let image = image(8, 8, 1, SampleFormat::UInt16);
let data = sample(image.data_size().unwrap() as usize);
let mut writer = Writer::new();
writer
.add_image(PendingImage::new(
image,
data,
BlockOptions {
compression: Some(CompressionRequest {
codec: Codec2::Zlib,
shuffle_item_size: Some(2),
}),
checksum: Some(ChecksumAlgorithm::Sha512),
},
))
.unwrap();
let reader = Reader::from_bytes(writer.to_bytes().unwrap()).unwrap();
let written = reader.header().images()[0];
assert_eq!(
reader.verify(&written.data).unwrap(),
crate::ChecksumStatus::Valid,
"a checksum we wrote ourselves did not verify"
);
}
#[cfg(feature = "zlib")]
#[test]
fn incompressible_data_is_stored_plain() {
let image = image(4, 4, 1, SampleFormat::UInt8);
let data: Vec<u8> = (0..16u32).map(|i| (i.wrapping_mul(2654435761) >> 24) as u8).collect();
let mut writer = Writer::new();
writer
.add_image(PendingImage::new(
image,
data,
BlockOptions {
compression: Some(CompressionRequest {
codec: Codec2::Zlib,
shuffle_item_size: None,
}),
checksum: None,
},
))
.unwrap();
let reader = Reader::from_bytes(writer.to_bytes().unwrap()).unwrap();
assert!(
reader.header().images()[0].data.compression.is_none(),
"compression that did not help should not have been recorded"
);
}
#[test]
fn data_that_does_not_match_the_geometry_is_refused() {
let mut writer = Writer::new();
let err = writer
.add_image(PendingImage::new(
image(10, 10, 1, SampleFormat::UInt16),
vec![0; 3],
BlockOptions::default(),
))
.unwrap_err();
assert_eq!(err.kind(), crate::ErrorKind::InvalidArgument);
}
#[test]
fn special_characters_in_metadata_are_escaped() {
let mut writer = Writer::new();
writer.add_metadata("Test:Value", r#"a & b < c > d " e ' f"#).expect("id");
writer
.add_image(PendingImage::new(
image(2, 2, 1, SampleFormat::UInt8),
sample(4),
BlockOptions::default(),
))
.unwrap();
let reader = Reader::from_bytes(writer.to_bytes().unwrap()).unwrap();
let property = reader
.header()
.root
.descendants()
.into_iter()
.find(|e| e.attr("id") == Some("Test:Value"))
.expect("the property survived");
assert_eq!(property.data.text.as_deref(), Some(r#"a & b < c > d " e ' f"#));
}
}
#[cfg(test)]
mod time_tests {
use super::iso8601_from_unix;
#[test]
fn unix_timestamps_format_as_iso8601() {
for (seconds, expected) in [
(0, "1970-01-01T00:00:00Z"),
(86_399, "1970-01-01T23:59:59Z"),
(86_400, "1970-01-02T00:00:00Z"),
(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"), ] {
assert_eq!(iso8601_from_unix(seconds), expected, "for {seconds}");
}
}
}