Skip to content

Instantly share code, notes, and snippets.

@ecumene
Last active June 5, 2022 20:43
Show Gist options
  • Select an option

  • Save ecumene/ec530b099e09d2099f0ef69ad0aee3de to your computer and use it in GitHub Desktop.

Select an option

Save ecumene/ec530b099e09d2099f0ef69ad0aee3de to your computer and use it in GitHub Desktop.
A frontmatter parser
#[derive(Deserialize, Serialize)]
pub struct Markdown<T> {
pub meta: T,
pub content_markdown: String,
pub content_html: String,
}
const FRONTMATTER_DELIMITER: &str = "---";
pub fn parse_frontmatter<'de, T>(post: &'de str) -> Result<(T, &'de str), toml::de::Error>
where
T: serde::Deserialize<'de>,
{
if !post.starts_with(FRONTMATTER_DELIMITER) {
panic!("Couldn't find start delimiter.");
}
let slice = &post[FRONTMATTER_DELIMITER.len()..];
let index_of_ending_line = slice
.find(FRONTMATTER_DELIMITER)
.expect("Couldn't find end delimiter.");
Ok((
toml::from_str(&slice[..index_of_ending_line])?,
&slice[(index_of_ending_line + FRONTMATTER_DELIMITER.len())..],
))
}
pub fn parse<'de, T>(source: &'de str) -> Result<Markdown<T>, toml::de::Error>
where
T: serde::Deserialize<'de>,
{
let (meta, rest): (T, &'de str) = parse_frontmatter(source)?;
let html = custom_markdown_to_html(rest);
Ok(Markdown {
meta,
content_html: html,
content_markdown: String::from(source),
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment