refactor(parser): clean up parse functions

This commit is contained in:
PoiScript 2019-03-19 13:53:47 +08:00
parent 7273a2e84d
commit 1f52e75d3d
13 changed files with 245 additions and 284 deletions

View file

@ -1,26 +1,27 @@
use jetscii::Substring;
use memchr::memchr;
/// returns (link path, link description, offset)
#[inline]
pub fn parse(src: &str) -> Option<(&str, Option<&str>, usize)> {
debug_assert!(src.starts_with("[["));
pub fn parse(text: &str) -> Option<(&str, Option<&str>, usize)> {
debug_assert!(text.starts_with("[["));
let bytes = src.as_bytes();
let path = memchr(b']', bytes).filter(|&i| {
bytes[2..i]
.iter()
.all(|&c| c != b'<' && c != b'>' && c != b'\n')
})?;
let (path, off) = memchr(b']', text.as_bytes())
.map(|i| (&text[2..i], i))
.filter(|(path, _)| {
path.as_bytes()
.iter()
.all(|&c| c != b'<' && c != b'>' && c != b'\n')
})?;
if *bytes.get(path + 1)? == b']' {
Some((&src[2..path], None, path + 2))
} else if bytes[path + 1] == b'[' {
let desc = memchr(b']', &bytes[path + 2..])
.map(|i| i + path + 2)
.filter(|&i| bytes[path + 2..i].iter().all(|&c| c != b'['))?;
expect!(src, desc + 1, b']')?;
Some((&src[2..path], Some(&src[path + 2..desc]), desc + 2))
if *text.as_bytes().get(off + 1)? == b']' {
Some((path, None, off + 2))
} else if text.as_bytes()[off + 1] == b'[' {
let (desc, off) = Substring::new("]]")
.find(&text[off + 1..])
.map(|i| (&text[off + 2..off + i + 1], off + i + 3))
.filter(|(desc, _)| desc.as_bytes().iter().all(|&c| c != b'[' && c != b']'))?;
Some((path, Some(desc), off))
} else {
None
}