error handling for dialogues

This commit is contained in:
Max Bradbury 2020-10-18 13:46:22 +01:00
parent dba84e01fa
commit d8183e29fc
2 changed files with 22 additions and 14 deletions

View File

@ -1,5 +1,7 @@
use crate::optional_data_line; use crate::optional_data_line;
use std::fmt;
#[derive(Clone, Debug, Eq, PartialEq)] #[derive(Clone, Debug, Eq, PartialEq)]
pub struct Dialogue { pub struct Dialogue {
pub id: String, pub id: String,
@ -7,10 +9,9 @@ pub struct Dialogue {
pub name: Option<String>, pub name: Option<String>,
} }
impl From<String> for Dialogue { impl Dialogue {
#[inline] pub fn from_str(str: &str) -> Result<Dialogue, crate::Error> {
fn from(string: String) -> Dialogue { let mut lines: Vec<&str> = str.lines().collect();
let mut lines: Vec<&str> = string.lines().collect();
let id = lines[0].replace("DLG ", ""); let id = lines[0].replace("DLG ", "");
let name = if lines.last().unwrap().starts_with("NAME ") { let name = if lines.last().unwrap().starts_with("NAME ") {
@ -21,13 +22,14 @@ impl From<String> for Dialogue {
let contents = lines[1..].join("\n"); let contents = lines[1..].join("\n");
Dialogue { id, contents, name } Ok(Dialogue { id, contents, name })
} }
} }
impl ToString for Dialogue { impl fmt::Display for Dialogue {
fn to_string(&self) -> String { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
format!( write!(
f,
"DLG {}\n{}{}", "DLG {}\n{}{}",
self.id, self.id,
self.contents, self.contents,
@ -41,10 +43,10 @@ mod test {
use crate::Dialogue; use crate::Dialogue;
#[test] #[test]
fn dialogue_from_string() { fn dialogue_from_str() {
let output = Dialogue::from( let output = Dialogue::from_str(
"DLG h\nhello\nNAME not a dialogue name\nNAME a dialogue name".to_string() "DLG h\nhello\nNAME not a dialogue name\nNAME a dialogue name"
); ).unwrap();
let expected = Dialogue { let expected = Dialogue {
id: "h".to_string(), id: "h".to_string(),
@ -63,7 +65,7 @@ mod test {
name: Some("a dialogue name".to_string()) name: Some("a dialogue name".to_string())
}.to_string(); }.to_string();
let expected = "DLG y\nThis is a bit of dialogue,\nblah blah\nblah blah\nNAME a dialogue name".to_string(); let expected = "DLG y\nThis is a bit of dialogue,\nblah blah\nblah blah\nNAME a dialogue name";
assert_eq!(output, expected); assert_eq!(output, expected);
} }

View File

@ -223,7 +223,13 @@ impl Game {
} else if segment.starts_with("ITM ") { } else if segment.starts_with("ITM ") {
items.push(Item::from(segment)); items.push(Item::from(segment));
} else if segment.starts_with("DLG ") { } else if segment.starts_with("DLG ") {
dialogues.push(Dialogue::from(segment)); let result = Dialogue::from_str(&segment);
if let Ok(dialogue) = result {
dialogues.push(dialogue);
} else {
warnings.push(result.unwrap_err());
}
} else if segment.starts_with("END ") { } else if segment.starts_with("END ") {
let result = Ending::from_str(&segment); let result = Ending::from_str(&segment);
if let Ok(ending) = result { if let Ok(ending) = result {