imperator-save 0.4.2

Ergonomically work with Imperator Rome saves (debug and ironman)
Documentation
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
use crate::{
    flavor::ImperatorFlavor, Encoding, ImperatorError, ImperatorErrorKind, ImperatorMelter,
    SaveHeader,
};
use jomini::{
    binary::{BinaryDeserializerBuilder, FailedResolveStrategy, TokenResolver},
    text::ObjectReader,
    BinaryDeserializer, BinaryTape, TextDeserializer, TextTape, Utf8Encoding,
};
use serde::Deserialize;
use std::io::Cursor;
use zip::result::ZipError;

enum FileKind<'a> {
    Text(&'a [u8]),
    Binary(&'a [u8]),
    Zip {
        archive: ImperatorZipFiles<'a>,
        metadata: &'a [u8],
        gamestate: VerifiedIndex,
        is_text: bool,
    },
}

/// Entrypoint for parsing Imperator saves
///
/// Only consumes enough data to determine encoding of the file
pub struct ImperatorFile<'a> {
    header: SaveHeader,
    kind: FileKind<'a>,
}

impl<'a> ImperatorFile<'a> {
    /// Creates a Imperator file from a slice of data
    pub fn from_slice(data: &[u8]) -> Result<ImperatorFile, ImperatorError> {
        let header = SaveHeader::from_slice(data)?;
        let data = &data[header.header_len()..];

        let reader = Cursor::new(data);
        match zip::ZipArchive::new(reader) {
            Ok(mut zip) => {
                let metadata = &data[..zip.offset() as usize];
                let files = ImperatorZipFiles::new(&mut zip, data);
                let gamestate_idx = files
                    .gamestate_index()
                    .ok_or(ImperatorErrorKind::ZipMissingEntry)?;

                let is_text = !header.kind().is_binary();
                Ok(ImperatorFile {
                    header,
                    kind: FileKind::Zip {
                        archive: files,
                        gamestate: gamestate_idx,
                        metadata,
                        is_text,
                    },
                })
            }
            Err(ZipError::InvalidArchive(_)) => {
                if header.kind().is_binary() {
                    Ok(ImperatorFile {
                        header,
                        kind: FileKind::Binary(data),
                    })
                } else {
                    Ok(ImperatorFile {
                        header,
                        kind: FileKind::Text(data),
                    })
                }
            }
            Err(e) => Err(ImperatorErrorKind::ZipArchive(e).into()),
        }
    }

    /// Returns the detected decoding of the file
    pub fn encoding(&self) -> Encoding {
        match &self.kind {
            FileKind::Text(_) => Encoding::Text,
            FileKind::Binary(_) => Encoding::Binary,
            FileKind::Zip { is_text, .. } if *is_text => Encoding::TextZip,
            FileKind::Zip { .. } => Encoding::BinaryZip,
        }
    }

    /// Returns the size of the file
    ///
    /// The size includes the inflated size of the zip
    pub fn size(&self) -> usize {
        match &self.kind {
            FileKind::Text(x) | FileKind::Binary(x) => x.len(),
            FileKind::Zip { gamestate, .. } => gamestate.size,
        }
    }

    pub fn parse_metadata(&self) -> Result<ImperatorParsedFile<'a>, ImperatorError> {
        match &self.kind {
            FileKind::Text(x) => {
                // The metadata section should be way smaller than the total
                // length so if the total data isn't significantly bigger (2x or
                // more), assume that the header doesn't accurately represent
                // the metadata length. Like maybe someone accidentally
                // converted the line endings from unix to dos.
                let len = self.header.metadata_len() as usize;
                let data = if len * 2 > x.len() {
                    x
                } else {
                    &x[..len.min(x.len())]
                };

                let text = ImperatorText::from_raw(data)?;
                Ok(ImperatorParsedFile {
                    kind: ImperatorParsedFileKind::Text(text),
                })
            }
            FileKind::Binary(x) => {
                let metadata = x.get(..self.header.metadata_len() as usize).unwrap_or(x);
                let binary = ImperatorBinary::from_raw(metadata, self.header.clone())?;
                Ok(ImperatorParsedFile {
                    kind: ImperatorParsedFileKind::Binary(binary),
                })
            }
            FileKind::Zip {
                metadata, is_text, ..
            } if *is_text => {
                let text = ImperatorText::from_raw(metadata)?;
                Ok(ImperatorParsedFile {
                    kind: ImperatorParsedFileKind::Text(text),
                })
            }
            FileKind::Zip { metadata, .. } => {
                let binary = ImperatorBinary::from_raw(metadata, self.header.clone())?;
                Ok(ImperatorParsedFile {
                    kind: ImperatorParsedFileKind::Binary(binary),
                })
            }
        }
    }

    /// Parses the entire file
    ///
    /// If the file is a zip, the zip contents will be inflated into the zip
    /// sink before being parsed
    pub fn parse(
        &self,
        zip_sink: &'a mut Vec<u8>,
    ) -> Result<ImperatorParsedFile<'a>, ImperatorError> {
        match &self.kind {
            FileKind::Text(x) => {
                let text = ImperatorText::from_raw(x)?;
                Ok(ImperatorParsedFile {
                    kind: ImperatorParsedFileKind::Text(text),
                })
            }
            FileKind::Binary(x) => {
                let binary = ImperatorBinary::from_raw(x, self.header.clone())?;
                Ok(ImperatorParsedFile {
                    kind: ImperatorParsedFileKind::Binary(binary),
                })
            }
            FileKind::Zip {
                archive,
                gamestate,
                is_text,
                ..
            } => {
                let zip = archive.retrieve_file(*gamestate);
                zip.read_to_end(zip_sink)?;

                if *is_text {
                    let text = ImperatorText::from_raw(zip_sink)?;
                    Ok(ImperatorParsedFile {
                        kind: ImperatorParsedFileKind::Text(text),
                    })
                } else {
                    let binary = ImperatorBinary::from_raw(zip_sink, self.header.clone())?;
                    Ok(ImperatorParsedFile {
                        kind: ImperatorParsedFileKind::Binary(binary),
                    })
                }
            }
        }
    }
}

/// Contains the parsed Imperator file
pub enum ImperatorParsedFileKind<'a> {
    /// The Imperator file as text
    Text(ImperatorText<'a>),

    /// The Imperator file as binary
    Binary(ImperatorBinary<'a>),
}

/// An Imperator file that has been parsed
pub struct ImperatorParsedFile<'a> {
    kind: ImperatorParsedFileKind<'a>,
}

impl<'a> ImperatorParsedFile<'a> {
    /// Returns the file as text
    pub fn as_text(&self) -> Option<&ImperatorText> {
        match &self.kind {
            ImperatorParsedFileKind::Text(x) => Some(x),
            _ => None,
        }
    }

    /// Returns the file as binary
    pub fn as_binary(&self) -> Option<&ImperatorBinary> {
        match &self.kind {
            ImperatorParsedFileKind::Binary(x) => Some(x),
            _ => None,
        }
    }

    /// Returns the kind of file (binary or text)
    pub fn kind(&self) -> &ImperatorParsedFileKind {
        &self.kind
    }

    /// Prepares the file for deserialization into a custom structure
    pub fn deserializer(&self) -> ImperatorDeserializer {
        match &self.kind {
            ImperatorParsedFileKind::Text(x) => ImperatorDeserializer {
                kind: ImperatorDeserializerKind::Text(x),
            },
            ImperatorParsedFileKind::Binary(x) => ImperatorDeserializer {
                kind: ImperatorDeserializerKind::Binary(x.deserializer()),
            },
        }
    }
}

#[derive(Debug, Clone, Copy)]
struct VerifiedIndex {
    data_start: usize,
    data_end: usize,
    size: usize,
}

#[derive(Debug, Clone)]
struct ImperatorZipFiles<'a> {
    archive: &'a [u8],
    gamestate_index: Option<VerifiedIndex>,
}

impl<'a> ImperatorZipFiles<'a> {
    pub fn new(archive: &mut zip::ZipArchive<Cursor<&'a [u8]>>, data: &'a [u8]) -> Self {
        let mut gamestate_index = None;

        for index in 0..archive.len() {
            if let Ok(file) = archive.by_index_raw(index) {
                let size = file.size() as usize;
                let data_start = file.data_start() as usize;
                let data_end = data_start + file.compressed_size() as usize;

                if file.name() == "gamestate" {
                    gamestate_index = Some(VerifiedIndex {
                        data_start,
                        data_end,
                        size,
                    })
                }
            }
        }

        Self {
            archive: data,
            gamestate_index,
        }
    }

    pub fn retrieve_file(&self, index: VerifiedIndex) -> ImperatorZipFile {
        let raw = &self.archive[index.data_start..index.data_end];
        ImperatorZipFile {
            raw,
            size: index.size,
        }
    }

    pub fn gamestate_index(&self) -> Option<VerifiedIndex> {
        self.gamestate_index
    }
}

struct ImperatorZipFile<'a> {
    raw: &'a [u8],
    size: usize,
}

impl<'a> ImperatorZipFile<'a> {
    pub fn read_to_end(&self, buf: &mut Vec<u8>) -> Result<(), ImperatorError> {
        let start_len = buf.len();
        buf.resize(start_len + self.size(), 0);
        let body = &mut buf[start_len..];
        crate::deflate::inflate_exact(self.raw, body).map_err(ImperatorErrorKind::from)?;
        Ok(())
    }

    pub fn size(&self) -> usize {
        self.size
    }
}

/// A parsed Imperator text document
pub struct ImperatorText<'a> {
    tape: TextTape<'a>,
}

impl<'a> ImperatorText<'a> {
    pub fn from_slice(data: &'a [u8]) -> Result<Self, ImperatorError> {
        let header = SaveHeader::from_slice(data)?;
        Self::from_raw(&data[..header.header_len()])
    }

    pub(crate) fn from_raw(data: &'a [u8]) -> Result<Self, ImperatorError> {
        let tape = TextTape::from_slice(data).map_err(ImperatorErrorKind::Parse)?;
        Ok(ImperatorText { tape })
    }

    pub fn reader(&self) -> ObjectReader<Utf8Encoding> {
        self.tape.utf8_reader()
    }

    pub fn deserialize<T>(&self) -> Result<T, ImperatorError>
    where
        T: Deserialize<'a>,
    {
        let result = TextDeserializer::from_utf8_tape(&self.tape)
            .map_err(ImperatorErrorKind::Deserialize)?;
        Ok(result)
    }
}

/// A parsed Imperator binary document
pub struct ImperatorBinary<'a> {
    tape: BinaryTape<'a>,
    header: SaveHeader,
}

impl<'a> ImperatorBinary<'a> {
    pub fn from_slice(data: &'a [u8]) -> Result<Self, ImperatorError> {
        let header = SaveHeader::from_slice(data)?;
        Self::from_raw(&data[..header.header_len()], header)
    }

    pub(crate) fn from_raw(data: &'a [u8], header: SaveHeader) -> Result<Self, ImperatorError> {
        let tape = BinaryTape::from_slice(data).map_err(ImperatorErrorKind::Parse)?;
        Ok(ImperatorBinary { tape, header })
    }

    pub fn deserializer<'b>(&'b self) -> ImperatorBinaryDeserializer<'a, 'b> {
        ImperatorBinaryDeserializer {
            builder: BinaryDeserializer::builder_flavor(ImperatorFlavor),
            tape: &self.tape,
        }
    }

    pub fn melter<'b>(&'b self) -> ImperatorMelter<'a, 'b> {
        ImperatorMelter::new(&self.tape, &self.header)
    }
}

enum ImperatorDeserializerKind<'a, 'b> {
    Text(&'b ImperatorText<'a>),
    Binary(ImperatorBinaryDeserializer<'a, 'b>),
}

/// A deserializer for custom structures
pub struct ImperatorDeserializer<'a, 'b> {
    kind: ImperatorDeserializerKind<'a, 'b>,
}

impl<'a, 'b> ImperatorDeserializer<'a, 'b> {
    pub fn on_failed_resolve(&mut self, strategy: FailedResolveStrategy) -> &mut Self {
        if let ImperatorDeserializerKind::Binary(x) = &mut self.kind {
            x.on_failed_resolve(strategy);
        }
        self
    }

    pub fn build<T, R>(&self, resolver: &'a R) -> Result<T, ImperatorError>
    where
        R: TokenResolver,
        T: Deserialize<'a>,
    {
        match &self.kind {
            ImperatorDeserializerKind::Text(x) => x.deserialize(),
            ImperatorDeserializerKind::Binary(x) => x.build(resolver),
        }
    }
}

/// Deserializes binary data into custom structures
pub struct ImperatorBinaryDeserializer<'a, 'b> {
    builder: BinaryDeserializerBuilder<ImperatorFlavor>,
    tape: &'b BinaryTape<'a>,
}

impl<'a, 'b> ImperatorBinaryDeserializer<'a, 'b> {
    pub fn on_failed_resolve(&mut self, strategy: FailedResolveStrategy) -> &mut Self {
        self.builder.on_failed_resolve(strategy);
        self
    }

    pub fn build<T, R>(&self, resolver: &'a R) -> Result<T, ImperatorError>
    where
        R: TokenResolver,
        T: Deserialize<'a>,
    {
        let result = self
            .builder
            .from_tape(self.tape, resolver)
            .map_err(|e| match e.kind() {
                jomini::ErrorKind::Deserialize(e2) => match e2.kind() {
                    &jomini::DeserializeErrorKind::UnknownToken { token_id } => {
                        ImperatorErrorKind::UnknownToken { token_id }
                    }
                    _ => ImperatorErrorKind::Deserialize(e),
                },
                _ => ImperatorErrorKind::Deserialize(e),
            })?;
        Ok(result)
    }
}