Expand description
§fits-header
A pure-Rust library for reading and writing the header of a FITS file.
- Header-scoped: this crate never owns, inspects, or fabricates pixel data. Editing a
file on disk means
Header::update_file, which preserves the existing data unit byte-for-byte; creating a new file meansHeader::write_to_file, which writes your own pixel bytes right after the header and errors instead of overwriting an existing path. - Pure Rust, no C or system libraries. Builds with the MSVC toolchain.
- Every card is retained on parse; untouched cards (including long-string runs) re-serialize byte-for-byte. Only created or edited cards are re-rendered.
- Keyword access is strict: a bare name addresses the sole occurrence of a keyword and
errors when it is duplicated;
("NAME", n)selects the n-th occurrence — seeKey. - Create, read, update, and delete single or multiple keywords; batch mutations
(
set_many,remove_many) are atomic (all or nothing). - Typed reads and writes:
get::<T>covers strings, numbers, booleans, and date/times;Literal/Fixed/Sciwrappers control number formatting on write. - Long strings use the
CONTINUEconvention on read and write (withLONGSTRN). - The API is an ordered
HeaderofRecords — value cards, repeatable commentary cards, and opaque pass-through cards; it contains no application types. HIERARCHand other non-standard or malformed cards parse asRecordKind::Opaquerecords: preserved byte-for-byte on re-serialization, but not addressable by keyword (get/set/removenever see them).
§Install
cargo add fits-header
# opt into serde derives on the public types:
cargo add fits-header --features serde§Usage
A Header is an in-memory value; set/remove/append mutate it only — nothing is
written to disk until you persist it.
use fits_header::{Header, Result};
fn demo(bytes: &[u8]) -> Result<()> {
// Read every card from a FITS header unit.
let mut header = Header::parse(bytes)?;
// Typed reads through one generic accessor. Access is strict: a bare
// name errors if the keyword occurs more than once.
let exptime: Option<f64> = header.get("EXPTIME")?;
let object: Option<&str> = header.get_str("OBJECT")?;
let gain: Option<i64> = header.get(("GAIN", 1))?; // second occurrence
// Create, update, delete. These change the in-memory header only.
header.set("OBJECT", "M31")?;
header.set("EXPTIME", 300.0)?;
header.remove("AIRMASS")?;
// Batch mutations are atomic — all or nothing.
header.set_many([("FILTER", "Ha"), ("TELESCOP", "EdgeHD 8")])?;
// The low-level building block: the header block alone. `update_file` and
// `write_to_file` below cover the common cases directly.
let block: Vec<u8> = header.to_header_bytes();
Ok(())
}
// Editing a file on disk: the data unit (and any later HDUs) survives untouched. This
// is the common path — most callers only ever edit an existing file.
fn edit_in_place(path: &std::path::Path) -> Result<()> {
Header::update_file(path, |h| {
h.set("OBJECT", "M31")?;
Ok(())
})
}
// Creating a NEW file: build a header, then hand it your own pixel bytes. Errors if
// `path` already exists — this crate never fabricates pixel data or clobbers a file.
fn create_file(path: &std::path::Path) -> Result<()> {
let mut header = Header::new();
header.set("OBJECT", "M31")?;
header.write_to_file(path, &[0u8; 2880]) // stand-in pixel data
}See the guide for a
longer, task-oriented walkthrough backed by
examples/quickstart.rs.
§Repeated keywords (HISTORY / COMMENT)
Commentary keywords like HISTORY and COMMENT repeat.
append
adds an occurrence,
get_all
reads every one in order, and an ("HISTORY", n) key addresses a single
occurrence to update it in place or remove it.
use fits_header::Header;
let mut header = Header::new();
header.append("HISTORY", "dark subtracted")?;
header.append("HISTORY", "flat fielded")?;
assert_eq!(header.count("HISTORY"), 2);
// Read the processing log in order.
assert_eq!(
header.get_all::<String>("HISTORY"),
["dark subtracted", "flat fielded"],
);
// Update one occurrence in place, then drop another. Commentary cards carry no
// value, so read them through `get`/`get_all`, not `get_str`.
header.set(("HISTORY", 1), "flat fielded (master flat v2)")?;
header.remove(("HISTORY", 0))?;
assert_eq!(header.get_all::<String>("HISTORY"), ["flat fielded (master flat v2)"]);§Reading and writing real files
Header::read_from_file(path)— read a header from disk. Parsing stops atEND, so the data unit is read but never interpreted.Header::update_file(path, edit)— the common path: edit an existing file in place. Reads the file, locates the header by scanning forEND, hands you the parsed header to mutate, then writes the new header back followed by everything that came after the original one (data unit, later HDUs) untouched. The write is atomic (temp file + rename). Errors withFitsError::MissingEndif the file has noENDcard.Header::write_to_file(path, data)— the rarer path: create a new file from a header and pixel bytes you already have. Errors instead of overwritingpathif it already exists; pass&[]for a header-only file.Header::to_header_bytes()— the lower-level building block behind both: the header block only (cards +END, padded to a 2880-byte multiple), for callers who assemble the file bytes themselves.
§Documentation
- guide — task-oriented quickstart.
- docs.rs/fits-header — full API reference, generated
from the crate’s rustdoc. Every public item is documented; the examples are compiled
and run as part of the test suite. Build it locally with
cargo doc --no-deps --all-features --open.
§Features
§Development
just verify # fmt-check + clippy (-D warnings) + tests
cargo test --all-features # includes the serde suite
just doc§License
Licensed under the Apache License, Version 2.0.
Modules§
- guide
- Quickstart
Structs§
- Fixed
- Write a float with a fixed number of decimal places.
- Header
- An ordered FITS header unit:
Records in appearance order, with strict keyword access (viaKey) and CRUD. - Literal
- Write a literal token verbatim (numeric text a vendor supplied, or a value you don’t want reformatted).
- Record
- One header card. Carries its parsed
RecordKindplus, when parsed and unmodified, the original bytes of its physical card(s) so it can be serialized verbatim. - Sci
- Write a float in scientific notation with
Nsignificant digits (uppercaseE).
Enums§
- Fits
Error - Errors from validated header mutations, ambiguous lookups, and oversized standalone serialization.
- Key
- Selects a record by keyword.
- Record
Kind - The semantic content of a
Record. - Value
- A value card’s payload.
Constants§
Traits§
- From
Card - Convert a record’s value into a Rust type. The extension point behind
Header::get. - Into
Value - Convert a Rust value into a
Value. The extension point behindHeader::set/append.
Functions§
- format_
datetime - Format a date/time back to the FITS civil form (
YYYY-MM-DDThh:mm:ss[.fff]), dropping a zero sub-second part. - parse
Deprecated - Deprecated free-function alias for
Header::parse; use that instead. - parse_
datetime - Parse a FITS civil date/time (
YYYY-MM-DD[Thh:mm:ss[.fff]]), timezone-naive. - parse_
f64 - Parse a float, accepting the Fortran
Dexponent (1.5D3). - parse_
i64 - Parse an integer, accepting decimal-form integers (
"20.0"→20).