bitsy-parser/src/dialogue.rs

72 lines
1.8 KiB
Rust
Raw Normal View History

2020-04-30 18:44:20 +00:00
use crate::optional_data_line;
2020-04-12 12:26:33 +00:00
#[derive(Debug, Eq, PartialEq)]
pub struct Dialogue {
pub id: String,
pub contents: String,
2020-04-30 18:44:20 +00:00
pub name: Option<String>,
2020-04-12 12:26:33 +00:00
}
impl From<String> for Dialogue {
#[inline]
2020-04-12 12:26:33 +00:00
fn from(string: String) -> Dialogue {
2020-04-30 18:44:20 +00:00
let mut lines: Vec<&str> = string.lines().collect();
2020-04-12 12:26:33 +00:00
let id = lines[0].replace("DLG ", "").to_string();
2020-04-30 18:44:20 +00:00
let name = if lines.last().unwrap().starts_with("NAME ") {
Some(lines.pop().unwrap().replace("NAME ", ""))
} else {
None
};
2020-04-12 12:26:33 +00:00
let contents = lines[1..].join("\n");
2020-04-30 18:44:20 +00:00
Dialogue { id, contents, name }
2020-04-12 12:26:33 +00:00
}
}
impl ToString for Dialogue {
#[inline]
fn to_string(&self) -> String {
2020-04-30 18:44:20 +00:00
format!(
"DLG {}\n{}{}",
self.id,
self.contents,
optional_data_line("NAME", self.name.as_ref())
)
2020-04-12 12:26:33 +00:00
}
}
2020-04-19 07:13:55 +00:00
#[cfg(test)]
mod test {
use crate::dialogue::Dialogue;
#[test]
fn test_dialogue_from_string() {
2020-04-30 18:44:20 +00:00
let output = Dialogue::from(
"DLG h\nhello\nNAME not a dialogue name\nNAME a dialogue name".to_string()
);
let expected = Dialogue {
id: "h".to_string(),
contents: "hello\nNAME not a dialogue name".to_string(),
name: Some("a dialogue name".to_string())
};
assert_eq!(output, expected);
2020-04-19 07:13:55 +00:00
}
2020-04-12 12:26:33 +00:00
2020-04-19 07:13:55 +00:00
#[test]
fn test_dialogue_to_string() {
let output = Dialogue {
2020-04-12 12:26:33 +00:00
id: "y".to_string(),
2020-04-30 18:44:20 +00:00
contents: "This is a bit of dialogue,\nblah blah\nblah blah".to_string(),
name: Some("a dialogue name".to_string())
2020-04-19 07:13:55 +00:00
}.to_string();
2020-04-30 18:44:20 +00:00
let expected = "DLG y\nThis is a bit of dialogue,\nblah blah\nblah blah\nNAME a dialogue name".to_string();
2020-04-19 07:13:55 +00:00
assert_eq!(output, expected);
}
2020-04-12 12:26:33 +00:00
}