rustronomy_fits/
extensions.rs

1/*
2    Copyright (C) 2022 Raúl Wolters
3
4    This file is part of rustronomy-fits.
5
6    rustronomy is free software: you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation, either version 3 of the License, or
9    (at your option) any later version.
10
11    rustronomy is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with rustronomy.  If not, see <http://www.gnu.org/licenses/>.
18*/
19
20use std::{
21  error::Error,
22  fmt::{Display, Formatter},
23};
24
25use crate::{
26  io_err::{self, InvalidFitsFileErr as IFFErr},
27  raw::{raw_io::RawFitsWriter, BlockSized},
28};
29
30use self::{
31  image::{ImgParser, TypedImage},
32  table::{AsciiTable, AsciiTblParser},
33};
34
35//FITS standard-conforming extensions
36pub mod image;
37pub mod table;
38
39#[derive(Debug, Clone)]
40pub enum Extension {
41  /*  THIS IS PART OF THE USER-FACING API
42      Users receive a FITS struct, within which they may access the header and
43      data. The data is provided as a variant of this Extension struct.
44
45      All implementations of this struct are however internal!
46  */
47  Corrupted,
48  Image(TypedImage),
49  AsciiTable(AsciiTable),
50}
51
52impl BlockSized for Extension {
53  fn get_block_len(&self) -> usize {
54    use Extension::*;
55    match &self {
56      Corrupted => 0, //corrupted data is disregarded
57      Image(img) => img.get_block_len(),
58      AsciiTable(tbl) => tbl.get_block_len(),
59    }
60  }
61}
62
63impl Display for Extension {
64  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
65    use Extension::*;
66    match &self {
67      Corrupted => write!(f, "(CORRUPTED_DATA)"),
68      Image(img) => write!(f, "{}", img.xprint()),
69      AsciiTable(tbl) => write!(f, "{}", tbl.xprint()),
70    }
71  }
72}
73
74impl Extension {
75  pub(crate) fn write_to_buffer(self, writer: &mut RawFitsWriter) -> Result<(), Box<dyn Error>> {
76    use Extension::*;
77    match self {
78      Corrupted => return Err(Box::new(IFFErr::new(io_err::CORRUPTED))),
79      Image(img) => ImgParser::encode_img(img, writer),
80      AsciiTable(tbl) => AsciiTblParser::encode_tbl(tbl, writer),
81    }
82  }
83}
84
85pub(crate) trait ExtensionPrint {
86  //This tiny trait is used for printing concise descriptions of Extensions
87  fn xprint(&self) -> String;
88}