Skip to main content

sb3_decoder/
decode.rs

1use std::{
2    fs::File,
3    io::{BufReader, Cursor, Read, Seek},
4    path::Path,
5};
6
7use crate::{Error, model::Project, raw};
8
9mod block;
10mod project;
11mod target;
12
13const DEFAULT_MAX_PROJECT_JSON: u64 = 5 * 1024 * 1024;
14const DEFAULT_MAX_ASSET: u64 = 10 * 1024 * 1024;
15const DEFAULT_MAX_DEPTH: usize = 256;
16const DEFAULT_ALLOW_UNKNOWN_BLOCKS: bool = false;
17
18struct DecodeCtx<'a> {
19    max_depth: usize,
20    allow_unknown_blocks: bool,
21    asset_loader: &'a mut dyn FnMut(&str) -> Result<Vec<u8>, Error>,
22}
23
24impl<'a> DecodeCtx<'a> {
25    fn load_asset(&mut self, name: &str) -> Result<Vec<u8>, Error> {
26        (self.asset_loader)(name)
27    }
28}
29
30/// Decodes a project from a ZIP archive containing a `project.json` entry.
31///
32/// The decoder supports reading from files or in-memory byte slices and limits the size of the
33/// project JSON to protect against oversized entries. Use [`Decoder::max_project_json`] to
34/// configure the limit.
35///
36/// # Examples
37///
38/// ```no_run
39/// # use sb3_decoder::prelude::*;
40/// let bytes = std::fs::read("project.zip")?;
41/// let mut decoder = Decoder::from_bytes(&bytes)?;
42/// let project = decoder.decode()?;
43/// # Ok::<(), sb3_decoder::Error>(())
44/// ```
45pub struct Decoder<R> {
46    /// Maximum number of bytes allowed when reading `project.json`.
47    ///
48    /// Defaults to 5 MiB. If the entry exceeds this limit, decoding returns an error.
49    pub max_project_json: u64,
50
51    /// Maximum number of bytes allowed when reading an asset.
52    ///
53    /// Defaults to 10 MiB. If the entry exceeds this limit, decoding returns an error.
54    pub max_asset: u64,
55
56    /// Maximum nesting of C-blocks and reporter inputs.
57    ///
58    /// Defaults to 256. If the block nesting exceeds this limit, decoding returns an error.
59    pub max_depth: usize,
60
61    /// Decides if the decoder returns an error or outputs an [`crate::model::code::Action::Unknown`]
62    /// or an [`crate::model::code::Reporter::Unknown`] when met with an unknown block opcode.
63    ///
64    /// Defaults to false.
65    pub allow_unknown_blocks: bool,
66
67    archive: zip::ZipArchive<R>,
68}
69
70impl<R: Read + Seek> Decoder<R> {
71    /// Creates a decoder from a readable and seekable ZIP archive.
72    ///
73    /// The JSON size limit defaults to 5 MiB. Returns an error if the archive cannot be opened.
74    ///
75    /// # Examples
76    ///
77    /// ```
78    /// # use sb3_decoder::prelude::*;
79    /// # use std::io::Cursor;
80    /// # let zip_bytes: &[u8] = &[];
81    /// let decoder = Decoder::new(Cursor::new(zip_bytes));
82    /// ```
83    pub fn new(reader: R) -> Result<Self, Error> {
84        Ok(Self {
85            max_project_json: DEFAULT_MAX_PROJECT_JSON,
86            max_asset: DEFAULT_MAX_ASSET,
87            max_depth: DEFAULT_MAX_DEPTH,
88            allow_unknown_blocks: DEFAULT_ALLOW_UNKNOWN_BLOCKS,
89
90            archive: zip::ZipArchive::new(reader).map_err(|e| Error::zip(e, ""))?,
91        })
92    }
93
94    /// Sets the maximum size of the `project.json` entry in bytes. Defaults to 5 MiB.
95    pub fn max_project_json(mut self, bytes: u64) -> Self {
96        self.max_project_json = bytes;
97        self
98    }
99
100    /// Sets the maximum size of the asset entries in bytes. Defaults to 10 MiB.
101    pub fn max_asset(mut self, bytes: u64) -> Self {
102        self.max_asset = bytes;
103        self
104    }
105
106    /// Sets the maximum nesting of C-blocks and reporter inputs. Defaults to 256.
107    pub fn max_depth(mut self, depth: usize) -> Self {
108        self.max_depth = depth;
109        self
110    }
111
112    /// Sets whether to allow unknown blocks. Defaults to false.
113    pub fn allow_unknown_blocks(mut self, allow: bool) -> Self {
114        self.allow_unknown_blocks = allow;
115        self
116    }
117
118    /// Decodes the Scratch project.
119    pub fn decode(mut self) -> Result<Project, Error> {
120        let json = self.read_entry("project.json", self.max_project_json)?;
121        let raw: raw::Project = serde_json::from_slice(&json).map_err(Error::json)?;
122        project::decode_project(
123            raw,
124            DecodeCtx {
125                max_depth: self.max_depth,
126                allow_unknown_blocks: self.allow_unknown_blocks,
127                asset_loader: &mut |n| self.read_entry(n, self.max_asset),
128            },
129        )
130    }
131
132    fn read_entry(&mut self, name: &str, limit: u64) -> Result<Vec<u8>, Error> {
133        let file = self
134            .archive
135            .by_name(name)
136            .map_err(|e| Error::zip(e, name))?;
137        let mut buf = Vec::new();
138        file.take(limit + 1).read_to_end(&mut buf)?;
139        if buf.len() as u64 > limit {
140            return Err(Error::ZipEntryTooLarge {
141                name: name.to_string(),
142                limit,
143            });
144        }
145        Ok(buf)
146    }
147}
148
149impl Decoder<BufReader<File>> {
150    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
151        Self::new(BufReader::new(File::open(path)?))
152    }
153}
154
155impl<'a> Decoder<Cursor<&'a [u8]>> {
156    pub fn from_bytes(bytes: &'a [u8]) -> Result<Self, Error> {
157        Self::new(Cursor::new(bytes))
158    }
159}