mabel_aseprite/
external_file.rs

1use crate::reader::AseReader;
2use crate::Result;
3use core::str;
4use std::collections::HashMap;
5
6/// Unique identifier of a reference to an [ExternalFile].
7#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
8pub struct ExternalFileId(u32);
9
10impl ExternalFileId {
11    /// Converts a raw u32 value to an ExternalFileId.
12    pub fn new(id: u32) -> Self {
13        Self(id)
14    }
15
16    /// Returns the underlying u32 value.
17    pub fn value(&self) -> u32 {
18        self.0
19    }
20}
21
22/// An external file. Used to reference external palettes or tilesets.
23#[derive(Debug)]
24pub struct ExternalFile {
25    id: ExternalFileId,
26    name: String,
27}
28
29impl ExternalFile {
30    pub(crate) fn new(id: ExternalFileId, name: String) -> Self {
31        Self { id, name }
32    }
33
34    /// Returns a reference to the external file's id.
35    pub fn id(&self) -> &ExternalFileId {
36        &self.id
37    }
38
39    /// Returns a reference to the external file's name.
40    pub fn name(&self) -> &str {
41        &self.name
42    }
43
44    pub(crate) fn parse_chunk(data: &[u8]) -> Result<Vec<Self>> {
45        let mut reader = AseReader::new(data);
46        let entry_ct = reader.dword()?;
47        reader.skip_reserved(8)?;
48
49        let mut results = Vec::with_capacity(entry_ct as usize);
50        for _ in 0..entry_ct {
51            let id = ExternalFileId::new(reader.dword()?);
52            reader.skip_reserved(8)?;
53            let name = reader.string()?;
54            results.push(Self::new(id, name))
55        }
56
57        Ok(results)
58    }
59}
60
61/// A map of [ExternalFileId] values to [ExternalFile] instances.
62#[derive(Debug)]
63pub struct ExternalFilesById(HashMap<ExternalFileId, ExternalFile>);
64
65impl ExternalFilesById {
66    pub(crate) fn new() -> Self {
67        Self(HashMap::new())
68    }
69
70    pub(crate) fn add(&mut self, external_file: ExternalFile) {
71        self.0.insert(*external_file.id(), external_file);
72    }
73
74    /// Returns a reference to the underlying HashMap value.
75    pub fn map(&self) -> &HashMap<ExternalFileId, ExternalFile> {
76        &self.0
77    }
78
79    /// Get a reference to an [ExternalFile] from an [ExternalFileId], if the entry exists.
80    pub fn get(&self, id: &ExternalFileId) -> Option<&ExternalFile> {
81        self.0.get(id)
82    }
83}