Skip to main content

xisf_core/
table.rs

1//! Table properties: `<Structure>`, `<Table>`, and the rows and cells in one.
2//!
3//! A table is the one property type whose value cannot be a `<Property>`
4//! element. Its shape lives in a `<Structure>` -- an ordered list of typed
5//! fields -- and its data in `<Row>`/`<Cell>` elements underneath a `<Table>`.
6//!
7//! The structure can be shared: a `<Table>` either contains its own
8//! `<Structure>` or carries a `<Reference>` to a standalone one defined at the
9//! root. That is the same association mechanism used for resolutions and
10//! thumbnails, and it exists so a catalogue's column layout is written once
11//! however many tables use it.
12
13use crate::err;
14use crate::error::Result;
15use crate::header::{DataRef, Element, Header};
16use crate::property::PropertyType;
17
18/// One column of a table: a name, a type, and how to present it.
19#[derive(Clone, PartialEq, Debug)]
20pub struct Field {
21    /// The `id` attribute, a property identifier.
22    pub id: String,
23    pub kind: PropertyType,
24    /// A `format` specifier, which affects only how a value is *printed*.
25    pub format: Option<String>,
26    /// A `header`, for use as a column title.
27    pub header: Option<String>,
28}
29
30impl Field {
31    /// Parse a `<Field>` element.
32    pub fn parse(element: &Element) -> Result<Self> {
33        if element.name != "Field" {
34            return Err(err!(InvalidArgument, "expected <Field>, got <{}>", element.name));
35        }
36        let id =
37            element.attr("id").ok_or_else(|| err!(BadHeader, "a <Field> has no id"))?.to_string();
38        let name =
39            element.attr("type").ok_or_else(|| err!(BadHeader, "<Field id={id:?}> has no type"))?;
40        Ok(Field {
41            kind: PropertyType::parse(name)?,
42            id,
43            format: element.attr("format").map(str::to_owned),
44            header: element.attr("header").map(str::to_owned),
45        })
46    }
47}
48
49/// A `<Structure>` element: the ordered fields of a table.
50#[derive(Clone, PartialEq, Debug)]
51pub struct Structure {
52    /// The `uid`, present when the structure stands alone to be referenced.
53    pub uid: Option<String>,
54    pub fields: Vec<Field>,
55}
56
57impl Structure {
58    /// Parse a `<Structure>` element.
59    pub fn parse(element: &Element) -> Result<Self> {
60        if element.name != "Structure" {
61            return Err(err!(InvalidArgument, "expected <Structure>, got <{}>", element.name));
62        }
63        let fields =
64            element.children_named("Field").map(Field::parse).collect::<Result<Vec<_>>>()?;
65        if fields.is_empty() {
66            return Err(err!(BadHeader, "a <Structure> must have at least one <Field>"));
67        }
68        // "Field property identifiers must be unique, i.e., two or more fields
69        // pertaining to the same table cannot have the same property
70        // identifier." A column is found by the position of the first field
71        // with a given id, so a duplicate makes the second column permanently
72        // unreachable and hands its values to whoever asks for the first --
73        // right ascensions read as declinations, and the table looks whole.
74        for (index, field) in fields.iter().enumerate() {
75            if fields[..index].iter().any(|earlier| earlier.id == field.id) {
76                return Err(err!(
77                    BadHeader,
78                    "two fields of a <Structure> share the identifier {:?}",
79                    field.id
80                ));
81            }
82        }
83        Ok(Structure { uid: element.attr("uid").map(str::to_owned), fields })
84    }
85}
86
87/// One cell's value.
88///
89/// A cell is written exactly as a property value would be, minus the `id`,
90/// `type` and `format` attributes it inherits from its field: a scalar in a
91/// `value` attribute, a short string as character data, anything larger in a
92/// data block that [`crate::Reader`] reads through [`Cell::data`].
93#[derive(Clone, PartialEq, Debug)]
94pub struct Cell {
95    /// The `value` attribute, for scalars and time points.
96    pub value: Option<String>,
97    /// The block this cell's value lives in, or the character data it holds
98    /// directly -- both live on the [`DataRef`], as they do for a property.
99    pub data: DataRef,
100}
101
102impl Cell {
103    /// Parse a `<Cell>` element.
104    pub fn parse(element: &Element) -> Result<Self> {
105        if element.name != "Cell" {
106            return Err(err!(InvalidArgument, "expected <Cell>, got <{}>", element.name));
107        }
108        Ok(Cell { value: element.attr("value").map(str::to_owned), data: element.data.clone() })
109    }
110
111    /// The cell's textual value, if it has one in the header.
112    ///
113    /// `None` means the value is in a data block, not that the cell is empty.
114    ///
115    /// Character data is preferred over a `value` attribute. A cell
116    /// "serializes its corresponding table cell value exactly as a Property
117    /// element serializing an XISF property of the corresponding field type",
118    /// and a String property "shall not have a value attribute" -- which
119    /// Revision 1 corrected the specification's own table examples for. So a
120    /// `value` on a string cell is the malformed half and must not win.
121    pub fn as_str(&self) -> Option<&str> {
122        if self.data.location.is_some() {
123            return None;
124        }
125        self.data.text.as_deref().or(self.value.as_deref())
126    }
127}
128
129/// A `<Table>` element: a table property, with its structure resolved.
130#[derive(Clone, PartialEq, Debug)]
131pub struct Table {
132    /// The `id` attribute: the property this table serialises.
133    pub id: String,
134    pub structure: Structure,
135    pub rows: Vec<Vec<Cell>>,
136    pub caption: Option<String>,
137    pub comment: Option<String>,
138}
139
140impl Table {
141    /// Parse a `<Table>` element, resolving its structure against `header`.
142    ///
143    /// The structure may be a child or a `<Reference>` to a standalone one,
144    /// so the whole header is needed to make sense of a single table.
145    pub fn parse(element: &Element, header: &Header) -> Result<Self> {
146        if element.name != "Table" {
147            return Err(err!(InvalidArgument, "expected <Table>, got <{}>", element.name));
148        }
149        let id =
150            element.attr("id").ok_or_else(|| err!(BadHeader, "a <Table> has no id"))?.to_string();
151
152        let structure = match header.associated(element, "Structure").first() {
153            Some(found) => Structure::parse(found)?,
154            None => {
155                return Err(err!(
156                    BadHeader,
157                    "<Table id={id:?}> has neither a <Structure> nor a reference to one"
158                ));
159            }
160        };
161
162        let mut rows = Vec::new();
163        for row in element.children_named("Row") {
164            let cells = row.children_named("Cell").map(Cell::parse).collect::<Result<Vec<_>>>()?;
165            // The spec requires one cell per field. A row with the wrong
166            // number of cells cannot be read column-wise at all: which field
167            // a given cell belongs to is decided by position and nothing else.
168            if cells.len() != structure.fields.len() {
169                return Err(err!(
170                    BadHeader,
171                    "<Table id={id:?}> row {} has {} cells but the structure declares {} fields",
172                    rows.len(),
173                    cells.len(),
174                    structure.fields.len()
175                ));
176            }
177            rows.push(cells);
178        }
179
180        // `rows` and `columns` are optional, but when written they must agree
181        // with the data. A disagreement means the file was assembled wrongly.
182        let declared = |name: &str| -> Result<Option<usize>> {
183            match element.attr(name) {
184                None => Ok(None),
185                Some(text) => text.trim().parse::<usize>().map(Some).map_err(|_| {
186                    err!(BadAttribute, "<Table id={id:?}> {name}={text:?} is not a count")
187                }),
188            }
189        };
190        if let Some(count) = declared("rows")?
191            && count != rows.len()
192        {
193            return Err(err!(
194                BadHeader,
195                "<Table id={id:?}> declares {count} rows but serialises {}",
196                rows.len()
197            ));
198        }
199        if let Some(count) = declared("columns")?
200            && count != structure.fields.len()
201        {
202            return Err(err!(
203                BadHeader,
204                "<Table id={id:?}> declares {count} columns but its structure has {}",
205                structure.fields.len()
206            ));
207        }
208
209        Ok(Table {
210            id,
211            structure,
212            rows,
213            caption: element.attr("caption").map(str::to_owned),
214            comment: element.attr("comment").map(str::to_owned),
215        })
216    }
217
218    /// The index of a field by id.
219    pub fn column(&self, id: &str) -> Option<usize> {
220        self.structure.fields.iter().position(|f| f.id == id)
221    }
222
223    /// One row's cell for a named field.
224    pub fn cell(&self, row: usize, id: &str) -> Option<&Cell> {
225        self.rows.get(row)?.get(self.column(id)?)
226    }
227}