evtc_parse/
skill.rs

1use crate::{
2    util::{read_string_buffer, truncate_null, write_string_buffer, Endian},
3    Parse, ParseError, Save,
4};
5use byteorder::{ReadBytesExt, WriteBytesExt};
6use std::io;
7
8#[cfg(feature = "serde")]
9use serde::{Deserialize, Serialize};
10
11/// An EVTC skill definition.
12#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
13#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
14pub struct Skill {
15    /// Id of the skill.
16    pub id: u32,
17
18    /// Name of the skill.
19    pub name: String,
20}
21
22impl Skill {
23    /// Size of the skill name string.
24    pub const NAME_SIZE: usize = 64;
25}
26
27impl Parse for Skill {
28    type Error = ParseError;
29
30    fn parse(input: &mut impl io::Read) -> Result<Self, Self::Error> {
31        Ok(Self {
32            id: input.read_u32::<Endian>()?,
33            name: truncate_null(read_string_buffer::<{ Self::NAME_SIZE }>(input)?),
34        })
35    }
36}
37
38impl Save for Skill {
39    type Error = io::Error;
40
41    fn save(&self, output: &mut impl io::Write) -> Result<(), Self::Error> {
42        output.write_u32::<Endian>(self.id)?;
43        write_string_buffer::<{ Self::NAME_SIZE }>(output, &self.name)
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50    use std::mem::size_of;
51
52    #[test]
53    fn skill_name() {
54        const SIZE: usize = size_of::<u32>() + Skill::NAME_SIZE;
55
56        let data: &[u8; SIZE] = b"\x07\0\0\0Skill Name\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
57
58        let skill = Skill::parse(io::Cursor::new(data.as_slice()).get_mut())
59            .expect("failed to parse skill");
60        assert_eq!(7, skill.id, "incorrect skill id");
61        assert_eq!("Skill Name", skill.name, "incorrect skill name");
62
63        let mut buffer = [123u8; SIZE];
64        skill
65            .save(&mut buffer.as_mut_slice())
66            .expect("failed to save skill");
67        assert_eq!(data, &buffer, "incorrect saved data");
68    }
69}