pub mod markdown;
pub mod plain;
use crate::domain::{Format, Section};
pub trait Decomposer {
fn decompose(&self, text: &str) -> Vec<Section>;
}
#[derive(Default)]
pub struct Decomposers {
entries: Vec<(Format, Box<dyn Decomposer>)>,
}
impl Decomposers {
pub fn new() -> Self {
Self {
entries: Vec::new(),
}
}
#[must_use]
pub fn with(mut self, format: Format, decomposer: Box<dyn Decomposer>) -> Self {
if let Some(slot) = self.entries.iter_mut().find(|(f, _)| *f == format) {
slot.1 = decomposer;
} else {
self.entries.push((format, decomposer));
}
self
}
pub fn get(&self, format: &Format) -> Option<&dyn Decomposer> {
self.entries
.iter()
.find(|(f, _)| f == format)
.map(|(_, d)| d.as_ref())
}
}
#[cfg(test)]
mod tests {
use super::*;
struct Marker(&'static str);
impl Decomposer for Marker {
fn decompose(&self, _text: &str) -> Vec<Section> {
vec![Section::new(Some(self.0.to_string()), 1, Vec::new())]
}
}
fn marker_of(d: &dyn Decomposer) -> String {
d.decompose("")[0].heading.clone().unwrap()
}
#[test]
fn empty_table_supports_nothing() {
let table = Decomposers::new();
assert!(table.get(&Format::Markdown).is_none());
assert!(table.get(&Format::PlainText).is_none());
}
#[test]
fn lookup_finds_the_registered_decomposer() {
let table = Decomposers::new()
.with(Format::Markdown, Box::new(Marker("md")))
.with(Format::PlainText, Box::new(Marker("plain")));
assert_eq!(marker_of(table.get(&Format::Markdown).unwrap()), "md");
assert_eq!(marker_of(table.get(&Format::PlainText).unwrap()), "plain");
assert!(table.get(&Format::Pdf).is_none());
}
#[test]
fn with_replaces_on_duplicate_key() {
let table = Decomposers::new()
.with(Format::Markdown, Box::new(Marker("first")))
.with(Format::Markdown, Box::new(Marker("second")));
assert_eq!(marker_of(table.get(&Format::Markdown).unwrap()), "second");
}
}