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
30pub struct Decoder<R> {
46 pub max_project_json: u64,
50
51 pub max_asset: u64,
55
56 pub max_depth: usize,
60
61 pub allow_unknown_blocks: bool,
66
67 archive: zip::ZipArchive<R>,
68}
69
70impl<R: Read + Seek> Decoder<R> {
71 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 pub fn max_project_json(mut self, bytes: u64) -> Self {
96 self.max_project_json = bytes;
97 self
98 }
99
100 pub fn max_asset(mut self, bytes: u64) -> Self {
102 self.max_asset = bytes;
103 self
104 }
105
106 pub fn max_depth(mut self, depth: usize) -> Self {
108 self.max_depth = depth;
109 self
110 }
111
112 pub fn allow_unknown_blocks(mut self, allow: bool) -> Self {
114 self.allow_unknown_blocks = allow;
115 self
116 }
117
118 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}