fits-header 0.3.4

Pure-Rust, MSVC-safe FITS header reader/writer: parse every card from a FITS file, CRUD single or multiple header keywords, then serialize back to a valid FITS object.
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
# Quickstart

A task-oriented walkthrough of [`fits-header`](https://docs.rs/fits-header). The snippets
below are adapted from
[`examples/quickstart.rs`](https://github.com/nightwatch-astro/fits-header/blob/main/examples/quickstart.rs),
which packages the same steps into one runnable file — run it yourself with:

```sh
cargo run --example quickstart
```

This page also renders at [`fits_header::guide`](https://docs.rs/fits-header/latest/fits_header/guide/index.html);
every code block below compiles and runs as a doctest, so the guide cannot drift from the
API. Each block rebuilds the fixture from scratch (hidden lines in the rendered doctest) so
it stands alone. Full API reference: [docs.rs/fits-header](https://docs.rs/fits-header/latest/fits_header/).

## The fixture

One header, reused for every step: a CCD image of M31. One string per 80-byte card,
space-padded, in appearance order.

```rust
const SAMPLE_CARDS: &[&str] = &[
    "SIMPLE  =                    T / conforms to FITS standard",
    "BITPIX  =                  -32 / IEEE single-precision float",
    "NAXIS   =                    2 / number of data axes",
    "NAXIS1  =                 1024 / axis 1 length",
    "NAXIS2  =                 1024 / axis 2 length",
    "OBJECT  = 'M31     '           / target name",
    "EXPTIME =                120.0 / exposure time in seconds",
    "DATE-OBS= '2026-07-11T22:15:03' / UTC start of exposure",
    "GAIN    =                  1.0 / e-/ADU",
    "FILTER  = 'Ha      '           / filter name",
    "TELESCOP= 'EdgeHD 8'           / telescope",
    "HISTORY dark subtracted",
];
# assert_eq!(SAMPLE_CARDS.len(), 12);
```

Pack it into a valid header unit —
[`CARD_LEN`](https://docs.rs/fits-header/latest/fits_header/constant.CARD_LEN.html)-byte
cards, an `END` card, padded to a
[`BLOCK_LEN`](https://docs.rs/fits-header/latest/fits_header/constant.BLOCK_LEN.html)
multiple — and
[`Header::parse`](https://docs.rs/fits-header/latest/fits_header/struct.Header.html#method.parse)
it into a [`Header`](https://docs.rs/fits-header/latest/fits_header/struct.Header.html):

```rust
use fits_header::Header;

# const SAMPLE_CARDS: &[&str] = &[
#     "SIMPLE  =                    T / conforms to FITS standard",
#     "BITPIX  =                  -32 / IEEE single-precision float",
#     "NAXIS   =                    2 / number of data axes",
#     "NAXIS1  =                 1024 / axis 1 length",
#     "NAXIS2  =                 1024 / axis 2 length",
#     "OBJECT  = 'M31     '           / target name",
#     "EXPTIME =                120.0 / exposure time in seconds",
#     "DATE-OBS= '2026-07-11T22:15:03' / UTC start of exposure",
#     "GAIN    =                  1.0 / e-/ADU",
#     "FILTER  = 'Ha      '           / filter name",
#     "TELESCOP= 'EdgeHD 8'           / telescope",
#     "HISTORY dark subtracted",
# ];
let mut bytes = Vec::new();
for card in SAMPLE_CARDS.iter().chain(["END"].iter()) {
    let mut c = card.as_bytes().to_vec();
    c.resize(fits_header::CARD_LEN, b' ');
    bytes.extend(c);
}
while bytes.len() % fits_header::BLOCK_LEN != 0 {
    bytes.push(b' ');
}

let mut header: Header = Header::parse(&bytes).unwrap();
# assert_eq!(header.get_str("OBJECT").unwrap(), Some("M31"));
```

The same bytes read from disk instead of memory:
[`Header::read_from_file`](https://docs.rs/fits-header/latest/fits_header/struct.Header.html#method.read_from_file)
reads the file and parses it the same way; parsing already stops at `END`, so the data
unit is read but never interpreted.

Every card is retained, including ones this guide never touches — they re-serialize
byte-for-byte at the end.

## Read

[`Header::get`](https://docs.rs/fits-header/latest/fits_header/struct.Header.html#method.get)
is one generic accessor for every value type; string keywords also have a borrowing
shortcut,
[`Header::get_str`](https://docs.rs/fits-header/latest/fits_header/struct.Header.html#method.get_str):

```rust
# fn sample_header() -> fits_header::Header {
#     const SAMPLE_CARDS: &[&str] = &[
#         "SIMPLE  =                    T / conforms to FITS standard",
#         "BITPIX  =                  -32 / IEEE single-precision float",
#         "NAXIS   =                    2 / number of data axes",
#         "NAXIS1  =                 1024 / axis 1 length",
#         "NAXIS2  =                 1024 / axis 2 length",
#         "OBJECT  = 'M31     '           / target name",
#         "EXPTIME =                120.0 / exposure time in seconds",
#         "DATE-OBS= '2026-07-11T22:15:03' / UTC start of exposure",
#         "GAIN    =                  1.0 / e-/ADU",
#         "FILTER  = 'Ha      '           / filter name",
#         "TELESCOP= 'EdgeHD 8'           / telescope",
#         "HISTORY dark subtracted",
#     ];
#     let mut bytes = Vec::new();
#     for card in SAMPLE_CARDS.iter().chain(["END"].iter()) {
#         let mut c = card.as_bytes().to_vec();
#         c.resize(fits_header::CARD_LEN, b' ');
#         bytes.extend(c);
#     }
#     while bytes.len() % fits_header::BLOCK_LEN != 0 {
#         bytes.push(b' ');
#     }
#     fits_header::Header::parse(&bytes).unwrap()
# }
# let header = sample_header();
let object: Option<&str> = header.get_str("OBJECT").unwrap();
let exptime: Option<f64> = header.get("EXPTIME").unwrap();
assert_eq!(object, Some("M31"));
assert_eq!(exptime, Some(120.0));
```

`COMMENT`, `HISTORY`, and blank-keyword cards are free-text
[`RecordKind::Commentary`](https://docs.rs/fits-header/latest/fits_header/enum.RecordKind.html#variant.Commentary)
records rather than addressable
[`RecordKind::Value`](https://docs.rs/fits-header/latest/fits_header/enum.RecordKind.html#variant.Value)
cards, so they repeat. Count occurrences with
[`Header::count`](https://docs.rs/fits-header/latest/fits_header/struct.Header.html#method.count)
and read them all with
[`Header::get_all`](https://docs.rs/fits-header/latest/fits_header/struct.Header.html#method.get_all):

```rust
# fn sample_header() -> fits_header::Header {
#     const SAMPLE_CARDS: &[&str] = &[
#         "SIMPLE  =                    T / conforms to FITS standard",
#         "BITPIX  =                  -32 / IEEE single-precision float",
#         "NAXIS   =                    2 / number of data axes",
#         "NAXIS1  =                 1024 / axis 1 length",
#         "NAXIS2  =                 1024 / axis 2 length",
#         "OBJECT  = 'M31     '           / target name",
#         "EXPTIME =                120.0 / exposure time in seconds",
#         "DATE-OBS= '2026-07-11T22:15:03' / UTC start of exposure",
#         "GAIN    =                  1.0 / e-/ADU",
#         "FILTER  = 'Ha      '           / filter name",
#         "TELESCOP= 'EdgeHD 8'           / telescope",
#         "HISTORY dark subtracted",
#     ];
#     let mut bytes = Vec::new();
#     for card in SAMPLE_CARDS.iter().chain(["END"].iter()) {
#         let mut c = card.as_bytes().to_vec();
#         c.resize(fits_header::CARD_LEN, b' ');
#         bytes.extend(c);
#     }
#     while bytes.len() % fits_header::BLOCK_LEN != 0 {
#         bytes.push(b' ');
#     }
#     fits_header::Header::parse(&bytes).unwrap()
# }
# let header = sample_header();
assert_eq!(header.count("HISTORY"), 1);
assert_eq!(
    header.get_all::<String>("HISTORY"),
    vec!["dark subtracted".to_string()]
);
```

Value cards are read by bare name, and that access is strict: nothing stops a keyword
like `GAIN` from appearing more than once, so if it does, `header.get::<f64>("GAIN")`
returns
[`FitsError::AmbiguousKeyword`](https://docs.rs/fits-header/latest/fits_header/enum.FitsError.html#variant.AmbiguousKeyword)
instead of guessing. Select one occurrence with a
[`Key`](https://docs.rs/fits-header/latest/fits_header/enum.Key.html) pair, e.g.
`header.get::<f64>(("GAIN", 1))` for the second occurrence.

`HIERARCH` cards and other non-standard or malformed cards parse as opaque
[`RecordKind::Opaque`](https://docs.rs/fits-header/latest/fits_header/enum.RecordKind.html#variant.Opaque)
records. They pass through unmodified on re-serialization, but they carry no addressable
keyword — `get`, `set`, and `remove` never see them, and
[`Header::count`](https://docs.rs/fits-header/latest/fits_header/struct.Header.html#method.count)
reports them as absent.

## Mutate

[`Header::set`](https://docs.rs/fits-header/latest/fits_header/struct.Header.html#method.set)
updates the addressed card in place, or appends one when the (unique) keyword is absent.
[`Header::append`](https://docs.rs/fits-header/latest/fits_header/struct.Header.html#method.append)
always adds a card, which is how repeatable keywords like `HISTORY` grow.
[`Header::set_comment`](https://docs.rs/fits-header/latest/fits_header/struct.Header.html#method.set_comment)
and
[`Header::remove`](https://docs.rs/fits-header/latest/fits_header/struct.Header.html#method.remove)
round out single-card CRUD:

```rust
# fn sample_header() -> fits_header::Header {
#     const SAMPLE_CARDS: &[&str] = &[
#         "SIMPLE  =                    T / conforms to FITS standard",
#         "BITPIX  =                  -32 / IEEE single-precision float",
#         "NAXIS   =                    2 / number of data axes",
#         "NAXIS1  =                 1024 / axis 1 length",
#         "NAXIS2  =                 1024 / axis 2 length",
#         "OBJECT  = 'M31     '           / target name",
#         "EXPTIME =                120.0 / exposure time in seconds",
#         "DATE-OBS= '2026-07-11T22:15:03' / UTC start of exposure",
#         "GAIN    =                  1.0 / e-/ADU",
#         "FILTER  = 'Ha      '           / filter name",
#         "TELESCOP= 'EdgeHD 8'           / telescope",
#         "HISTORY dark subtracted",
#     ];
#     let mut bytes = Vec::new();
#     for card in SAMPLE_CARDS.iter().chain(["END"].iter()) {
#         let mut c = card.as_bytes().to_vec();
#         c.resize(fits_header::CARD_LEN, b' ');
#         bytes.extend(c);
#     }
#     while bytes.len() % fits_header::BLOCK_LEN != 0 {
#         bytes.push(b' ');
#     }
#     fits_header::Header::parse(&bytes).unwrap()
# }
# let mut header = sample_header();
header.set("OBJECT", "NGC 7000").unwrap(); // updates in place
header.append("HISTORY", "flat fielded").unwrap(); // HISTORY repeats, so this adds a second card
header.set(("HISTORY", 0), "dark subtracted (master dark v2)").unwrap(); // update one occurrence in place
header.set_comment("EXPTIME", "seconds, revised").unwrap();
header.remove("GAIN").unwrap();
# assert_eq!(header.get_str("OBJECT").unwrap(), Some("NGC 7000"));
# assert_eq!(header.count("HISTORY"), 2);
# assert_eq!(header.get_all::<String>("HISTORY"), ["dark subtracted (master dark v2)", "flat fielded"]);
```

These calls change only the in-memory `Header`; nothing is written to disk until you
persist it — with `update_file` to edit an existing file in place (the common case), or
`write_to_file`/`to_header_bytes` to create a new one (see [Serialize](#serialize)
below).

## Atomic batches

[`Header::set_many`](https://docs.rs/fits-header/latest/fits_header/struct.Header.html#method.set_many)
and
[`Header::remove_many`](https://docs.rs/fits-header/latest/fits_header/struct.Header.html#method.remove_many)
validate every entry before applying any of them — a rejected batch leaves the header
untouched:

```rust
# fn sample_header() -> fits_header::Header {
#     const SAMPLE_CARDS: &[&str] = &[
#         "SIMPLE  =                    T / conforms to FITS standard",
#         "BITPIX  =                  -32 / IEEE single-precision float",
#         "NAXIS   =                    2 / number of data axes",
#         "NAXIS1  =                 1024 / axis 1 length",
#         "NAXIS2  =                 1024 / axis 2 length",
#         "OBJECT  = 'M31     '           / target name",
#         "EXPTIME =                120.0 / exposure time in seconds",
#         "DATE-OBS= '2026-07-11T22:15:03' / UTC start of exposure",
#         "GAIN    =                  1.0 / e-/ADU",
#         "FILTER  = 'Ha      '           / filter name",
#         "TELESCOP= 'EdgeHD 8'           / telescope",
#         "HISTORY dark subtracted",
#     ];
#     let mut bytes = Vec::new();
#     for card in SAMPLE_CARDS.iter().chain(["END"].iter()) {
#         let mut c = card.as_bytes().to_vec();
#         c.resize(fits_header::CARD_LEN, b' ');
#         bytes.extend(c);
#     }
#     while bytes.len() % fits_header::BLOCK_LEN != 0 {
#         bytes.push(b' ');
#     }
#     fits_header::Header::parse(&bytes).unwrap()
# }
# let mut header = sample_header();
header
    .set_many([("FILTER", "OIII"), ("TELESCOP", "EdgeHD 11")])
    .unwrap();
# assert_eq!(header.get_str("FILTER").unwrap(), Some("OIII"));
```

## Serialize

[`Header::to_header_bytes`](https://docs.rs/fits-header/latest/fits_header/struct.Header.html#method.to_header_bytes)
writes the header block alone — cards plus `END`, padded to a `BLOCK_LEN` multiple:

```rust
# fn sample_header() -> fits_header::Header {
#     const SAMPLE_CARDS: &[&str] = &[
#         "SIMPLE  =                    T / conforms to FITS standard",
#         "BITPIX  =                  -32 / IEEE single-precision float",
#         "NAXIS   =                    2 / number of data axes",
#         "NAXIS1  =                 1024 / axis 1 length",
#         "NAXIS2  =                 1024 / axis 2 length",
#         "OBJECT  = 'M31     '           / target name",
#         "EXPTIME =                120.0 / exposure time in seconds",
#         "DATE-OBS= '2026-07-11T22:15:03' / UTC start of exposure",
#         "GAIN    =                  1.0 / e-/ADU",
#         "FILTER  = 'Ha      '           / filter name",
#         "TELESCOP= 'EdgeHD 8'           / telescope",
#         "HISTORY dark subtracted",
#     ];
#     let mut bytes = Vec::new();
#     for card in SAMPLE_CARDS.iter().chain(["END"].iter()) {
#         let mut c = card.as_bytes().to_vec();
#         c.resize(fits_header::CARD_LEN, b' ');
#         bytes.extend(c);
#     }
#     while bytes.len() % fits_header::BLOCK_LEN != 0 {
#         bytes.push(b' ');
#     }
#     fits_header::Header::parse(&bytes).unwrap()
# }
# let header = sample_header();
let block: Vec<u8> = header.to_header_bytes();
assert_eq!(block.len() % fits_header::BLOCK_LEN, 0);
```

`BITPIX`, `NAXIS*`, and `DATE-OBS` were never touched above, so they come back
byte-for-byte identical to the input.

This crate is header-only: it never owns, inspects, or fabricates pixel data. That
shapes the two ways real files get written:

- **Editing an existing file** — the common case —
  [`Header::update_file`]https://docs.rs/fits-header/latest/fits_header/struct.Header.html#method.update_file
  reads the file, locates the header by scanning for `END`, hands you the parsed header
  to mutate, then writes the new header back followed by everything that came after the
  original one (the data unit, and any later HDUs), untouched:

  ```rust
  use fits_header::Header;

  # const SAMPLE_CARDS: &[&str] = &[
  #     "SIMPLE  =                    T / conforms to FITS standard",
  #     "BITPIX  =                  -32 / IEEE single-precision float",
  #     "NAXIS   =                    2 / number of data axes",
  #     "NAXIS1  =                 1024 / axis 1 length",
  #     "NAXIS2  =                 1024 / axis 2 length",
  #     "OBJECT  = 'M31     '           / target name",
  #     "EXPTIME =                120.0 / exposure time in seconds",
  #     "DATE-OBS= '2026-07-11T22:15:03' / UTC start of exposure",
  #     "GAIN    =                  1.0 / e-/ADU",
  #     "FILTER  = 'Ha      '           / filter name",
  #     "TELESCOP= 'EdgeHD 8'           / telescope",
  #     "HISTORY dark subtracted",
  # ];
  # let mut bytes = Vec::new();
  # for card in SAMPLE_CARDS.iter().chain(["END"].iter()) {
  #     let mut c = card.as_bytes().to_vec();
  #     c.resize(fits_header::CARD_LEN, b' ');
  #     bytes.extend(c);
  # }
  # while bytes.len() % fits_header::BLOCK_LEN != 0 {
  #     bytes.push(b' ');
  # }
  # bytes.extend_from_slice(&[0u8; 4]); // stand-in pixel data
  # let path = std::env::temp_dir().join("fits-header-guide-doctest-update_file.fits");
  # std::fs::write(&path, &bytes).unwrap();
  Header::update_file(&path, |h| {
      h.set("OBJECT", "NGC 7000")?;
      Ok(())
  })
  .unwrap();
  # let header = Header::read_from_file(&path).unwrap();
  # assert_eq!(header.get_str("OBJECT").unwrap(), Some("NGC 7000"));
  # std::fs::remove_file(&path).ok();
  ```

  The write is atomic (temp file in the same directory, then rename), so a crash cannot
  leave a truncated file. It errors with
  [`FitsError::MissingEnd`]https://docs.rs/fits-header/latest/fits_header/enum.FitsError.html#variant.MissingEnd
  if the file has no `END` card.

- **Creating a new file** — the rarer case where you already have pixel data and are
  writing it for the first time —
  [`Header::write_to_file`]https://docs.rs/fits-header/latest/fits_header/struct.Header.html#method.write_to_file
  writes the header block followed by your pixel bytes. It creates `path` and errors if
  it already exists, so it can never clobber an existing file's data — use `update_file`
  for that:

  ```rust
  use fits_header::Header;

  let mut header = Header::new();
  header.set("OBJECT", "M31").unwrap();
  let pixel_data = [0u8; 4]; // caller-owned data, e.g. from an image buffer

  let path = std::env::temp_dir().join("fits-header-guide-doctest-write_to_file.fits");
  # std::fs::remove_file(&path).ok();
  header.write_to_file(&path, &pixel_data).unwrap();

  let bytes = std::fs::read(&path).unwrap();
  assert_eq!(&bytes[bytes.len() - pixel_data.len()..], &pixel_data);

  // Writing to the same path again errors instead of overwriting it.
  assert!(header.write_to_file(&path, &pixel_data).is_err());
  # std::fs::remove_file(&path).ok();
  ```

## Next

- [README]https://github.com/nightwatch-astro/fits-header/blob/main/README.md for the
  feature summary and install instructions.
- [docs.rs/fits-header]https://docs.rs/fits-header/latest/fits_header/ for the full
  API reference, including number-formatting wrappers
  ([`Literal`]https://docs.rs/fits-header/latest/fits_header/struct.Literal.html,
  [`Fixed`]https://docs.rs/fits-header/latest/fits_header/struct.Fixed.html,
  [`Sci`]https://docs.rs/fits-header/latest/fits_header/struct.Sci.html), the
  number parsers
  ([`parse_f64`]https://docs.rs/fits-header/latest/fits_header/fn.parse_f64.html,
  [`parse_i64`]https://docs.rs/fits-header/latest/fits_header/fn.parse_i64.html), and
  the date/time helpers
  ([`parse_datetime`]https://docs.rs/fits-header/latest/fits_header/fn.parse_datetime.html,
  [`format_datetime`]https://docs.rs/fits-header/latest/fits_header/fn.format_datetime.html).
- Extending the typed read/write layer: implement
  [`FromCard`]https://docs.rs/fits-header/latest/fits_header/trait.FromCard.html for a
  new read type behind `Header::get`, or
  [`IntoValue`]https://docs.rs/fits-header/latest/fits_header/trait.IntoValue.html for
  a new write type behind `Header::set`.