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

View File

@ -223,7 +223,13 @@ impl Game {
} else if segment.starts_with("ITM ") {
items.push(Item::from(segment));
} 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 ") {
let result = Ending::from_str(&segment);
if let Ok(ending) = result {