bitsy-parser/src/item.rs

69 lines
2.1 KiB
Rust
Raw Normal View History

use crate::{AnimationFrames, Image, mock, from_base36, ToBase36};
2020-04-12 12:46:55 +00:00
#[derive(Debug, Eq, PartialEq)]
pub struct Item {
pub id: u64,
pub animation_frames: Vec<Image>,
pub name: Option<String>,
pub dialogue_id: Option<String>, // dialogue id
2020-04-12 12:46:55 +00:00
}
impl From<String> for Item {
fn from(string: String) -> Item {
let mut lines: Vec<&str> = string.lines().collect();
let id = from_base36(&lines[0].replace("ITM ", ""));
2020-04-12 12:46:55 +00:00
let mut name = None;
let mut dialogue_id = None;
2020-04-12 12:46:55 +00:00
for _ in 0..2 {
let last_line = lines.pop().unwrap();
if last_line.starts_with("NAME") {
name = Some(last_line.replace("NAME ", "").to_string());
} else if last_line.starts_with("DLG") {
dialogue_id = Some(last_line.replace("DLG ", "").to_string());
2020-04-12 12:46:55 +00:00
} else {
lines.push(last_line);
break;
}
}
// todo dedupe
let animation_frames = lines[1..].join("");
let animation_frames: Vec<&str> = animation_frames.split("\n>\n").collect();
let animation_frames: Vec<Image> = animation_frames.iter().map(|&frame| {
Image::from(frame.to_string())
}).collect();
Item { id, name, animation_frames, dialogue_id }
2020-04-12 12:46:55 +00:00
}
}
impl ToString for Item {
#[inline]
fn to_string(&self) -> String {
format!(
"ITM {}\n{}{}{}",
self.id.to_base36(),
2020-04-12 12:46:55 +00:00
self.animation_frames.to_string(),
if self.name.is_some() { format!("\nNAME {}", self.name.as_ref().unwrap()) } else { "".to_string() },
if self.dialogue_id.is_some() { format!("\nDLG {}", self.dialogue_id.as_ref().unwrap()) } else { "".to_string() },
2020-04-12 12:46:55 +00:00
)
}
}
#[test]
fn test_item_from_string() {
let output = Item::from(include_str!("../test/resources/item").to_string());
2020-04-12 12:50:07 +00:00
let expected = mock::item();
2020-04-12 12:46:55 +00:00
assert_eq!(output, expected);
}
#[test]
fn test_item_to_string() {
2020-04-12 12:50:07 +00:00
let output = mock::item().to_string();
2020-04-12 12:46:55 +00:00
let expected = include_str!("../test/resources/item").to_string();
assert_eq!(output, expected);
}