refactor: cleanup parse function

This commit is contained in:
PoiScript 2019-02-08 21:34:58 +08:00
parent c1154a1853
commit c5b14256f0
25 changed files with 1299 additions and 1234 deletions

View file

@ -1,71 +1,46 @@
use jetscii::Substring;
use memchr::memchr;
#[cfg_attr(test, derive(PartialEq))]
#[derive(Debug)]
pub struct Snippet<'a> {
pub name: &'a str,
pub value: &'a str,
/// returns (snippet name, snippet value, offset)
#[inline]
pub fn parse(src: &str) -> Option<(&str, &str, usize)> {
debug_assert!(src.starts_with("@@"));
let name = memchr(b':', src.as_bytes()).filter(|&i| {
i != 2
&& src.as_bytes()[2..i]
.iter()
.all(|&c| c.is_ascii_alphanumeric() || c == b'-')
})?;
let end = Substring::new("@@")
.find(&src[name + 1..])
.map(|i| i + name + 1)?;
Some((&src[2..name], &src[name + 1..end], end + 2))
}
impl<'a> Snippet<'a> {
pub fn parse(src: &'a str) -> Option<(Snippet<'a>, usize)> {
debug_assert!(src.starts_with("@@"));
#[cfg(test)]
mod tests {
#[test]
fn parse() {
use super::parse;
let name = memchr(b':', src.as_bytes()).filter(|&i| {
i != 2
&& src.as_bytes()[2..i]
.iter()
.all(|&c| c.is_ascii_alphanumeric() || c == b'-')
})?;
let end = Substring::new("@@")
.find(&src[name + 1..])
.map(|i| i + name + 1)?;
Some((
Snippet {
name: &src[2..name],
value: &src[name + 1..end],
},
end + 2,
))
assert_eq!(
parse("@@html:<b>@@").unwrap(),
("html", "<b>", "@@html:<b>@@".len())
);
assert_eq!(
parse("@@latex:any arbitrary LaTeX code@@").unwrap(),
(
"latex",
"any arbitrary LaTeX code",
"@@latex:any arbitrary LaTeX code@@".len()
)
);
assert_eq!(parse("@@html:@@").unwrap(), ("html", "", "@@html:@@".len()));
assert!(parse("@@html:<b>@").is_none());
assert!(parse("@@html<b>@@").is_none());
assert!(parse("@@:<b>@@").is_none());
}
}
#[test]
fn parse() {
assert_eq!(
Snippet::parse("@@html:<b>@@").unwrap(),
(
Snippet {
name: "html",
value: "<b>"
},
"@@html:<b>@@".len()
)
);
assert_eq!(
Snippet::parse("@@latex:any arbitrary LaTeX code@@").unwrap(),
(
Snippet {
name: "latex",
value: "any arbitrary LaTeX code"
},
"@@latex:any arbitrary LaTeX code@@".len()
)
);
assert_eq!(
Snippet::parse("@@html:@@").unwrap(),
(
Snippet {
name: "html",
value: ""
},
"@@html:@@".len()
)
);
assert!(Snippet::parse("@@html:<b>@").is_none());
assert!(Snippet::parse("@@html<b>@@").is_none());
assert!(Snippet::parse("@@:<b>@@").is_none());
}