xisf-header 0.2.0

Read and write XISF image-file headers: extract FITS keywords and CRUD the XISF header container. Header-only (never touches pixel data).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! The [`Header`] value, [`StructuralHints`], and the keyword/property API.

use std::collections::BTreeMap;

use crate::error::{Error, Result};
use crate::key::Key;
use crate::keyword::FitsKeyword;
use crate::property::Property;
use crate::value::{FromField, IntoValue};

/// Geometry hints used when serializing a standalone container: they populate
/// the `<Image>` element when the header does not already carry that structure.
/// Defaults to a minimal 1×1 8-bit grayscale image.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct StructuralHints {
    /// XISF `geometry` attribute, e.g. `"1:1:1"` (width:height:channels).
    pub geometry: String,
    /// XISF `sampleFormat`, e.g. `"UInt8"`.
    pub sample_format: String,
    /// XISF `colorSpace`, e.g. `"Gray"`.
    pub color_space: String,
}

impl Default for StructuralHints {
    fn default() -> Self {
        Self {
            geometry: "1:1:1".to_owned(),
            sample_format: "UInt8".to_owned(),
            color_space: "Gray".to_owned(),
        }
    }
}

/// A parsed XISF header: an ordered list of [`FitsKeyword`]s plus a map of
/// XISF `<Property>` elements.
///
/// Keyword access is **strict**: a bare name must be unique, or the accessor
/// returns [`Error::Ambiguous`]. Repeated keywords are reached with an
/// `(name, n)` key or the `get_all`/`count` helpers. Keyword order is preserved.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Header {
    pub(crate) keywords: Vec<FitsKeyword>,
    pub(crate) properties: BTreeMap<String, Property>,
}

impl Header {
    /// Create an empty header.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    // ----- keyword reads -------------------------------------------------

    /// Interpret the addressed keyword's value as `T`.
    ///
    /// Returns `Ok(None)` when the keyword is absent or its value cannot be read
    /// as `T`, and [`Error::Ambiguous`] when a bare name matches more than one
    /// keyword.
    ///
    /// # Errors
    ///
    /// [`Error::Ambiguous`] on a duplicated bare name; [`Error::IndexOutOfRange`]
    /// for an `(name, n)` index past the last occurrence.
    pub fn get<'a, T: FromField>(&self, key: impl Into<Key<'a>>) -> Result<Option<T>> {
        Ok(self
            .resolve(key.into())?
            .and_then(|i| self.keywords[i].get::<T>()))
    }

    /// The addressed keyword's raw value text.
    ///
    /// # Errors
    ///
    /// See [`Header::get`].
    pub fn get_str<'a>(&self, key: impl Into<Key<'a>>) -> Result<Option<&str>> {
        Ok(self
            .resolve(key.into())?
            .map(|i| self.keywords[i].value_str()))
    }

    /// The addressed keyword's value as an `f64`.
    ///
    /// # Errors
    ///
    /// See [`Header::get`].
    pub fn get_f64<'a>(&self, key: impl Into<Key<'a>>) -> Result<Option<f64>> {
        self.get(key)
    }

    /// The addressed keyword's value as an `i64` (accepts `20` and `20.0`).
    ///
    /// # Errors
    ///
    /// See [`Header::get`].
    pub fn get_i64<'a>(&self, key: impl Into<Key<'a>>) -> Result<Option<i64>> {
        self.get(key)
    }

    /// The addressed keyword's value as a `u32`.
    ///
    /// # Errors
    ///
    /// See [`Header::get`].
    pub fn get_u32<'a>(&self, key: impl Into<Key<'a>>) -> Result<Option<u32>> {
        self.get(key)
    }

    /// The addressed keyword's value as a `bool` (FITS `T`/`F`).
    ///
    /// # Errors
    ///
    /// See [`Header::get`].
    pub fn get_bool<'a>(&self, key: impl Into<Key<'a>>) -> Result<Option<bool>> {
        self.get(key)
    }

    /// The addressed keyword's value as a civil date/time.
    ///
    /// # Errors
    ///
    /// See [`Header::get`].
    pub fn get_datetime<'a>(
        &self,
        key: impl Into<Key<'a>>,
    ) -> Result<Option<time::PrimitiveDateTime>> {
        self.get(key)
    }

    /// Every value for `name`, in order, that reads as `T`.
    pub fn get_all<T: FromField>(&self, name: &str) -> Vec<T> {
        self.indices(name)
            .filter_map(|i| self.keywords[i].get::<T>())
            .collect()
    }

    /// How many keywords carry `name` (case-insensitive).
    #[must_use]
    pub fn count(&self, name: &str) -> usize {
        self.indices(name).count()
    }

    /// All keywords in document order.
    #[must_use]
    pub fn keywords(&self) -> &[FitsKeyword] {
        &self.keywords
    }

    /// Iterate the keywords in document order.
    pub fn iter(&self) -> std::slice::Iter<'_, FitsKeyword> {
        self.keywords.iter()
    }

    // ----- keyword writes ------------------------------------------------

    /// Set a keyword's value: update in place when the name is unique, append
    /// when absent. The existing comment is preserved.
    ///
    /// # Errors
    ///
    /// [`Error::Ambiguous`] when a bare name is duplicated (use `(name, n)` or
    /// `set_at`-style selection), [`Error::IndexOutOfRange`] for a bad occurrence
    /// index, or [`Error::InvalidName`] when creating an invalid keyword.
    pub fn set<'a>(&mut self, key: impl Into<Key<'a>>, value: impl IntoValue) -> Result<()> {
        let key = key.into();
        let value = value.into_value();
        match key {
            Key::Name(name) => match self.resolve(Key::Name(name))? {
                Some(i) => self.keywords[i].value = value,
                None => {
                    Self::validate_name(name)?;
                    self.keywords.push(FitsKeyword {
                        name: name.to_owned(),
                        value,
                        comment: String::new(),
                    });
                }
            },
            Key::Nth(name, n) => {
                let i = self.require_nth(name, n)?;
                self.keywords[i].value = value;
            }
        }
        Ok(())
    }

    /// Append a keyword unconditionally (allowing duplicate names). This is how
    /// commentary keywords such as `HISTORY` are built up.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidName`] if `name` is not a valid keyword.
    pub fn append(&mut self, name: &str, value: impl IntoValue) -> Result<()> {
        Self::validate_name(name)?;
        self.keywords.push(FitsKeyword {
            name: name.to_owned(),
            value: value.into_value(),
            comment: String::new(),
        });
        Ok(())
    }

    /// Set (or clear, with `""`) the comment on the addressed keyword.
    /// Returns `true` if a keyword was found.
    ///
    /// # Errors
    ///
    /// See [`Header::set`].
    pub fn set_comment<'a>(
        &mut self,
        key: impl Into<Key<'a>>,
        comment: impl Into<String>,
    ) -> Result<bool> {
        match self.resolve(key.into())? {
            Some(i) => {
                self.keywords[i].comment = comment.into();
                Ok(true)
            }
            None => Ok(false),
        }
    }

    /// Set a keyword's value and comment together.
    ///
    /// # Errors
    ///
    /// See [`Header::set`].
    pub fn set_with_comment<'a>(
        &mut self,
        key: impl Into<Key<'a>>,
        value: impl IntoValue,
        comment: impl Into<String>,
    ) -> Result<()> {
        let key = key.into();
        self.set(key, value)?;
        if let Some(i) = self.resolve(key)? {
            self.keywords[i].comment = comment.into();
        }
        Ok(())
    }

    /// Remove the addressed keyword. Returns `true` if one was removed.
    ///
    /// # Errors
    ///
    /// See [`Header::set`].
    pub fn remove<'a>(&mut self, key: impl Into<Key<'a>>) -> Result<bool> {
        match self.resolve(key.into())? {
            Some(i) => {
                self.keywords.remove(i);
                Ok(true)
            }
            None => Ok(false),
        }
    }

    /// Remove every keyword named `name`. Returns how many were removed.
    pub fn remove_all(&mut self, name: &str) -> usize {
        let before = self.keywords.len();
        self.keywords.retain(|k| !k.name.eq_ignore_ascii_case(name));
        before - self.keywords.len()
    }

    /// Apply several single-keyword upserts atomically: validate every entry
    /// first, then apply all — or, on any rejection, apply none.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidName`] or [`Error::Ambiguous`] for any entry; on error the
    /// header is unchanged.
    pub fn set_many<'a, V, I>(&mut self, entries: I) -> Result<()>
    where
        V: IntoValue,
        I: IntoIterator<Item = (&'a str, V)>,
    {
        let entries: Vec<(&str, V)> = entries.into_iter().collect();
        for (name, _) in &entries {
            Self::validate_name(name)?;
            let count = self.count(name);
            if count > 1 {
                return Err(Error::Ambiguous {
                    name: (*name).to_owned(),
                    count,
                });
            }
        }
        for (name, value) in entries {
            match self.first_index(name) {
                Some(i) => self.keywords[i].value = value.into_value(),
                None => self.keywords.push(FitsKeyword {
                    name: name.to_owned(),
                    value: value.into_value(),
                    comment: String::new(),
                }),
            }
        }
        Ok(())
    }

    /// Remove several keywords atomically. Returns how many were removed.
    ///
    /// # Errors
    ///
    /// [`Error::Ambiguous`] if any name is duplicated; on error the header is
    /// unchanged.
    pub fn remove_many<'a, I: IntoIterator<Item = &'a str>>(&mut self, names: I) -> Result<usize> {
        let names: Vec<&str> = names.into_iter().collect();
        for name in &names {
            let count = self.count(name);
            if count > 1 {
                return Err(Error::Ambiguous {
                    name: (*name).to_owned(),
                    count,
                });
            }
        }
        let mut removed = 0;
        for name in names {
            if let Some(i) = self.first_index(name) {
                self.keywords.remove(i);
                removed += 1;
            }
        }
        Ok(removed)
    }

    // ----- property CRUD -------------------------------------------------

    /// All `<Property>` entries, keyed by `id`.
    #[must_use]
    pub fn properties(&self) -> &BTreeMap<String, Property> {
        &self.properties
    }

    /// A property's raw value text by `id`.
    #[must_use]
    pub fn property(&self, id: &str) -> Option<&str> {
        self.properties.get(id).map(|p| p.value.as_str())
    }

    /// A property value interpreted as `T`.
    #[must_use]
    pub fn property_get<T: FromField>(&self, id: &str) -> Option<T> {
        self.properties
            .get(id)
            .and_then(|p| T::from_field(&p.value))
    }

    /// Insert or update a property's value. An existing property keeps its
    /// `type`, `comment`, and `format`; a new one is created with type
    /// `String`.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidName`] if `id` is not a valid XISF property id.
    pub fn set_property(&mut self, id: impl Into<String>, value: impl Into<String>) -> Result<()> {
        let id = id.into();
        Self::validate_property_id(&id)?;
        self.properties.entry(id).or_default().value = value.into();
        Ok(())
    }

    /// Insert or update a property with an explicit XISF `type` (e.g.
    /// `Float32`, `TimePoint`). An existing property keeps its `comment` and
    /// `format`.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidName`] if `id` is not a valid XISF property id.
    pub fn set_property_with_type(
        &mut self,
        id: impl Into<String>,
        value: impl Into<String>,
        type_: impl Into<String>,
    ) -> Result<()> {
        let id = id.into();
        Self::validate_property_id(&id)?;
        let p = self.properties.entry(id).or_default();
        p.value = value.into();
        p.type_ = type_.into();
        Ok(())
    }

    /// Remove a property by `id`. Returns `true` if it existed.
    pub fn remove_property(&mut self, id: &str) -> bool {
        self.properties.remove(id).is_some()
    }

    // ----- internals -----------------------------------------------------

    fn indices<'s>(&'s self, name: &'s str) -> impl Iterator<Item = usize> + 's {
        self.keywords
            .iter()
            .enumerate()
            .filter(move |(_, k)| k.name.eq_ignore_ascii_case(name))
            .map(|(i, _)| i)
    }

    fn first_index(&self, name: &str) -> Option<usize> {
        self.indices(name).next()
    }

    /// Resolve a key to a keyword index, enforcing the strict rules.
    fn resolve(&self, key: Key) -> Result<Option<usize>> {
        match key {
            Key::Name(name) => {
                let mut it = self.indices(name);
                let first = it.next();
                if first.is_some() && it.next().is_some() {
                    return Err(Error::Ambiguous {
                        name: name.to_owned(),
                        count: self.count(name),
                    });
                }
                Ok(first)
            }
            Key::Nth(name, n) => {
                let indices: Vec<usize> = self.indices(name).collect();
                match indices.get(n) {
                    Some(&i) => Ok(Some(i)),
                    None if indices.is_empty() => Ok(None),
                    None => Err(Error::IndexOutOfRange {
                        name: name.to_owned(),
                        index: n,
                        count: indices.len(),
                    }),
                }
            }
        }
    }

    fn require_nth(&self, name: &str, n: usize) -> Result<usize> {
        self.resolve(Key::Nth(name, n))?
            .ok_or_else(|| Error::IndexOutOfRange {
                name: name.to_owned(),
                index: n,
                count: 0,
            })
    }

    fn validate_name(name: &str) -> Result<()> {
        if name.is_empty() {
            return Err(Error::InvalidName {
                name: name.to_owned(),
                reason: "empty",
            });
        }
        if name.len() > 8 {
            return Err(Error::InvalidName {
                name: name.to_owned(),
                reason: "exceeds 8 characters",
            });
        }
        if !name
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
        {
            return Err(Error::InvalidName {
                name: name.to_owned(),
                reason: "must be ASCII letters, digits, `-`, or `_`",
            });
        }
        Ok(())
    }

    fn validate_property_id(id: &str) -> Result<()> {
        if id.is_empty() {
            return Err(Error::InvalidName {
                name: id.to_owned(),
                reason: "empty",
            });
        }
        if !id
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b':')
        {
            return Err(Error::InvalidName {
                name: id.to_owned(),
                reason: "property id must be ASCII alphanumeric, `_`, or `:`",
            });
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn validate_name_rules() {
        assert!(Header::validate_name("GAIN").is_ok());
        assert!(Header::validate_name("DATE-OBS").is_ok());
        assert!(Header::validate_name("lower_k").is_ok());
        assert!(Header::validate_name("EIGHTCHR").is_ok());
        assert!(Header::validate_name("").is_err());
        assert!(Header::validate_name("NINECHARS").is_err());
        assert!(Header::validate_name("BAD KEY").is_err());
        assert!(Header::validate_name("NAME!").is_err());
    }

    #[test]
    fn validate_property_id_rules() {
        assert!(Header::validate_property_id("Instrument:Telescope:FocalLength").is_ok());
        assert!(Header::validate_property_id("A_b:9").is_ok());
        assert!(Header::validate_property_id("").is_err());
        assert!(Header::validate_property_id("bad id!").is_err());
        assert!(Header::validate_property_id("hy-phen").is_err());
    }

    #[test]
    fn nth_write_on_absent_name_errors() {
        let mut h = Header::new();
        assert!(matches!(
            h.set(("MISSING", 0), 1_i64),
            Err(Error::IndexOutOfRange { count: 0, .. })
        ));
    }

    #[test]
    fn set_with_comment_creates_and_updates() {
        let mut h = Header::new();
        h.set_with_comment("GAIN", 100_i64, "sensor gain").unwrap();
        assert_eq!(h.get_i64("GAIN").unwrap(), Some(100));
        assert_eq!(h.keywords()[0].comment, "sensor gain");

        h.set_with_comment("GAIN", 200_i64, "updated").unwrap();
        assert_eq!(h.get_i64("GAIN").unwrap(), Some(200));
        assert_eq!(h.keywords()[0].comment, "updated");

        h.append("HISTORY", "a").unwrap();
        h.append("HISTORY", "b").unwrap();
        assert!(matches!(
            h.set_with_comment("HISTORY", "x", "c"),
            Err(Error::Ambiguous { .. })
        ));
    }

    #[test]
    fn set_comment_on_absent_keyword_reports_not_found() {
        let mut h = Header::new();
        assert!(!h.set_comment("MISSING", "c").unwrap());
    }

    #[test]
    fn remove_all_clears_every_occurrence() {
        let mut h = Header::new();
        h.append("HISTORY", "a").unwrap();
        h.append("HISTORY", "b").unwrap();
        h.set("GAIN", 1_i64).unwrap();
        assert_eq!(h.remove_all("history"), 2); // case-insensitive
        assert_eq!(h.count("HISTORY"), 0);
        assert_eq!(h.remove_all("HISTORY"), 0);
        assert_eq!(h.get_i64("GAIN").unwrap(), Some(1));
    }

    #[test]
    fn iter_preserves_document_order() {
        let mut h = Header::new();
        h.set("A", 1_i64).unwrap();
        h.set("B", 2_i64).unwrap();
        h.set("C", 3_i64).unwrap();
        let names: Vec<&str> = h.iter().map(|k| k.name.as_str()).collect();
        assert_eq!(names, ["A", "B", "C"]);
    }

    #[test]
    fn string_keys_are_accepted() {
        let mut h = Header::new();
        let key = String::from("GAIN");
        h.set(&key, 100_i64).unwrap();
        assert_eq!(h.get_i64(&key).unwrap(), Some(100));
    }

    #[test]
    fn generic_get_reads_string() {
        let mut h = Header::new();
        h.set("OBJECT", "M31").unwrap();
        assert_eq!(h.get::<String>("OBJECT").unwrap(), Some("M31".to_owned()));
    }
}