Skip to main content

rstest_bdd/datatable/
spec.rs

1//! Header and row specifications for the datatable runtime.
2
3use std::{collections::HashMap, error::Error as StdError};
4
5use super::DataTableError;
6
7/// Metadata describing the header row of a data table.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct HeaderSpec {
10    /// Column names in their original order.
11    columns: Vec<String>,
12    /// Mapping from column names to their zero-based positions.
13    index: HashMap<String, usize>,
14}
15
16impl HeaderSpec {
17    /// Builds a [`HeaderSpec`] from the supplied header row.
18    ///
19    /// # Errors
20    ///
21    /// Returns [`DataTableError::DuplicateHeader`] when column names repeat.
22    pub fn new(header_row: Vec<String>) -> Result<Self, DataTableError> {
23        let mut index = HashMap::with_capacity(header_row.len());
24        for (idx, column) in header_row.iter().enumerate() {
25            if index.insert(column.clone(), idx).is_some() {
26                return Err(DataTableError::DuplicateHeader {
27                    column: column.clone(),
28                });
29            }
30        }
31        Ok(Self {
32            columns: header_row,
33            index,
34        })
35    }
36
37    /// Returns the number of columns declared in the header.
38    #[must_use]
39    pub fn len(&self) -> usize { self.columns.len() }
40
41    /// Returns `true` when the header is empty.
42    #[must_use]
43    pub fn is_empty(&self) -> bool { self.columns.is_empty() }
44
45    /// Fetches a column name by index.
46    #[must_use]
47    pub fn column(&self, index: usize) -> Option<&str> {
48        self.columns.get(index).map(String::as_str)
49    }
50
51    /// Looks up the index for a column, returning an error when missing.
52    ///
53    /// # Errors
54    ///
55    /// Returns [`DataTableError::MissingColumn`] when the column is absent.
56    pub fn require(&self, name: &str, row_number: usize) -> Result<usize, DataTableError> {
57        self.index
58            .get(name)
59            .copied()
60            .ok_or_else(|| DataTableError::MissingColumn {
61                row_number,
62                column: name.to_owned(),
63            })
64    }
65
66    /// Returns the names of all columns.
67    #[must_use]
68    pub fn columns(&self) -> &[String] { &self.columns }
69}
70
71/// Representation of a single row within a data table.
72#[derive(Debug)]
73pub struct RowSpec<'h> {
74    /// Header metadata, when the table has a header row.
75    header: Option<&'h HeaderSpec>,
76    /// One-based row number including the header.
77    row_number: usize,
78    /// Zero-based row index excluding the header.
79    index: usize,
80    /// Remaining cell values in their current order.
81    cells: Vec<String>,
82    /// Original column positions mapped to current cell positions.
83    indices: Vec<Option<usize>>,
84}
85
86impl<'h> RowSpec<'h> {
87    /// Create a row specification with all cells initially available.
88    pub(super) fn new(
89        header: Option<&'h HeaderSpec>,
90        row_number: usize,
91        index: usize,
92        cells: Vec<String>,
93    ) -> Self {
94        let indices = (0..cells.len()).map(Some).collect();
95        Self {
96            header,
97            row_number,
98            index,
99            cells,
100            indices,
101        }
102    }
103
104    /// Returns the 1-based row number, including any header.
105    #[must_use]
106    pub fn row_number(&self) -> usize { self.row_number }
107
108    /// Returns the zero-based row index relative to the data rows (excluding
109    /// the header).
110    #[must_use]
111    pub fn index(&self) -> usize { self.index }
112
113    /// Returns the number of cells in the row.
114    #[must_use]
115    pub fn len(&self) -> usize { self.cells.len() }
116
117    /// Returns `true` when the row contains no cells.
118    #[must_use]
119    pub fn is_empty(&self) -> bool { self.cells.is_empty() }
120
121    /// Provides immutable access to the underlying cells.
122    #[must_use]
123    pub fn cells(&self) -> &[String] { &self.cells }
124
125    /// Retrieves the cell at a given index.
126    ///
127    /// # Errors
128    ///
129    /// Returns [`DataTableError::MissingCell`] when the index is out of range.
130    pub fn cell(&self, column_index: usize) -> Result<&str, DataTableError> {
131        let Some(position) = self.indices.get(column_index).copied().flatten() else {
132            return Err(DataTableError::MissingCell {
133                row_number: self.row_number,
134                column_index: column_index + 1,
135            });
136        };
137        self.cells
138            .get(position)
139            .map(String::as_str)
140            .ok_or(DataTableError::MissingCell {
141                row_number: self.row_number,
142                column_index: column_index + 1,
143            })
144    }
145
146    /// Removes and returns the cell at `column_index`.
147    ///
148    /// # Errors
149    ///
150    /// Returns [`DataTableError::MissingCell`] when the index is out of range.
151    pub fn take_cell(&mut self, column_index: usize) -> Result<String, DataTableError> {
152        let Some(position) = self.indices.get(column_index).copied().flatten() else {
153            return Err(DataTableError::MissingCell {
154                row_number: self.row_number,
155                column_index: column_index + 1,
156            });
157        };
158        let value = self.cells.remove(position);
159        if let Some(slot) = self.indices.get_mut(column_index) {
160            *slot = None;
161        }
162        for slot in self.indices.iter_mut().flatten() {
163            if *slot > position {
164                *slot -= 1;
165            }
166        }
167        Ok(value)
168    }
169
170    /// Retrieves the cell associated with a header column.
171    ///
172    /// # Errors
173    ///
174    /// Returns [`DataTableError::MissingHeader`] or
175    /// [`DataTableError::MissingColumn`] when the lookup fails.
176    pub fn column(&self, name: &str) -> Result<&str, DataTableError> {
177        let header = self.header.ok_or(DataTableError::MissingHeader)?;
178        let index = header.require(name, self.row_number)?;
179        self.cell(index)
180    }
181
182    /// Removes and returns the cell associated with a header column.
183    ///
184    /// # Errors
185    ///
186    /// Returns [`DataTableError::MissingHeader`] or
187    /// [`DataTableError::MissingColumn`] when the lookup fails.
188    pub fn take_column(&mut self, name: &str) -> Result<String, DataTableError> {
189        let header = self.header.ok_or(DataTableError::MissingHeader)?;
190        let index = header.require(name, self.row_number)?;
191        self.take_cell(index)
192    }
193
194    /// Parses a cell using a user-supplied parser.
195    ///
196    /// # Errors
197    ///
198    /// Returns [`DataTableError::MissingCell`] when the index is out of range
199    /// or [`DataTableError::CellParse`] when the parser fails.
200    pub fn parse_with<F, T, E>(&self, column_index: usize, parser: F) -> Result<T, DataTableError>
201    where
202        F: FnOnce(&str) -> Result<T, E>,
203        E: StdError + Send + Sync + 'static,
204    {
205        let value = self.cell(column_index)?;
206        parser(value).map_err(|err| {
207            let label = self
208                .header
209                .and_then(|h| h.column(column_index))
210                .map(ToOwned::to_owned);
211            DataTableError::cell_parse(self.row_number, column_index, label, err)
212        })
213    }
214
215    /// Parses a named column using a user-supplied parser.
216    ///
217    /// # Errors
218    ///
219    /// Returns [`DataTableError::MissingHeader`],
220    /// [`DataTableError::MissingColumn`], or
221    /// [`DataTableError::CellParse`] when access or parsing fails.
222    pub fn parse_column_with<F, T, E>(&self, name: &str, parser: F) -> Result<T, DataTableError>
223    where
224        F: FnOnce(&str) -> Result<T, E>,
225        E: StdError + Send + Sync + 'static,
226    {
227        let header = self.header.ok_or(DataTableError::MissingHeader)?;
228        let index = header.require(name, self.row_number)?;
229        self.parse_with(index, parser)
230    }
231}