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,44 +1,59 @@
use memchr::memchr;
pub struct Emphasis;
#[inline]
/// returns offset
pub fn parse(src: &str, marker: u8) -> Option<usize> {
debug_assert!(src.len() >= 3);
impl Emphasis {
// TODO: return usize instead of Option<usize>
pub fn parse(src: &str, marker: u8) -> Option<usize> {
expect!(src, 1, |c: u8| !c.is_ascii_whitespace())?;
let bytes = src.as_bytes();
let bytes = src.as_bytes();
let end = memchr(marker, &bytes[1..])
.map(|i| i + 1)
.filter(|&i| bytes[1..i].iter().filter(|&&c| c == b'\n').count() < 2)?;
if bytes[1].is_ascii_whitespace() {
return None;
}
expect!(src, end - 1, |c: u8| !c.is_ascii_whitespace())?;
let end = memchr(marker, &bytes[1..])
.map(|i| i + 1)
.filter(|&i| bytes[1..i].iter().filter(|&&c| c == b'\n').count() < 2)?;
if end < src.len() - 1 {
expect!(src, end + 1, |ch| ch == b' '
|| ch == b'-'
|| ch == b'.'
|| ch == b','
|| ch == b':'
|| ch == b'!'
|| ch == b'?'
|| ch == b'\''
|| ch == b'\n'
|| ch == b')'
|| ch == b'}')?;
if bytes[end - 1].is_ascii_whitespace() {
return None;
}
if end < src.len() - 1 {
let post = bytes[end + 1];
if post == b' '
|| post == b'-'
|| post == b'.'
|| post == b','
|| post == b':'
|| post == b'!'
|| post == b'?'
|| post == b'\''
|| post == b'\n'
|| post == b')'
|| post == b'}'
{
Some(end)
} else {
None
}
} else {
Some(end)
}
}
#[test]
fn parse() {
assert_eq!(Emphasis::parse("*bold*", b'*').unwrap(), "*bold".len());
assert_eq!(Emphasis::parse("*bo\nld*", b'*').unwrap(), "*bo\nld".len());
assert!(Emphasis::parse("*bold*a", b'*').is_none());
assert!(Emphasis::parse("*bold*", b'/').is_none());
assert!(Emphasis::parse("*bold *", b'*').is_none());
assert!(Emphasis::parse("* bold*", b'*').is_none());
assert!(Emphasis::parse("*b\nol\nd*", b'*').is_none());
#[cfg(test)]
mod tests {
#[test]
fn parse() {
use super::parse;
assert_eq!(parse("*bold*", b'*').unwrap(), "*bold".len());
assert_eq!(parse("*bo\nld*", b'*').unwrap(), "*bo\nld".len());
assert!(parse("*bold*a", b'*').is_none());
assert!(parse("*bold*", b'/').is_none());
assert!(parse("*bold *", b'*').is_none());
assert!(parse("* bold*", b'*').is_none());
assert!(parse("*b\nol\nd*", b'*').is_none());
}
}