feat(elements): update Cookie struct

Similar with org-elements-api.
This commit is contained in:
PoiScript 2019-07-30 21:20:39 +08:00
parent b429e4f54a
commit e835103ac6

View file

@ -3,9 +3,8 @@ use memchr::{memchr, memchr2};
#[cfg_attr(test, derive(PartialEq))] #[cfg_attr(test, derive(PartialEq))]
#[cfg_attr(feature = "serde", derive(serde::Serialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[derive(Debug)] #[derive(Debug)]
pub enum Cookie<'a> { pub struct Cookie<'a> {
Percent(&'a str), value: &'a str,
Slash(&'a str, &'a str),
} }
impl Cookie<'_> { impl Cookie<'_> {
@ -18,14 +17,21 @@ impl Cookie<'_> {
memchr2(b'%', b'/', bytes).filter(|&i| bytes[1..i].iter().all(u8::is_ascii_digit))?; memchr2(b'%', b'/', bytes).filter(|&i| bytes[1..i].iter().all(u8::is_ascii_digit))?;
if bytes[num1] == b'%' && *bytes.get(num1 + 1)? == b']' { if bytes[num1] == b'%' && *bytes.get(num1 + 1)? == b']' {
Some((&src[num1 + 2..], Cookie::Percent(&src[1..num1]))) Some((
&src[num1 + 2..],
Cookie {
value: &src[0..num1 + 2],
},
))
} else { } else {
let num2 = memchr(b']', bytes) let num2 = memchr(b']', bytes)
.filter(|&i| bytes[num1 + 1..i].iter().all(u8::is_ascii_digit))?; .filter(|&i| bytes[num1 + 1..i].iter().all(u8::is_ascii_digit))?;
Some(( Some((
&src[num2 + 1..], &src[num2 + 1..],
Cookie::Slash(&src[1..num1], &src[num1 + 1..num2]), Cookie {
value: &src[0..num2 + 1],
},
)) ))
} }
} }
@ -35,22 +41,25 @@ impl Cookie<'_> {
fn parse() { fn parse() {
assert_eq!( assert_eq!(
Cookie::parse("[1/10]"), Cookie::parse("[1/10]"),
Some(("", Cookie::Slash("1", "10"))) Some(("", Cookie { value: "[1/10]" }))
); );
assert_eq!( assert_eq!(
Cookie::parse("[1/1000]"), Cookie::parse("[1/1000]"),
Some(("", Cookie::Slash("1", "1000"))) Some(("", Cookie { value: "[1/1000]" }))
); );
assert_eq!(Cookie::parse("[10%]"), Some(("", Cookie::Percent("10")))); assert_eq!(
assert_eq!(Cookie::parse("[%]"), Some(("", Cookie::Percent("")))); Cookie::parse("[10%]"),
assert_eq!(Cookie::parse("[/]"), Some(("", Cookie::Slash("", "")))); Some(("", Cookie { value: "[10%]" }))
);
assert_eq!(Cookie::parse("[%]"), Some(("", Cookie { value: "[%]" })));
assert_eq!(Cookie::parse("[/]"), Some(("", Cookie { value: "[/]" })));
assert_eq!( assert_eq!(
Cookie::parse("[100/]"), Cookie::parse("[100/]"),
Some(("", Cookie::Slash("100", ""))) Some(("", Cookie { value: "[100/]" }))
); );
assert_eq!( assert_eq!(
Cookie::parse("[/100]"), Cookie::parse("[/100]"),
Some(("", Cookie::Slash("", "100"))) Some(("", Cookie { value: "[/100]" }))
); );
assert_eq!(Cookie::parse("[10% ]"), None); assert_eq!(Cookie::parse("[10% ]"), None);