feat: HeadlineNode struct

This commit is contained in:
PoiScript 2019-08-07 15:37:11 +08:00
parent a1af0663b5
commit ce16610935
3 changed files with 44 additions and 2 deletions

View file

@ -219,9 +219,11 @@
mod config; mod config;
pub mod elements; pub mod elements;
pub mod export; pub mod export;
mod node;
mod org; mod org;
mod parsers; mod parsers;
pub use config::ParseConfig; pub use config::ParseConfig;
pub use elements::Element; pub use elements::Element;
pub use node::HeadlineNode;
pub use org::Org; pub use org::Org;

27
src/node.rs Normal file
View file

@ -0,0 +1,27 @@
use indextree::NodeId;
use crate::elements::{Element, Title};
use crate::Org;
#[derive(Copy, Clone)]
pub struct HeadlineNode(pub(crate) NodeId);
impl HeadlineNode {
pub fn get_title<'a>(self, org: &'a Org<'a>) -> &'a Title<'a> {
let title_node = org.arena[self.0].first_child().unwrap();
if let Element::Title(title) = org.arena[title_node].get() {
title
} else {
unreachable!()
}
}
pub fn get_title_mut<'a>(self, org: &'a mut Org<'a>) -> &'a mut Title<'a> {
let title_node = org.arena[self.0].first_child().unwrap();
if let Element::Title(title) = org.arena[title_node].get_mut() {
title
} else {
unreachable!()
}
}
}

View file

@ -2,12 +2,13 @@ use indextree::{Arena, NodeEdge, NodeId};
use std::io::{Error, Write}; use std::io::{Error, Write};
use crate::config::ParseConfig; use crate::config::ParseConfig;
use crate::elements::*; use crate::elements::Element;
use crate::export::*; use crate::export::*;
use crate::node::HeadlineNode;
use crate::parsers::*; use crate::parsers::*;
pub struct Org<'a> { pub struct Org<'a> {
arena: Arena<Element<'a>>, pub(crate) arena: Arena<Element<'a>>,
document: NodeId, document: NodeId,
} }
@ -68,6 +69,18 @@ impl Org<'_> {
}) })
} }
pub fn headlines(&self) -> Vec<HeadlineNode> {
self.document
.descendants(&self.arena)
.skip(1)
.filter(|&node| match self.arena[node].get() {
Element::Headline => true,
_ => false,
})
.map(|node| HeadlineNode(node))
.collect()
}
pub fn html<W: Write>(&self, wrtier: W) -> Result<(), Error> { pub fn html<W: Write>(&self, wrtier: W) -> Result<(), Error> {
self.html_with_handler(wrtier, DefaultHtmlHandler) self.html_with_handler(wrtier, DefaultHtmlHandler)
} }