use FnMut, drop a bunch of refcells
continuous-integration/drone/pr Build is passing Details

This commit is contained in:
Asherah Connor 2020-06-01 12:17:13 +10:00
parent ac2982b2ab
commit 5eb6a3c3bf
1 changed files with 13 additions and 20 deletions

View File

@ -1,7 +1,6 @@
use anyhow::Result; use anyhow::Result;
use comrak::nodes::{AstNode, NodeValue}; use comrak::nodes::{AstNode, NodeValue};
use comrak::{format_commonmark, parse_document, Arena, ComrakOptions}; use comrak::{format_commonmark, parse_document, Arena, ComrakOptions};
use std::cell::RefCell;
use std::fs::read_to_string; use std::fs::read_to_string;
use std::path::PathBuf; use std::path::PathBuf;
@ -10,41 +9,35 @@ pub(crate) fn read(fname: PathBuf, tag: String) -> Result<String> {
let arena = Arena::new(); let arena = Arena::new();
let mut root = parse_document(&arena, &data, &ComrakOptions::default()); let mut root = parse_document(&arena, &data, &ComrakOptions::default());
let collect = RefCell::new(false); let mut collect = false;
let buf = RefCell::new(Vec::<u8>::new()); let mut buf = Vec::<u8>::new();
iter_nodes(&mut root, &|node| { iter_nodes(&mut root, &mut |node| {
let nd = node.data.borrow(); let nd = node.data.borrow();
match nd.value { match nd.value {
NodeValue::Heading(ref hdr) => { NodeValue::Heading(ref hdr) => {
if hdr.level == 2 { if hdr.level == 2 {
if *collect.borrow() { if collect {
collect.swap(&RefCell::new(false)); collect = false;
} }
let found_tag = String::from_utf8(nd.content.clone())?; let found_tag = String::from_utf8(nd.content.clone())?;
if found_tag == tag { if found_tag == tag {
collect.swap(&RefCell::new(true)); collect = true;
} }
} else { } else {
if *collect.borrow() { if collect {
let mut apd = buf.borrow_mut(); format_commonmark(&node, &ComrakOptions::default(), &mut buf)?;
let mut new_buf = Vec::<u8>::new();
format_commonmark(&node, &ComrakOptions::default(), &mut new_buf)?;
apd.append(&mut new_buf);
} }
} }
Ok(()) Ok(())
} }
NodeValue::Item(_) => Ok(()), NodeValue::Item(_) => Ok(()),
_ => { _ => {
if *collect.borrow() { if collect {
let mut apd = buf.borrow_mut(); format_commonmark(&node, &ComrakOptions::default(), &mut buf)?;
let mut new_buf = Vec::<u8>::new();
format_commonmark(&node, &ComrakOptions::default(), &mut new_buf)?;
apd.append(&mut new_buf);
} }
Ok(()) Ok(())
@ -52,12 +45,12 @@ pub(crate) fn read(fname: PathBuf, tag: String) -> Result<String> {
} }
})?; })?;
Ok(String::from_utf8(buf.into_inner())?) Ok(String::from_utf8(buf)?)
} }
fn iter_nodes<'a, F>(node: &'a AstNode<'a>, f: &F) -> Result<()> fn iter_nodes<'a, F>(node: &'a AstNode<'a>, f: &mut F) -> Result<()>
where where
F: Fn(&'a AstNode<'a>) -> Result<()>, F: FnMut(&'a AstNode<'a>) -> Result<()>,
{ {
f(node)?; f(node)?;
for c in node.children() { for c in node.children() {