From 82a9dad4dff96a0daf5fb41bef22fd7f54b7ef80 Mon Sep 17 00:00:00 2001 From: Mathieu David Date: Thu, 7 Jul 2016 14:39:16 +0200 Subject: [PATCH] Basic implementation of the parser for the title of the link, does not pass the test with nested brackets --- src/lib.rs | 6 +++++- src/parse/nom.rs | 46 +++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 91aa9fa9..6340c1bd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -73,7 +73,11 @@ extern crate rustc_serialize; extern crate handlebars; extern crate pulldown_cmark; -#[macro_use] pub mod macros; +#[macro_use] +extern crate nom; + +#[macro_use] +pub mod macros; pub mod book; mod parse; pub mod renderer; diff --git a/src/parse/nom.rs b/src/parse/nom.rs index e151bcd2..bc3d8e73 100644 --- a/src/parse/nom.rs +++ b/src/parse/nom.rs @@ -1,6 +1,7 @@ -extern crate nom; +use nom::{self, IResult, alphanumeric}; -use self::nom::IResult; +use std::str; +use std::str::FromStr; #[derive(Debug, Clone)] struct Link { @@ -23,9 +24,48 @@ fn link(i: &[u8]) -> IResult<&[u8], Link> { /// Parser for parsing the title part of the link: [title](destination) /// ^^^^^^^ fn link_text(i: &[u8]) -> IResult<&[u8], String> { - unimplemented!(); + map_res!(i, map_res!(delimited!(char!('['), is_not!("[]"), char!(']')), str::from_utf8), FromStr::from_str) } +/// Parser for parsing the destination part of the link: [title](destination) +/// ^^^^^^^^^^^^^ fn link_destination(i: &[u8]) -> IResult<&[u8], String> { unimplemented!(); } + +#[cfg(test)] +mod tests { + + use nom::{self, IResult}; + + // Tests for link_text + + #[test] + fn link_text_one_ch() { + assert_eq!(super::link_text(b"[a]"), nom::IResult::Done(&b""[..], String::from("a"))); + } + + #[test] + fn link_text_multi_ch() { + assert_eq!(super::link_text(b"[Intro]"), nom::IResult::Done(&b""[..], String::from("Intro"))); + } + + #[test] + fn link_text_sp_ch() { + assert_eq!(super::link_text(b"[Intro!]"), nom::IResult::Done(&b""[..], String::from("Intro!"))); + } + + #[test] + fn link_text_unicode() { + assert_eq!(super::link_text("[Heizölrückstoßabdämpfung]".as_bytes()), + nom::IResult::Done(&b""[..], String::from("Heizölrückstoßabdämpfung"))); + assert_eq!(super::link_text("[Здравствуйте]".as_bytes()), + nom::IResult::Done(&b""[..], String::from("Здравствуйте"))); + } + + #[test] + fn link_text_brackets() { + assert_eq!(super::link_text(b"[Intro[]]"), nom::IResult::Done(&b""[..], String::from("Intro[]"))); + assert_eq!(super::link_text(br"[Intro\[]"), nom::IResult::Done(&b""[..], String::from("Intro["))); + } +}