use crate::model::{Invariant, Island, Loss, Mark};
use serde_json::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KnownIslandType {
Table,
Image,
}
impl KnownIslandType {
pub fn as_str(self) -> &'static str {
match self {
Self::Table => "table",
Self::Image => "image",
}
}
pub fn parse(s: &str) -> Option<Self> {
match s {
"table" => Some(Self::Table),
"image" => Some(Self::Image),
_ => None,
}
}
pub fn default_loss(self) -> Loss {
match self {
Self::Table => Loss::Lossless,
Self::Image => Loss::Lossless,
}
}
pub fn cell_marks(self, props: &Value) -> Vec<(String, Vec<Mark>)> {
match self {
Self::Table => crate::serial::table_cells(props),
Self::Image => Vec::new(),
}
}
pub fn normalize_props(self, props: &mut Value) {
match self {
Self::Table => crate::serial::normalize_table_props(props),
Self::Image => {}
}
}
pub fn shape_error(self, props: &Value) -> Option<Invariant> {
match self {
Self::Table => crate::serial::table_shape_error(props),
Self::Image => None,
}
}
}
pub(crate) fn normalize_island_structure(island: &mut Island) {
if let Some(k) = KnownIslandType::parse(&island.island_type) {
k.normalize_props(&mut island.props);
}
}
pub(crate) fn island_cell_marks(island: &Island) -> Vec<(String, Vec<Mark>)> {
match KnownIslandType::parse(&island.island_type) {
Some(k) => k.cell_marks(&island.props),
None => Vec::new(),
}
}
pub(crate) fn island_shape_error(island: &Island) -> Option<Invariant> {
KnownIslandType::parse(&island.island_type).and_then(|k| k.shape_error(&island.props))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_types_round_trip() {
for k in [KnownIslandType::Table, KnownIslandType::Image] {
assert_eq!(KnownIslandType::parse(k.as_str()), Some(k));
}
}
#[test]
fn unknown_type_parses_to_none() {
assert_eq!(KnownIslandType::parse("figure"), None);
assert_eq!(KnownIslandType::parse(""), None);
}
}