From c2e59d08aa22871641c94332df809fa76df06b57 Mon Sep 17 00:00:00 2001 From: Dane Johnson Date: Mon, 24 Jan 2022 12:35:52 -0600 Subject: [PATCH] Parser outputs stories not books --- src/lib.rs | 52 ++++++++++++++++++++++++++++------------------------ 1 file changed, 28 insertions(+), 24 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 99b5f8a..c512e98 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,6 +2,12 @@ use std::collections::HashMap; +#[derive(Debug, PartialEq)] +pub struct Book { + pages: HashMap, + current_page: Option +} + #[derive(Debug, PartialEq)] pub struct Page { id: String, @@ -40,8 +46,8 @@ pub struct StatChange { peg::parser! { grammar storybook_parser() for str { - pub rule story() -> Vec - = blankline()* ps:page()+ eof() { ps } + pub rule story() -> Book + = blankline()* ps:page()+ eof() { Book::from(ps) } rule page() -> Page = h:header() b:body() f:footer() blankline()* { Page { @@ -97,17 +103,9 @@ peg::parser! { } } -// Book is a collection of pages and utilities - -pub struct Book { - pages: HashMap, - current_page: Option -} - impl Book { pub fn new (story: &str) -> Self { - let pages = storybook_parser::story(story).unwrap(); - Book::from(pages) + storybook_parser::story(story).unwrap() } pub fn find (&mut self, id: &str) { if self.pages.contains_key(id) { @@ -173,6 +171,7 @@ impl From> for Book { // C API +#[allow(clippy::not_unsafe_ptr_arg_deref)] pub mod ffi { use std::ffi::CStr; use std::ffi::CString; @@ -265,8 +264,7 @@ pub mod ffi { CStr::from_ptr(string) }; let string = string.to_str().expect("Error, input string not valid UTF-8"); - let pages = super::storybook_parser::story(string).expect("Error, input string could not be parsed"); - let book = Book::from(pages); + let book = super::storybook_parser::story(string).expect("Error, input string could not be parsed"); let book = Box::from(book); Box::into_raw(book) } @@ -388,15 +386,14 @@ THE END "; #[test] fn storybook_parser_test() { - assert_eq!( - storybook_parser::story(STORY), - Ok(vec![ - Page { + let expected = Book { + pages: HashMap::from([ + ("START".to_string(), Page { id: String::from("START"), body: String::from("One day, Dane took a really big shit."), footer: Footer::Goto(String::from("DIALOG")) - }, - Page { + }), + ("DIALOG".to_string(), Page { id: String::from("DIALOG"), body: String::from("Dane: 'Wow, that was a really big shit!'"), footer: Footer::Choices(HashMap::from([ @@ -422,14 +419,21 @@ THE END }) }), ])) - }, - Page { + }), + ("DIE".to_string(), Page { id: String::from("DIE"), body: String::from("Then he died.\n\nFuck you, Dane!"), footer: Footer::Ending, - } - ]) - ); + }), + ]), + current_page: None, + }; + let result = Book::new(STORY); + + for (key, expected_page) in expected.pages.iter() { + let result_page = result.pages.get(key).unwrap(); + assert_eq!(expected_page, result_page); + } } #[test]