1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
use crate::{
models::{Gamestate, HeaderBorrowed, HeaderOwned},
tokens::TokenLookup,
Ck3Error, Ck3ErrorKind, FailedResolveStrategy,
};
use jomini::{BinaryDeserializer, TextDeserializer};
use serde::de::{Deserialize, DeserializeOwned};
use std::io::{Cursor, Read, Seek, SeekFrom};
use zip::{result::ZipError, ZipArchive};
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Encoding {
TextZip,
BinaryZip,
Binary,
}
#[derive(Debug, Clone, Copy)]
pub enum Extraction {
InMemory,
#[cfg(feature = "mmap")]
MmapTemporaries,
}
#[derive(Debug, Clone)]
pub struct Ck3ExtractorBuilder {
extraction: Extraction,
on_failed_resolve: FailedResolveStrategy,
}
impl Default for Ck3ExtractorBuilder {
fn default() -> Self {
Ck3ExtractorBuilder::new()
}
}
impl Ck3ExtractorBuilder {
pub fn new() -> Self {
Ck3ExtractorBuilder {
extraction: Extraction::InMemory,
on_failed_resolve: FailedResolveStrategy::Ignore,
}
}
pub fn with_extraction(mut self, extraction: Extraction) -> Self {
self.extraction = extraction;
self
}
pub fn with_on_failed_resolve(mut self, strategy: FailedResolveStrategy) -> Self {
self.on_failed_resolve = strategy;
self
}
pub fn extract_header_owned(&self, data: &[u8]) -> Result<(HeaderOwned, Encoding), Ck3Error> {
self.extract_header_as(data)
}
pub fn extract_header_borrowed<'a>(
&self,
data: &'a [u8],
) -> Result<(HeaderBorrowed<'a>, Encoding), Ck3Error> {
self.extract_header_as(data)
}
pub fn extract_header_as<'de, T>(&self, data: &'de [u8]) -> Result<(T, Encoding), Ck3Error>
where
T: Deserialize<'de>,
{
let data = skip_save_prefix(&data);
let mut cursor = Cursor::new(data);
let offset = match detect_encoding(&mut cursor)? {
BodyEncoding::Plain => data.len(),
BodyEncoding::Zip(zip) => zip.offset() as usize,
};
let is_zipped = offset != data.len();
let data = &data[..offset];
if sniff_is_binary(data) {
let encoding = if is_zipped {
Encoding::BinaryZip
} else {
Encoding::Binary
};
let res = BinaryDeserializer::ck3_builder()
.on_failed_resolve(self.on_failed_resolve)
.from_slice(data, &TokenLookup)?;
Ok((res, encoding))
} else {
let res = TextDeserializer::from_utf8_slice(data)?;
Ok((res, Encoding::TextZip))
}
}
pub fn extract_save<R>(&self, reader: R) -> Result<(Gamestate, Encoding), Ck3Error>
where
R: Read + Seek,
{
self.extract_save_as(reader)
}
pub fn extract_save_as<T, R>(&self, mut reader: R) -> Result<(T, Encoding), Ck3Error>
where
R: Read + Seek,
T: DeserializeOwned,
{
let mut buffer = Vec::new();
match detect_encoding(&mut reader)? {
BodyEncoding::Plain => {
reader.seek(SeekFrom::Start(0))?;
let len = reader.seek(SeekFrom::End(0))?;
reader.seek(SeekFrom::Start(0))?;
buffer.reserve(len as usize);
reader.read_to_end(&mut buffer)?;
let data = skip_save_prefix(&buffer);
let res = BinaryDeserializer::ck3_builder()
.on_failed_resolve(self.on_failed_resolve)
.from_slice(data, &TokenLookup)?;
Ok((res, Encoding::Binary))
}
BodyEncoding::Zip(mut zip) => match self.extraction {
Extraction::InMemory => {
melt_in_memory(&mut buffer, "gamestate", &mut zip, self.on_failed_resolve)
}
#[cfg(feature = "mmap")]
Extraction::MmapTemporaries => {
melt_with_temporary("gamestate", &mut zip, self.on_failed_resolve)
}
},
}
}
}
#[derive(Debug, Clone)]
pub struct Ck3Extractor {}
impl Ck3Extractor {
pub fn builder() -> Ck3ExtractorBuilder {
Ck3ExtractorBuilder::new()
}
pub fn extract_header(data: &[u8]) -> Result<(HeaderOwned, Encoding), Ck3Error> {
Self::builder().extract_header_owned(data)
}
pub fn extract_save<R>(reader: R) -> Result<(Gamestate, Encoding), Ck3Error>
where
R: Read + Seek,
{
Self::builder().extract_save(reader)
}
}
fn melt_in_memory<T, R>(
mut buffer: &mut Vec<u8>,
name: &'static str,
zip: &mut zip::ZipArchive<R>,
on_failed_resolve: FailedResolveStrategy,
) -> Result<(T, Encoding), Ck3Error>
where
R: Read + Seek,
T: DeserializeOwned,
{
buffer.clear();
let mut zip_file = zip
.by_name(name)
.map_err(|e| Ck3ErrorKind::ZipMissingEntry(name, e))?;
if zip_file.size() > 1024 * 1024 * 200 {
return Err(Ck3ErrorKind::ZipSize(name).into());
}
buffer.reserve(zip_file.size() as usize);
zip_file
.read_to_end(&mut buffer)
.map_err(|e| Ck3ErrorKind::ZipExtraction(name, e))?;
if sniff_is_binary(&buffer) {
let res = BinaryDeserializer::ck3_builder()
.on_failed_resolve(on_failed_resolve)
.from_slice(&buffer, &TokenLookup)
.map_err(|e| Ck3ErrorKind::Deserialize {
part: Some(name.to_string()),
err: e,
})?;
Ok((res, Encoding::BinaryZip))
} else {
let res = TextDeserializer::from_utf8_slice(&buffer)?;
Ok((res, Encoding::TextZip))
}
}
#[cfg(feature = "mmap")]
fn melt_with_temporary<T, R>(
name: &'static str,
zip: &mut zip::ZipArchive<R>,
on_failed_resolve: FailedResolveStrategy,
) -> Result<(T, Encoding), Ck3Error>
where
R: Read + Seek,
T: DeserializeOwned,
{
let mut zip_file = zip
.by_name(name)
.map_err(|e| Ck3ErrorKind::ZipMissingEntry(name, e))?;
if zip_file.size() > 1024 * 1024 * 200 {
return Err(Ck3ErrorKind::ZipSize(name).into());
}
let mut mmap = memmap::MmapMut::map_anon(zip_file.size() as usize)?;
std::io::copy(&mut zip_file, &mut mmap.as_mut())
.map_err(|e| Ck3ErrorKind::ZipExtraction(name, e))?;
let buffer = &mmap[..];
if sniff_is_binary(buffer) {
let res = BinaryDeserializer::ck3_builder()
.on_failed_resolve(on_failed_resolve)
.from_slice(&buffer, &TokenLookup)
.map_err(|e| Ck3ErrorKind::Deserialize {
part: Some(name.to_string()),
err: e,
})?;
Ok((res, Encoding::BinaryZip))
} else {
let res = TextDeserializer::from_utf8_slice(&buffer)?;
Ok((res, Encoding::TextZip))
}
}
fn skip_save_prefix(data: &[u8]) -> &[u8] {
let id_line_idx = data
.iter()
.position(|&x| x == b'\n')
.map(|x| x + 1)
.unwrap_or(0);
&data[id_line_idx..]
}
fn sniff_is_binary(data: &[u8]) -> bool {
data.get(2..4).map_or(false, |x| x == [0x01, 0x00])
}
pub(crate) enum BodyEncoding<'a, R>
where
R: Read + Seek,
{
Zip(ZipArchive<&'a mut R>),
Plain,
}
pub(crate) fn detect_encoding<R>(reader: &mut R) -> Result<BodyEncoding<R>, Ck3Error>
where
R: Read + Seek,
{
let zip_attempt = zip::ZipArchive::new(reader);
match zip_attempt {
Ok(x) => Ok(BodyEncoding::Zip(x)),
Err(ZipError::InvalidArchive(_)) => Ok(BodyEncoding::Plain),
Err(e) => Err(Ck3Error::new(Ck3ErrorKind::ZipCentralDirectory(e))),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_skip_save_prefix() {
let data = b"abc\n123";
let result = skip_save_prefix(&data[..]);
assert_eq!(result, b"123");
}
}