markdown_parser/adapt/
yaml.rs

1//! yaml adapter module
2
3use crate::{Format, Markdown};
4
5use super::Adapter;
6
7/// YamlAdapter
8///
9/// transform markdown frontMatter into yaml
10#[derive(Default, Debug)]
11pub struct YamlAdapter();
12
13impl Adapter for YamlAdapter {
14    fn adapt<T>(&self, mut md: Markdown) -> crate::MarkdownResult
15    where
16        T: serde::ser::Serialize + serde::de::DeserializeOwned,
17    {
18        match md.format() {
19            Format::YAML => Ok(md),
20            Format::JSON | Format::TOML => {
21                let data = super::de_fm::<T>(&md)?;
22
23                md.set_front_matter(self.ser_fm(&data)?);
24                md.set_format(Format::YAML);
25                Ok(md)
26            }
27        }
28    }
29
30    fn ser_fm<T>(&self, data: &T) -> Result<String, crate::Error>
31    where
32        T: serde::Serialize,
33    {
34        let mut front_matter = serde_yaml::to_string(&data)?;
35
36        if front_matter.starts_with("---\n") {
37            front_matter = front_matter[4..].to_string();
38        }
39
40        if front_matter.ends_with("\n") {
41            front_matter.pop();
42        }
43
44        Ok(front_matter)
45    }
46}