use std::fmt;
use std::sync::Arc;
use techy::serialize::{DeserializeContext, DeserializeError, SerialValue};
use crate::model::addr::TreeId;
use crate::model::names::{ElementName, Name};
use crate::dump::session::PayloadReaders;
use crate::lang::{Flm, PresPayload};
use super::length::Length;
use super::names;
pub(crate) fn text(value: impl Into<String>) -> SerialValue {
SerialValue::Str(value.into())
}
pub(crate) fn map(entries: Vec<(&str, SerialValue)>) -> SerialValue {
SerialValue::Map(entries.into_iter().map(|(key, value)| (String::from(key), value)).collect())
}
fn names(list: &[Name]) -> SerialValue {
SerialValue::List(list.iter().map(|name| text(name.as_str())).collect())
}
fn push_opt(
entries: &mut Vec<(&'static str, SerialValue)>,
key: &'static str,
value: Option<SerialValue>,
) {
if let Some(value) = value {
entries.push((key, value));
}
}
pub(crate) fn bad(element: &str, detail: impl fmt::Display) -> DeserializeError {
DeserializeError::failed(format!("the payload of `{element}`: {detail}"))
}
pub(crate) fn entries<'v>(
element: &str,
value: &'v SerialValue,
) -> Result<&'v [(String, SerialValue)], DeserializeError> {
match value {
SerialValue::Map(entries) => Ok(entries),
other => Err(bad(element, format!("expected a map, found {other:?}"))),
}
}
pub(crate) fn field<'v>(
entries: &'v [(String, SerialValue)],
key: &str,
) -> Option<&'v SerialValue> {
entries.iter().find(|(k, _)| k == key).map(|(_, v)| v)
}
fn opt_string(
element: &str,
entries: &[(String, SerialValue)],
key: &str,
) -> Result<Option<String>, DeserializeError> {
match field(entries, key) {
None | Some(SerialValue::Null) => Ok(None),
Some(SerialValue::Str(s)) => Ok(Some(s.clone())),
Some(other) => Err(bad(element, format!("`{key}` must be a string, found {other:?}"))),
}
}
pub(crate) fn string(
element: &str,
entries: &[(String, SerialValue)],
key: &str,
) -> Result<String, DeserializeError> {
opt_string(element, entries, key)?.ok_or_else(|| bad(element, format!("`{key}` is missing")))
}
fn opt_int(
element: &str,
entries: &[(String, SerialValue)],
key: &str,
) -> Result<Option<i64>, DeserializeError> {
match field(entries, key) {
None | Some(SerialValue::Null) => Ok(None),
Some(SerialValue::Int(n)) => Ok(Some(*n)),
Some(other) => Err(bad(element, format!("`{key}` must be an integer, found {other:?}"))),
}
}
fn int(
element: &str,
entries: &[(String, SerialValue)],
key: &str,
) -> Result<i64, DeserializeError> {
opt_int(element, entries, key)?.ok_or_else(|| bad(element, format!("`{key}` is missing")))
}
fn name_list(
element: &str,
entries: &[(String, SerialValue)],
key: &str,
) -> Result<Vec<Name>, DeserializeError> {
match field(entries, key) {
None | Some(SerialValue::Null) => Ok(Vec::new()),
Some(SerialValue::List(items)) => items
.iter()
.map(|item| match item {
SerialValue::Str(s) => Ok(Name::from(s.as_str())),
other => Err(bad(element, format!("`{key}` holds a non-string {other:?}"))),
})
.collect(),
Some(other) => Err(bad(element, format!("`{key}` must be a list, found {other:?}"))),
}
}
fn name_opt(
element: &str,
entries: &[(String, SerialValue)],
key: &str,
) -> Result<Option<Name>, DeserializeError> {
Ok(opt_string(element, entries, key)?.map(Name::from))
}
fn doc_role_opt(
element: &str,
entries: &[(String, SerialValue)],
) -> Result<Option<DocRole>, DeserializeError> {
match opt_string(element, entries, "doc_role")? {
None => Ok(None),
Some(name) => DocRole::parse(&name)
.map(Some)
.ok_or_else(|| bad(element, format!("unknown document role `{name}`"))),
}
}
fn small(element: &str, key: &str, value: i64, max: i64) -> Result<u16, DeserializeError> {
if (0..=max).contains(&value) {
Ok(value as u16)
} else {
Err(bad(element, format!("`{key}` = {value} is outside 0..={max}")))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SpanStyle {
Emphasis,
Bold,
Italic,
Monospace,
Underline,
SmallCaps,
Superscript,
Subscript,
UnresolvedReference,
}
impl SpanStyle {
pub const ALL: [SpanStyle; 9] = [
SpanStyle::Emphasis,
SpanStyle::Bold,
SpanStyle::Italic,
SpanStyle::Monospace,
SpanStyle::Underline,
SpanStyle::SmallCaps,
SpanStyle::Superscript,
SpanStyle::Subscript,
SpanStyle::UnresolvedReference,
];
pub fn as_str(self) -> &'static str {
match self {
SpanStyle::Emphasis => "emph",
SpanStyle::Bold => "bold",
SpanStyle::Italic => "italic",
SpanStyle::Monospace => "monospace",
SpanStyle::Underline => "underline",
SpanStyle::SmallCaps => "small-caps",
SpanStyle::Superscript => "superscript",
SpanStyle::Subscript => "subscript",
SpanStyle::UnresolvedReference => "unresolved-reference",
}
}
pub fn parse(name: &str) -> Option<SpanStyle> {
SpanStyle::ALL.into_iter().find(|style| style.as_str() == name)
}
}
impl fmt::Display for SpanStyle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum VerbatimKind {
#[default]
Text,
Code,
Identifier,
}
impl VerbatimKind {
pub const ALL: [VerbatimKind; 3] =
[VerbatimKind::Text, VerbatimKind::Code, VerbatimKind::Identifier];
pub fn as_str(self) -> &'static str {
match self {
VerbatimKind::Text => "text",
VerbatimKind::Code => "code",
VerbatimKind::Identifier => "a",
}
}
pub fn parse(name: &str) -> Option<VerbatimKind> {
VerbatimKind::ALL.into_iter().find(|kind| kind.as_str() == name)
}
}
impl fmt::Display for VerbatimKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VerbatimDisplay {
Inline,
Block,
}
impl VerbatimDisplay {
pub fn as_str(self) -> &'static str {
match self {
VerbatimDisplay::Inline => "inline",
VerbatimDisplay::Block => "block",
}
}
pub fn parse(name: &str) -> Option<VerbatimDisplay> {
match name {
"inline" => Some(VerbatimDisplay::Inline),
"block" => Some(VerbatimDisplay::Block),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ImageDisplay {
#[default]
Inline,
Block,
}
impl ImageDisplay {
pub fn as_str(self) -> &'static str {
match self {
ImageDisplay::Inline => "inline",
ImageDisplay::Block => "block",
}
}
pub fn parse(name: &str) -> Option<ImageDisplay> {
match name {
"inline" => Some(ImageDisplay::Inline),
"block" => Some(ImageDisplay::Block),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MathDisplay {
Inline,
Display,
}
impl MathDisplay {
pub fn as_str(self) -> &'static str {
match self {
MathDisplay::Inline => "inline",
MathDisplay::Display => "display",
}
}
pub fn parse(name: &str) -> Option<MathDisplay> {
match name {
"inline" => Some(MathDisplay::Inline),
"display" => Some(MathDisplay::Display),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum LineAlign {
#[default]
Left,
Center,
Right,
}
impl LineAlign {
pub fn as_str(self) -> &'static str {
match self {
LineAlign::Left => "left",
LineAlign::Center => "center",
LineAlign::Right => "right",
}
}
pub fn parse(name: &str) -> Option<LineAlign> {
match name {
"left" => Some(LineAlign::Left),
"center" => Some(LineAlign::Center),
"right" => Some(LineAlign::Right),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DocRole {
Endnotes,
Footnote,
NoteRef,
BackLink,
Bibliography,
BiblioRef,
Toc,
}
impl DocRole {
pub const ALL: [DocRole; 7] = [
DocRole::Endnotes,
DocRole::Footnote,
DocRole::NoteRef,
DocRole::BackLink,
DocRole::Bibliography,
DocRole::BiblioRef,
DocRole::Toc,
];
pub fn as_str(self) -> &'static str {
match self {
DocRole::Endnotes => "endnotes",
DocRole::Footnote => "footnote",
DocRole::NoteRef => "noteref",
DocRole::BackLink => "backlink",
DocRole::Bibliography => "bibliography",
DocRole::BiblioRef => "biblioref",
DocRole::Toc => "toc",
}
}
pub fn parse(name: &str) -> Option<DocRole> {
DocRole::ALL.into_iter().find(|role| role.as_str() == name)
}
}
impl fmt::Display for DocRole {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ParPayload {
pub anchor: Option<String>,
}
impl PresPayload for ParPayload {
fn project(&self) -> SerialValue {
let mut entries = Vec::new();
push_opt(&mut entries, "anchor", self.anchor.as_deref().map(text));
map(entries)
}
}
impl ParPayload {
pub fn from_projection(value: &SerialValue) -> Result<ParPayload, DeserializeError> {
let entries = entries(names::PAR, value)?;
Ok(ParPayload { anchor: opt_string(names::PAR, entries, "anchor")? })
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct BlockPayload {
pub role: Option<Name>,
pub kinds: Vec<Name>,
pub anchor: Option<String>,
pub doc_role: Option<DocRole>,
}
impl PresPayload for BlockPayload {
fn project(&self) -> SerialValue {
let mut entries = Vec::new();
push_opt(&mut entries, "role", self.role.as_ref().map(|r| text(r.as_str())));
if !self.kinds.is_empty() {
entries.push(("kinds", names(&self.kinds)));
}
push_opt(&mut entries, "anchor", self.anchor.as_deref().map(text));
push_opt(&mut entries, "doc_role", self.doc_role.map(|r| text(r.as_str())));
map(entries)
}
}
impl BlockPayload {
pub fn from_projection(value: &SerialValue) -> Result<BlockPayload, DeserializeError> {
let e = entries(names::BLOCK, value)?;
Ok(BlockPayload {
role: name_opt(names::BLOCK, e, "role")?,
kinds: name_list(names::BLOCK, e, "kinds")?,
anchor: opt_string(names::BLOCK, e, "anchor")?,
doc_role: doc_role_opt(names::BLOCK, e)?,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeadingPayload {
pub name: Name,
pub level: u8,
pub in_toc: bool,
pub anchor: Option<String>,
pub number: Option<String>,
}
impl PresPayload for HeadingPayload {
fn project(&self) -> SerialValue {
let mut entries = vec![
("name", text(self.name.as_str())),
("level", SerialValue::Int(i64::from(self.level))),
("in_toc", SerialValue::Bool(self.in_toc)),
];
push_opt(&mut entries, "anchor", self.anchor.as_deref().map(text));
push_opt(&mut entries, "number", self.number.as_deref().map(text));
map(entries)
}
}
impl HeadingPayload {
pub fn from_projection(
element: &str,
value: &SerialValue,
) -> Result<HeadingPayload, DeserializeError> {
let e = entries(element, value)?;
let name = Name::from(string(element, e, "name")?.as_str());
let level = int(element, e, "level")?;
let level = small(element, "level", level, i64::from(u8::MAX))? as u8;
let in_toc = match field(e, "in_toc") {
Some(SerialValue::Bool(value)) => *value,
None | Some(SerialValue::Null) => {
return Err(bad(element, "`in_toc` is missing"));
}
Some(other) => {
return Err(bad(element, format!("`in_toc` must be a boolean, found {other:?}")));
}
};
Ok(HeadingPayload {
name,
level,
in_toc,
anchor: opt_string(element, e, "anchor")?,
number: opt_string(element, e, "number")?,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SpanPayload {
pub style: Option<SpanStyle>,
pub role: Option<Name>,
pub kinds: Vec<Name>,
pub anchor: Option<String>,
pub doc_role: Option<DocRole>,
}
impl PresPayload for SpanPayload {
fn project(&self) -> SerialValue {
let mut entries = Vec::new();
push_opt(&mut entries, "style", self.style.map(|s| text(s.as_str())));
push_opt(&mut entries, "role", self.role.as_ref().map(|r| text(r.as_str())));
if !self.kinds.is_empty() {
entries.push(("kinds", names(&self.kinds)));
}
push_opt(&mut entries, "anchor", self.anchor.as_deref().map(text));
push_opt(&mut entries, "doc_role", self.doc_role.map(|r| text(r.as_str())));
map(entries)
}
}
impl SpanPayload {
pub fn from_projection(value: &SerialValue) -> Result<SpanPayload, DeserializeError> {
let e = entries(names::SPAN, value)?;
let style = match opt_string(names::SPAN, e, "style")? {
None => None,
Some(name) => Some(
SpanStyle::parse(&name)
.ok_or_else(|| bad(names::SPAN, format!("unknown style `{name}`")))?,
),
};
Ok(SpanPayload {
style,
role: name_opt(names::SPAN, e, "role")?,
kinds: name_list(names::SPAN, e, "kinds")?,
anchor: opt_string(names::SPAN, e, "anchor")?,
doc_role: doc_role_opt(names::SPAN, e)?,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ListPayload {
pub kinds: Vec<Name>,
pub anchor: Option<String>,
pub entry_anchors: Vec<Option<String>>,
pub entry_levels: Vec<Option<u32>>,
}
impl PresPayload for ListPayload {
fn project(&self) -> SerialValue {
let mut entries = Vec::new();
if !self.kinds.is_empty() {
entries.push(("kinds", names(&self.kinds)));
}
push_opt(&mut entries, "anchor", self.anchor.as_deref().map(text));
if !self.entry_anchors.is_empty() {
let anchors = self
.entry_anchors
.iter()
.map(|anchor| anchor.as_deref().map_or(SerialValue::Null, text))
.collect();
entries.push(("entry_anchors", SerialValue::List(anchors)));
}
if !self.entry_levels.is_empty() {
let levels = self
.entry_levels
.iter()
.map(|level| level.map_or(SerialValue::Null, |level| SerialValue::Int(i64::from(level))))
.collect();
entries.push(("entry_levels", SerialValue::List(levels)));
}
map(entries)
}
}
impl ListPayload {
pub fn from_projection(value: &SerialValue) -> Result<ListPayload, DeserializeError> {
let e = entries(names::LIST, value)?;
let entry_anchors = match field(e, "entry_anchors") {
None | Some(SerialValue::Null) => Vec::new(),
Some(SerialValue::List(items)) => items
.iter()
.map(|item| match item {
SerialValue::Null => Ok(None),
SerialValue::Str(s) => Ok(Some(s.clone())),
other => Err(bad(
names::LIST,
format!("`entry_anchors` holds a non-string {other:?}"),
)),
})
.collect::<Result<Vec<_>, _>>()?,
Some(other) => {
return Err(bad(names::LIST, format!("`entry_anchors` must be a list, found {other:?}")));
}
};
let bad_level = |found: &dyn std::fmt::Debug| {
bad(
names::LIST,
format!(
"‘entry_levels’ must be a list of nulls and integers in 0..={} (found {found:?})",
u32::MAX
),
)
};
let entry_levels = match field(e, "entry_levels") {
None | Some(SerialValue::Null) => Vec::new(),
Some(SerialValue::List(items)) => items
.iter()
.map(|item| match item {
SerialValue::Null => Ok(None),
SerialValue::Int(n) => u32::try_from(*n).map(Some).map_err(|_| bad_level(n)),
other => Err(bad_level(other)),
})
.collect::<Result<Vec<_>, _>>()?,
Some(other) => return Err(bad_level(other)),
};
Ok(ListPayload {
kinds: name_list(names::LIST, e, "kinds")?,
anchor: opt_string(names::LIST, e, "anchor")?,
entry_anchors,
entry_levels,
})
}
}
pub const MAX_CELLS_POSITIONS: u64 = 1_000_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CellAlign {
Left,
Center,
Right,
}
impl CellAlign {
pub fn as_str(self) -> &'static str {
match self {
CellAlign::Left => "left",
CellAlign::Center => "center",
CellAlign::Right => "right",
}
}
pub fn parse(name: &str) -> Option<CellAlign> {
match name {
"left" => Some(CellAlign::Left),
"center" => Some(CellAlign::Center),
"right" => Some(CellAlign::Right),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CellHeader {
Column,
Row,
}
impl CellHeader {
pub fn as_str(self) -> &'static str {
match self {
CellHeader::Column => "column",
CellHeader::Row => "row",
}
}
pub fn parse(name: &str) -> Option<CellHeader> {
match name {
"column" => Some(CellHeader::Column),
"row" => Some(CellHeader::Row),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CellEdge {
Above,
Below,
Left,
Right,
}
impl CellEdge {
pub fn as_str(self) -> &'static str {
match self {
CellEdge::Above => "above",
CellEdge::Below => "below",
CellEdge::Left => "left",
CellEdge::Right => "right",
}
}
pub fn parse(name: &str) -> Option<CellEdge> {
match name {
"above" => Some(CellEdge::Above),
"below" => Some(CellEdge::Below),
"left" => Some(CellEdge::Left),
"right" => Some(CellEdge::Right),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CellSpec {
pub row: u32,
pub col: u32,
pub row_span: u32,
pub col_span: u32,
pub align: Option<CellAlign>,
pub header: Option<CellHeader>,
pub rules: Vec<CellEdge>,
pub styles: Vec<Name>,
}
impl CellSpec {
pub fn at(row: u32, col: u32) -> CellSpec {
CellSpec {
row,
col,
row_span: 1,
col_span: 1,
align: None,
header: None,
rules: Vec::new(),
styles: Vec::new(),
}
}
pub fn row_end(&self) -> u64 {
u64::from(self.row) + u64::from(self.row_span)
}
pub fn col_end(&self) -> u64 {
u64::from(self.col) + u64::from(self.col_span)
}
fn project(&self) -> SerialValue {
let mut e: Vec<(&'static str, SerialValue)> = vec![
("row", SerialValue::Int(i64::from(self.row))),
("col", SerialValue::Int(i64::from(self.col))),
];
if self.row_span != 1 {
e.push(("row_span", SerialValue::Int(i64::from(self.row_span))));
}
if self.col_span != 1 {
e.push(("col_span", SerialValue::Int(i64::from(self.col_span))));
}
push_opt(&mut e, "align", self.align.map(|align| text(align.as_str())));
push_opt(&mut e, "header", self.header.map(|header| text(header.as_str())));
if !self.rules.is_empty() {
let rules = self.rules.iter().map(|edge| text(edge.as_str())).collect();
e.push(("rules", SerialValue::List(rules)));
}
if !self.styles.is_empty() {
e.push(("styles", names(&self.styles)));
}
map(e)
}
fn from_projection(value: &SerialValue) -> Result<CellSpec, DeserializeError> {
const E: &str = names::CELLS;
let e = entries(E, value)?;
let count = |key: &str, value: i64, min: i64| -> Result<u32, DeserializeError> {
if (min..=i64::from(u32::MAX)).contains(&value) {
Ok(value as u32)
} else {
Err(bad(E, format!("a cell's `{key}` = {value} is outside {min}..={}", u32::MAX)))
}
};
let align = match opt_string(E, e, "align")? {
None => None,
Some(name) => Some(
CellAlign::parse(&name)
.ok_or_else(|| bad(E, format!("unknown cell alignment `{name}`")))?,
),
};
let header = match opt_string(E, e, "header")? {
None => None,
Some(name) => Some(
CellHeader::parse(&name)
.ok_or_else(|| bad(E, format!("unknown cell header kind `{name}`")))?,
),
};
let rules = name_list(E, e, "rules")?
.iter()
.map(|name| {
CellEdge::parse(name.as_str())
.ok_or_else(|| bad(E, format!("unknown cell edge `{name}`")))
})
.collect::<Result<Vec<_>, _>>()?;
Ok(CellSpec {
row: count("row", int(E, e, "row")?, 0)?,
col: count("col", int(E, e, "col")?, 0)?,
row_span: count("row_span", opt_int(E, e, "row_span")?.unwrap_or(1), 1)?,
col_span: count("col_span", opt_int(E, e, "col_span")?.unwrap_or(1), 1)?,
align,
header,
rules,
styles: name_list(E, e, "styles")?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GridPosition {
Empty,
TopLeft(usize),
Covered(usize),
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CellsPayload {
pub rows: u32,
pub cols: u32,
pub cells: Vec<CellSpec>,
}
impl PresPayload for CellsPayload {
fn project(&self) -> SerialValue {
map(vec![
("rows", SerialValue::Int(i64::from(self.rows))),
("cols", SerialValue::Int(i64::from(self.cols))),
("cells", SerialValue::List(self.cells.iter().map(CellSpec::project).collect())),
])
}
}
impl CellsPayload {
pub fn grid(&self) -> Vec<Vec<GridPosition>> {
let rows = self.rows as usize;
let cols = self.cols as usize;
let mut grid = vec![vec![GridPosition::Empty; cols]; rows];
for (index, cell) in self.cells.iter().enumerate() {
let row_end = cell.row_end().min(rows as u64) as usize;
let col_end = cell.col_end().min(cols as u64) as usize;
for (r, row) in grid.iter_mut().enumerate().take(row_end).skip(cell.row as usize) {
for (c, position) in row.iter_mut().enumerate().take(col_end).skip(cell.col as usize) {
if *position != GridPosition::Empty {
continue;
}
*position = if r == cell.row as usize && c == cell.col as usize {
GridPosition::TopLeft(index)
} else {
GridPosition::Covered(index)
};
}
}
}
grid
}
pub fn from_projection(value: &SerialValue) -> Result<CellsPayload, DeserializeError> {
const E: &str = names::CELLS;
let e = entries(E, value)?;
let size = |key: &str| -> Result<u32, DeserializeError> {
let value = int(E, e, key)?;
u32::try_from(value).map_err(|_| bad(E, format!("`{key}` = {value} is out of range")))
};
let rows = size("rows")?;
let cols = size("cols")?;
if u64::from(rows) * u64::from(cols) > MAX_CELLS_POSITIONS {
return Err(bad(
E,
format!("a grid of {rows} by {cols} exceeds {MAX_CELLS_POSITIONS} positions"),
));
}
let cells = match field(e, "cells") {
Some(SerialValue::List(items)) => {
items.iter().map(CellSpec::from_projection).collect::<Result<Vec<_>, _>>()?
}
Some(other) => return Err(bad(E, format!("`cells` must be a list, found {other:?}"))),
None => return Err(bad(E, "`cells` is missing")),
};
let payload = CellsPayload { rows, cols, cells };
payload.check().map_err(|detail| bad(E, detail))?;
Ok(payload)
}
fn check(&self) -> Result<(), String> {
for (index, cell) in self.cells.iter().enumerate() {
if cell.row_end() > u64::from(self.rows) || cell.col_end() > u64::from(self.cols) {
return Err(format!("the cell at index {index} reaches outside the grid"));
}
}
if self.cells.windows(2).any(|pair| (pair[0].row, pair[0].col) >= (pair[1].row, pair[1].col)) {
return Err("the cells are not in row-major order of their top-left positions".into());
}
let held = self.grid();
for (index, cell) in self.cells.iter().enumerate() {
for (r, row) in held.iter().enumerate().take(cell.row_end() as usize).skip(cell.row as usize) {
for position in row.iter().take(cell.col_end() as usize).skip(cell.col as usize) {
let holder = match *position {
GridPosition::TopLeft(i) | GridPosition::Covered(i) => i,
GridPosition::Empty => index,
};
if holder != index {
return Err(format!(
"the cell at index {index} overlaps the cell at index {holder} in row {r}"
));
}
}
}
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DroppedPayload {
pub condition: Name,
pub detail: String,
}
impl PresPayload for DroppedPayload {
fn project(&self) -> SerialValue {
map(vec![("condition", text(self.condition.as_str())), ("detail", text(&self.detail))])
}
}
impl DroppedPayload {
pub fn from_projection(value: &SerialValue) -> Result<DroppedPayload, DeserializeError> {
let e = entries(names::DROPPED, value)?;
Ok(DroppedPayload {
condition: Name::from(string(names::DROPPED, e, "condition")?),
detail: string(names::DROPPED, e, "detail")?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct LinesPayload;
impl PresPayload for LinesPayload {
fn project(&self) -> SerialValue {
map(Vec::new())
}
}
impl LinesPayload {
pub fn from_projection(value: &SerialValue) -> Result<LinesPayload, DeserializeError> {
entries(names::LINES, value)?;
Ok(LinesPayload)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct LinePayload {
pub indent_left: Length,
pub indent_right: Length,
pub align: LineAlign,
}
impl PresPayload for LinePayload {
fn project(&self) -> SerialValue {
map(vec![
("indent_left", text(self.indent_left.to_string())),
("indent_right", text(self.indent_right.to_string())),
("align", text(self.align.as_str())),
])
}
}
impl LinePayload {
pub fn from_projection(value: &SerialValue) -> Result<LinePayload, DeserializeError> {
let e = entries(names::LINE, value)?;
let length = |key: &str| -> Result<Length, DeserializeError> {
match opt_string(names::LINE, e, key)? {
None => Ok(Length::default()),
Some(written) => Length::parse(&written)
.map_err(|error| bad(names::LINE, format!("`{key}`: {error}"))),
}
};
let align = match opt_string(names::LINE, e, "align")? {
None => LineAlign::Left,
Some(name) => LineAlign::parse(&name)
.ok_or_else(|| bad(names::LINE, format!("unknown alignment `{name}`")))?,
};
Ok(LinePayload {
indent_left: length("indent_left")?,
indent_right: length("indent_right")?,
align,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerbatimPayload {
pub kind: VerbatimKind,
pub display: VerbatimDisplay,
pub lang: Option<String>,
}
impl PresPayload for VerbatimPayload {
fn project(&self) -> SerialValue {
let mut entries =
vec![("kind", text(self.kind.as_str())), ("display", text(self.display.as_str()))];
push_opt(&mut entries, "lang", self.lang.as_deref().map(text));
map(entries)
}
}
impl VerbatimPayload {
pub fn from_projection(value: &SerialValue) -> Result<VerbatimPayload, DeserializeError> {
let e = entries(names::VERBATIM, value)?;
let kind = string(names::VERBATIM, e, "kind")?;
let kind = VerbatimKind::parse(&kind)
.ok_or_else(|| bad(names::VERBATIM, format!("unknown kind `{kind}`")))?;
let display = string(names::VERBATIM, e, "display")?;
let display = VerbatimDisplay::parse(&display)
.ok_or_else(|| bad(names::VERBATIM, format!("unknown display `{display}`")))?;
Ok(VerbatimPayload { kind, display, lang: opt_string(names::VERBATIM, e, "lang")? })
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MathPassthroughPayload {
pub display: MathDisplay,
pub env: Option<String>,
pub role: Option<Name>,
}
impl PresPayload for MathPassthroughPayload {
fn project(&self) -> SerialValue {
let mut entries = vec![("display", text(self.display.as_str()))];
push_opt(&mut entries, "env", self.env.as_deref().map(text));
push_opt(&mut entries, "role", self.role.as_ref().map(|r| text(r.as_str())));
map(entries)
}
}
impl MathPassthroughPayload {
pub fn from_projection(value: &SerialValue) -> Result<MathPassthroughPayload, DeserializeError> {
let e = entries(names::MATH_PASSTHROUGH, value)?;
let display = string(names::MATH_PASSTHROUGH, e, "display")?;
let display = MathDisplay::parse(&display)
.ok_or_else(|| bad(names::MATH_PASSTHROUGH, format!("unknown display `{display}`")))?;
Ok(MathPassthroughPayload {
display,
env: opt_string(names::MATH_PASSTHROUGH, e, "env")?,
role: name_opt(names::MATH_PASSTHROUGH, e, "role")?,
})
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MathTextPayload {
pub command: Option<String>,
pub anchor: Option<String>,
pub at_tag: bool,
}
impl PresPayload for MathTextPayload {
fn project(&self) -> SerialValue {
let mut entries = Vec::new();
push_opt(&mut entries, "command", self.command.as_deref().map(text));
push_opt(&mut entries, "anchor", self.anchor.as_deref().map(text));
if self.at_tag {
entries.push(("at_tag", SerialValue::Bool(true)));
}
map(entries)
}
}
impl MathTextPayload {
pub fn from_projection(value: &SerialValue) -> Result<MathTextPayload, DeserializeError> {
let e = entries(names::MATH_TEXT, value)?;
let at_tag = match field(e, "at_tag") {
None | Some(SerialValue::Null) => false,
Some(SerialValue::Bool(value)) => *value,
Some(_) => return Err(bad(names::MATH_TEXT, "`at_tag` is not a boolean")),
};
Ok(MathTextPayload {
command: opt_string(names::MATH_TEXT, e, "command")?,
anchor: opt_string(names::MATH_TEXT, e, "anchor")?,
at_tag,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LinkPayload {
pub href: String,
pub kind: Name,
pub doc_role: Option<DocRole>,
pub label: Option<String>,
pub shows_target: bool,
}
impl PresPayload for LinkPayload {
fn project(&self) -> SerialValue {
let mut entries = vec![("href", text(&self.href)), ("kind", text(self.kind.as_str()))];
push_opt(&mut entries, "doc_role", self.doc_role.map(|r| text(r.as_str())));
push_opt(&mut entries, "label", self.label.as_deref().map(text));
if self.shows_target {
entries.push(("shows_target", SerialValue::Bool(true)));
}
map(entries)
}
}
impl LinkPayload {
pub fn from_projection(value: &SerialValue) -> Result<LinkPayload, DeserializeError> {
let e = entries(names::LINK, value)?;
let shows_target = match field(e, "shows_target") {
None | Some(SerialValue::Null) => false,
Some(SerialValue::Bool(value)) => *value,
Some(_) => return Err(bad(names::LINK, "`shows_target` is not a boolean")),
};
Ok(LinkPayload {
href: string(names::LINK, e, "href")?,
kind: Name::from(string(names::LINK, e, "kind")?),
doc_role: doc_role_opt(names::LINK, e)?,
label: opt_string(names::LINK, e, "label")?,
shows_target,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SrcsetCandidate {
pub src: String,
pub descriptor: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ImagePayload {
pub src: String,
pub display: ImageDisplay,
pub alt: Option<String>,
pub width: Option<Length>,
pub height: Option<Length>,
pub srcset: Vec<SrcsetCandidate>,
pub anchor: Option<String>,
}
impl PresPayload for ImagePayload {
fn project(&self) -> SerialValue {
let mut entries =
vec![("src", text(&self.src)), ("display", text(self.display.as_str()))];
push_opt(&mut entries, "alt", self.alt.as_deref().map(text));
push_opt(&mut entries, "width", self.width.map(|length| text(length.to_string())));
push_opt(&mut entries, "height", self.height.map(|length| text(length.to_string())));
if !self.srcset.is_empty() {
entries.push((
"srcset",
SerialValue::List(
self.srcset
.iter()
.map(|c| {
map(vec![("src", text(&c.src)), ("descriptor", text(&c.descriptor))])
})
.collect(),
),
));
}
push_opt(&mut entries, "anchor", self.anchor.as_deref().map(text));
map(entries)
}
}
impl ImagePayload {
pub fn from_projection(value: &SerialValue) -> Result<ImagePayload, DeserializeError> {
let e = entries(names::IMAGE, value)?;
let length = |key: &str| -> Result<Option<Length>, DeserializeError> {
opt_string(names::IMAGE, e, key)?
.map(|written| {
Length::parse(&written)
.map_err(|error| bad(names::IMAGE, format!("`{key}`: {error}")))
})
.transpose()
};
let srcset = match field(e, "srcset") {
None | Some(SerialValue::Null) => Vec::new(),
Some(SerialValue::List(items)) => items
.iter()
.map(|item| {
let c = entries(names::IMAGE, item)?;
Ok(SrcsetCandidate {
src: string(names::IMAGE, c, "src")?,
descriptor: string(names::IMAGE, c, "descriptor")?,
})
})
.collect::<Result<Vec<_>, DeserializeError>>()?,
Some(other) => {
return Err(bad(names::IMAGE, format!("`srcset` must be a list, found {other:?}")));
}
};
let display = string(names::IMAGE, e, "display")?;
let display = ImageDisplay::parse(&display)
.ok_or_else(|| bad(names::IMAGE, format!("unknown display `{display}`")))?;
Ok(ImagePayload {
src: string(names::IMAGE, e, "src")?,
display,
alt: opt_string(names::IMAGE, e, "alt")?,
width: length("width")?,
height: length("height")?,
srcset,
anchor: opt_string(names::IMAGE, e, "anchor")?,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnsupportedPayload {
pub element: ElementName,
pub message: String,
}
impl PresPayload for UnsupportedPayload {
fn project(&self) -> SerialValue {
map(vec![("element", text(self.element.as_str())), ("message", text(&self.message))])
}
}
impl UnsupportedPayload {
pub fn from_projection(value: &SerialValue) -> Result<UnsupportedPayload, DeserializeError> {
let e = entries(names::UNSUPPORTED, value)?;
Ok(UnsupportedPayload {
element: ElementName::from(string(names::UNSUPPORTED, e, "element")?),
message: string(names::UNSUPPORTED, e, "message")?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum UnknownKind {
Macro,
Environment,
}
impl UnknownKind {
pub fn as_str(self) -> &'static str {
match self {
UnknownKind::Macro => "macro",
UnknownKind::Environment => "environment",
}
}
pub fn parse(name: &str) -> Option<UnknownKind> {
match name {
"macro" => Some(UnknownKind::Macro),
"environment" => Some(UnknownKind::Environment),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownPayload {
pub kind: UnknownKind,
pub name: String,
pub spelling: String,
}
impl PresPayload for UnknownPayload {
fn project(&self) -> SerialValue {
map(vec![
("kind", text(self.kind.as_str())),
("name", text(&self.name)),
("spelling", text(&self.spelling)),
])
}
}
impl UnknownPayload {
pub fn from_projection(value: &SerialValue) -> Result<UnknownPayload, DeserializeError> {
let e = entries(names::UNKNOWN, value)?;
let kind = string(names::UNKNOWN, e, "kind")?;
let kind = UnknownKind::parse(&kind)
.ok_or_else(|| bad(names::UNKNOWN, format!("unknown kind `{kind}`")))?;
Ok(UnknownPayload {
kind,
name: string(names::UNKNOWN, e, "name")?,
spelling: string(names::UNKNOWN, e, "spelling")?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct DecorationPayload;
impl PresPayload for DecorationPayload {
fn project(&self) -> SerialValue {
map(Vec::new())
}
}
impl DecorationPayload {
pub fn from_projection(
element: &str,
value: &SerialValue,
) -> Result<DecorationPayload, DeserializeError> {
entries(element, value)?;
Ok(DecorationPayload)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DecoMarkPayload {
pub slot: u32,
}
impl PresPayload for DecoMarkPayload {
fn project(&self) -> SerialValue {
map(vec![("slot", SerialValue::Int(i64::from(self.slot)))])
}
}
impl DecoMarkPayload {
pub fn from_projection(value: &SerialValue) -> Result<DecoMarkPayload, DeserializeError> {
let e = entries(names::DECO_MARK, value)?;
let slot = int(names::DECO_MARK, e, "slot")?;
let slot = u32::try_from(slot)
.map_err(|_| bad(names::DECO_MARK, format!("`slot` = {slot} is not a slot index")))?;
Ok(DecoMarkPayload { slot })
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SubtreePayload {
pub tree: TreeId,
}
impl PresPayload for SubtreePayload {
fn project(&self) -> SerialValue {
map(vec![("tree", text(self.tree.to_string()))])
}
}
impl SubtreePayload {
pub fn from_projection(value: &SerialValue) -> Result<SubtreePayload, DeserializeError> {
let e = entries(names::SUBTREE, value)?;
let spelled = string(names::SUBTREE, e, "tree")?;
let index = spelled
.strip_prefix("tree#")
.and_then(|n| n.parse::<u32>().ok())
.filter(|n| n & (1 << 31) == 0)
.ok_or_else(|| bad(names::SUBTREE, format!("`{spelled}` is not a document tree id")))?;
Ok(SubtreePayload { tree: TreeId::tree(index) })
}
}
fn reader<P: PresPayload>(
readers: &mut PayloadReaders,
element: &'static str,
parse: fn(&SerialValue) -> Result<P, DeserializeError>,
) {
readers.register(element, move |value: &SerialValue, _cx: &mut DeserializeContext<'_, Flm>| {
parse(value).map(|payload| Arc::new(payload) as Arc<dyn PresPayload>)
});
}
pub fn payload_readers() -> PayloadReaders {
let mut readers = PayloadReaders::new();
reader(&mut readers, names::PAR, ParPayload::from_projection);
reader(&mut readers, names::BLOCK, BlockPayload::from_projection);
for element in [names::BLOCK_HEADING, names::RUNIN_HEADING] {
readers.register(
element,
move |value: &SerialValue, _cx: &mut DeserializeContext<'_, Flm>| {
HeadingPayload::from_projection(element, value)
.map(|payload| Arc::new(payload) as Arc<dyn PresPayload>)
},
);
}
reader(&mut readers, names::SPAN, SpanPayload::from_projection);
reader(&mut readers, names::LIST, ListPayload::from_projection);
reader(&mut readers, names::CELLS, CellsPayload::from_projection);
reader(&mut readers, names::LINES, LinesPayload::from_projection);
reader(&mut readers, names::LINE, LinePayload::from_projection);
reader(&mut readers, names::VERBATIM, VerbatimPayload::from_projection);
reader(&mut readers, names::MATH_PASSTHROUGH, MathPassthroughPayload::from_projection);
reader(&mut readers, names::MATH_TEXT, MathTextPayload::from_projection);
reader(&mut readers, names::LINK, LinkPayload::from_projection);
reader(&mut readers, names::IMAGE, ImagePayload::from_projection);
reader(&mut readers, names::UNSUPPORTED, UnsupportedPayload::from_projection);
reader(&mut readers, names::DROPPED, DroppedPayload::from_projection);
reader(&mut readers, names::UNKNOWN, UnknownPayload::from_projection);
for element in names::DECORATIONS {
readers.register(
element,
move |value: &SerialValue, _cx: &mut DeserializeContext<'_, Flm>| {
DecorationPayload::from_projection(element, value)
.map(|payload| Arc::new(payload) as Arc<dyn PresPayload>)
},
);
}
reader(&mut readers, names::DECO_MARK, DecoMarkPayload::from_projection);
reader(&mut readers, names::SUBTREE, SubtreePayload::from_projection);
readers
}
#[cfg(test)]
mod tests {
use super::*;
fn table() -> CellsPayload {
CellsPayload {
rows: 2,
cols: 3,
cells: vec![
CellSpec {
col_span: 2,
header: Some(CellHeader::Column),
align: Some(CellAlign::Center),
..CellSpec::at(0, 0)
},
CellSpec {
row_span: 2,
rules: vec![CellEdge::Left, CellEdge::Below],
styles: vec![Name::from("green"), Name::from("red")],
..CellSpec::at(0, 2)
},
CellSpec { header: Some(CellHeader::Row), ..CellSpec::at(1, 0) },
],
}
}
#[test]
fn a_table_of_cells_projects_its_entries_and_reads_back() {
let payload = table();
let projected = payload.project();
let cell = |entries: Vec<(&str, SerialValue)>| map(entries);
assert_eq!(
projected,
map(vec![
("rows", SerialValue::Int(2)),
("cols", SerialValue::Int(3)),
(
"cells",
SerialValue::List(vec![
cell(vec![
("row", SerialValue::Int(0)),
("col", SerialValue::Int(0)),
("col_span", SerialValue::Int(2)),
("align", text("center")),
("header", text("column")),
]),
cell(vec![
("row", SerialValue::Int(0)),
("col", SerialValue::Int(2)),
("row_span", SerialValue::Int(2)),
("rules", SerialValue::List(vec![text("left"), text("below")])),
("styles", SerialValue::List(vec![text("green"), text("red")])),
]),
cell(vec![
("row", SerialValue::Int(1)),
("col", SerialValue::Int(0)),
("header", text("row")),
]),
]),
),
])
);
assert_eq!(CellsPayload::from_projection(&projected).unwrap(), payload);
}
#[test]
fn the_grid_answers_every_position() {
use GridPosition::{Covered, Empty, TopLeft};
assert_eq!(
table().grid(),
vec![vec![TopLeft(0), Covered(0), TopLeft(1)], vec![TopLeft(2), Empty, Covered(1)]]
);
assert_eq!(CellsPayload::default().grid(), Vec::<Vec<GridPosition>>::new());
let odd = CellsPayload {
rows: 1,
cols: 2,
cells: vec![CellSpec { col_span: 5, ..CellSpec::at(0, 0) }, CellSpec::at(0, 1)],
};
assert_eq!(odd.grid(), vec![vec![TopLeft(0), Covered(0)]]);
}
#[test]
fn a_projection_the_feature_could_not_stage_is_refused() {
let refused = |payload: CellsPayload| {
CellsPayload::from_projection(&payload.project()).expect_err("refused")
};
let mut outside = table();
outside.cells[1].row_span = 3;
refused(outside);
let mut overlapping = table();
overlapping.cells[2] = CellSpec { col_span: 3, ..CellSpec::at(1, 0) };
refused(overlapping);
let mut unordered = table();
unordered.cells.swap(0, 1);
refused(unordered);
refused(CellsPayload { rows: 1001, cols: 1000, cells: Vec::new() });
let zero_span = map(vec![
("rows", SerialValue::Int(1)),
("cols", SerialValue::Int(1)),
(
"cells",
SerialValue::List(vec![map(vec![
("row", SerialValue::Int(0)),
("col", SerialValue::Int(0)),
("row_span", SerialValue::Int(0)),
])]),
),
]);
assert!(CellsPayload::from_projection(&zero_span).is_err());
}
#[test]
fn the_dropped_mark_projects_and_reads_back() {
let mark = DroppedPayload {
condition: Name::from("flm.cells.overlap"),
detail: String::from("cell overlapping another"),
};
assert_eq!(
mark.project(),
map(vec![
("condition", text("flm.cells.overlap")),
("detail", text("cell overlapping another")),
])
);
assert_eq!(DroppedPayload::from_projection(&mark.project()).unwrap(), mark);
}
#[test]
fn a_projection_omits_absent_optionals_and_empty_lists() {
let block = BlockPayload::default();
assert_eq!(block.project(), map(Vec::new()));
let block = BlockPayload {
role: Some(Name::from("t.thm")),
kinds: vec![Name::from("lemma")],
anchor: Some(String::from("lem-1")),
doc_role: Some(DocRole::Endnotes),
};
assert_eq!(
block.project(),
map(vec![
("role", text("t.thm")),
("kinds", SerialValue::List(vec![text("lemma")])),
("anchor", text("lem-1")),
("doc_role", text("endnotes")),
])
);
}
#[test]
fn every_payload_reads_back_from_its_projection() {
let readers = payload_readers();
assert_eq!(readers.len(), names::ALL.len());
let heading = HeadingPayload {
name: Name::from("subsection"),
level: 2,
in_toc: false,
anchor: Some(String::from("sec")),
number: Some(String::from("1.2")),
};
for element in [names::BLOCK_HEADING, names::RUNIN_HEADING] {
assert_eq!(HeadingPayload::from_projection(element, &heading.project()).unwrap(), heading);
}
let span = SpanPayload { style: Some(SpanStyle::SmallCaps), ..SpanPayload::default() };
assert_eq!(SpanPayload::from_projection(&span.project()).unwrap(), span);
let span = SpanPayload { doc_role: Some(DocRole::Footnote), ..SpanPayload::default() };
assert_eq!(SpanPayload::from_projection(&span.project()).unwrap(), span);
let block = BlockPayload { doc_role: Some(DocRole::Endnotes), ..BlockPayload::default() };
assert_eq!(BlockPayload::from_projection(&block.project()).unwrap(), block);
let link = LinkPayload {
href: String::from("#fn-1"),
kind: Name::from("xnote"),
doc_role: None,
label: None,
shows_target: false,
};
assert_eq!(link.project(), map(vec![("href", text("#fn-1")), ("kind", text("xnote"))]));
assert_eq!(LinkPayload::from_projection(&link.project()).unwrap(), link);
let link = LinkPayload {
doc_role: Some(DocRole::NoteRef),
label: Some(String::from("Footnote \"1\" <a>")),
..link
};
assert_eq!(LinkPayload::from_projection(&link.project()).unwrap(), link);
let link = LinkPayload {
href: String::from("https://example.com/"),
kind: Name::from("url"),
doc_role: None,
label: None,
shows_target: true,
};
assert_eq!(
link.project(),
map(vec![
("href", text("https://example.com/")),
("kind", text("url")),
("shows_target", SerialValue::Bool(true)),
])
);
assert_eq!(LinkPayload::from_projection(&link.project()).unwrap(), link);
let math = MathPassthroughPayload {
display: MathDisplay::Display,
env: Some(String::from("align")),
role: Some(Name::from("flm.math.formula")),
};
assert_eq!(MathPassthroughPayload::from_projection(&math.project()).unwrap(), math);
let math_text = MathTextPayload {
command: Some(String::from("textbf")),
anchor: Some(String::from("eq-1")),
at_tag: false,
};
assert_eq!(MathTextPayload::from_projection(&math_text.project()).unwrap(), math_text);
assert_eq!(MathTextPayload::default().project(), map(Vec::new()));
let at_tag = MathTextPayload { at_tag: true, ..MathTextPayload::default() };
assert_eq!(MathTextPayload::from_projection(&at_tag.project()).unwrap(), at_tag);
let subtree = SubtreePayload { tree: TreeId::tree(3) };
assert_eq!(SubtreePayload::from_projection(&subtree.project()).unwrap(), subtree);
let image = ImagePayload {
src: String::from("a.png"),
srcset: vec![SrcsetCandidate {
src: String::from("a@2x.png"),
descriptor: String::from("2x"),
}],
width: Some(Length::parse("5cm").unwrap()),
height: Some(Length::parse("2.5in").unwrap()),
display: ImageDisplay::Block,
..ImagePayload::default()
};
assert_eq!(ImagePayload::from_projection(&image.project()).unwrap(), image);
let one_dimension =
ImagePayload { height: Some(Length::parse("10pt").unwrap()), ..image.clone() };
assert_eq!(
ImagePayload::from_projection(&one_dimension.project()).unwrap(),
one_dimension
);
let line = LinePayload {
indent_left: Length::tabs(4),
indent_right: Length::parse("1.5em").unwrap(),
align: LineAlign::Right,
};
assert_eq!(LinePayload::from_projection(&line.project()).unwrap(), line);
let unknown = UnknownPayload {
kind: UnknownKind::Environment,
name: String::from("nope"),
spelling: String::from("nope"),
};
assert_eq!(UnknownPayload::from_projection(&unknown.project()).unwrap(), unknown);
let verbatim = VerbatimPayload {
kind: VerbatimKind::Identifier,
display: VerbatimDisplay::Block,
lang: Some(String::from("rust")),
};
assert_eq!(VerbatimPayload::from_projection(&verbatim.project()).unwrap(), verbatim);
let list = ListPayload {
kinds: vec![Name::from(names::LIST_NUMBERED), Name::from("enumerate")],
anchor: None,
entry_anchors: vec![None, Some(String::from("item-a")), None],
entry_levels: vec![Some(2), None, Some(3)],
};
assert_eq!(ListPayload::from_projection(&list.project()).unwrap(), list);
assert_eq!(ListPayload::default().project(), map(Vec::new()));
}
#[test]
fn every_verbatim_kind_round_trips_through_its_stable_name() {
for kind in VerbatimKind::ALL {
assert_eq!(VerbatimKind::parse(kind.as_str()), Some(kind));
}
assert_eq!(VerbatimKind::Identifier.as_str(), "a");
assert_eq!(VerbatimKind::parse("identifier"), None);
}
#[test]
fn a_malformed_projection_is_a_typed_read_error() {
assert!(LinkPayload::from_projection(&map(vec![("href", text("x"))])).is_err());
assert!(SubtreePayload::from_projection(&map(vec![("tree", text("value#1"))])).is_err());
}
#[test]
fn document_role_names_round_trip_and_an_unknown_one_is_refused() {
for role in DocRole::ALL {
assert_eq!(DocRole::parse(role.as_str()), Some(role));
}
assert_eq!(DocRole::NoteRef.as_str(), "noteref");
assert!(SpanPayload::from_projection(&map(vec![("doc_role", text("doc-noteref"))])).is_err());
assert!(
LinkPayload::from_projection(&map(vec![
("href", text("#a")),
("kind", text("ref")),
("label", SerialValue::Int(1)),
]))
.is_err()
);
}
#[test]
fn style_names_round_trip() {
for style in SpanStyle::ALL {
assert_eq!(SpanStyle::parse(style.as_str()), Some(style));
}
assert_eq!(SpanStyle::parse("blink"), None);
}
}