Skip to main content

rm2k/
file.rs

1//! Loading and saving whole files.
2//!
3//! Every LCF file is a length-prefixed ASCII magic followed by the root struct's chunk stream:
4//!
5//! ```text
6//! varint(len) len*u8 <chunk stream>
7//! ```
8//!
9//! `Database` and `Save` omit the terminating zero id that every other chunk stream ends with.
10//! And `TreeMap` is not a chunk stream at all; see [`TreeMap`].
11//!
12//! Loading takes no [`Engine`]: no field's default actually depends on it (see the
13//! [schema docs](crate::schema) for why that is not obvious from the raw tables). Saving does
14//! need one, and [`Engine::from_ldb_id`] recovers it from a loaded database.
15
16use crate::{
17    cursor::{ChunkIter, Ctx, Cursor},
18    diag::{DiagKind, DiagSink, NullSink},
19    engine::{Engine, SaveOpt},
20    error::ReadError,
21    field::LcfStruct,
22    rpg::{Database, Map, Save, TreeMap},
23    sink::Sink,
24    wire,
25};
26use alloc::vec::Vec;
27
28/// Read the length-prefixed magic at the head of a file.
29///
30/// The bytes are returned as they appear. A wrong length is fatal, wrong content
31/// is a warning it parses through - and that split is preserved here.
32///
33/// # Errors
34///
35/// [`ReadError::UnexpectedEof`] if the buffer is too short for the declared magic.
36pub fn read_magic<'a>(cur: &mut Cursor<'a>) -> Result<&'a [u8], ReadError> {
37    let offset = cur.offset();
38    cur.lstring().ok_or(ReadError::UnexpectedEof { offset })
39}
40
41/// What a successful load produced.
42///
43/// The header travels alongside the value because saving can be asked to preserve it verbatim,
44/// and a few games ship files whose magic is not the canonical one.
45#[derive(Clone, Debug)]
46pub struct Loaded<'a, T> {
47    /// The parsed root struct.
48    pub value: T,
49    /// The file's magic string, exactly as it appeared.
50    pub header: &'a [u8],
51}
52
53impl<T> core::ops::Deref for Loaded<'_, T> {
54    type Target = T;
55    #[inline]
56    fn deref(&self) -> &T {
57        &self.value
58    }
59}
60
61/// Generate a load/save pair for one format.
62macro_rules! format_io {
63    (
64        $(#[$meta:meta])*
65        $load:ident, $load_with:ident, $save:ident, $ty:ident, $magic:path, $zero:literal
66    ) => {
67        $(#[$meta])*
68        ///
69        /// # Errors
70        ///
71        /// Fails only when the file is too short to hold a header. A wrong magic, an unknown
72        /// chunk or a truncated field are all recovered from and reported as diagnostics.
73        pub fn $load(buf: &[u8]) -> Result<Loaded<'_, $ty<'_>>, ReadError> {
74            let mut sink = NullSink;
75            $load_with(buf, &mut sink)
76        }
77
78        $(#[$meta])*
79        ///
80        /// Recoverable problems are reported to `diag`; pass
81        /// [`StrictSink`](crate::diag::StrictSink) to stop at the first one.
82        ///
83        /// # Errors
84        ///
85        /// As the loader above.
86        pub fn $load_with<'a>(
87            buf: &'a [u8],
88            diag: &mut dyn DiagSink,
89        ) -> Result<Loaded<'a, $ty<'a>>, ReadError> {
90            let mut cur = Cursor::new(buf);
91            let header = read_magic(&mut cur)?;
92
93            // The engine is irrelevant while reading; see the module docs.
94            let mut ctx = Ctx::new(Engine::R2K, diag);
95            if header != $magic {
96                ctx.report(<$ty as LcfStruct>::NAME, 0, 0, DiagKind::BadMagic);
97            }
98
99            let mut chunks = ChunkIter::from_cursor(cur);
100            let value = <$ty as LcfStruct>::read_stream(&mut chunks, &mut ctx);
101            Ok(Loaded { value, header })
102        }
103
104        $(#[$meta])*
105        ///
106        /// # Errors
107        ///
108        /// Propagates the sink's error. Infallible when writing into a `Vec<u8>`.
109        pub fn $save<S: Sink>(
110            value: &$ty<'_>,
111            sink: &mut S,
112            engine: Engine,
113            opt: SaveOpt,
114            header: &[u8],
115        ) -> Result<(), S::Error> {
116            let header = if opt.preserve_header && !header.is_empty() { header } else { $magic };
117            wire::write_varint(sink, header.len() as u32)?;
118            sink.write(header)?;
119            value.write_body(sink, engine)?;
120            if $zero {
121                sink.write(&[0])?;
122            }
123            Ok(())
124        }
125    };
126}
127
128format_io! {
129    /// The `LDB` database (`RPG_RT.ldb`).
130    load_database, load_database_with, save_database, Database, wire::LDB_HEADER, false
131}
132
133format_io! {
134    /// An `LMU` map (`MapNNNN.lmu`).
135    load_map, load_map_with, save_map, Map, wire::LMU_HEADER, true
136}
137
138format_io! {
139    /// An `LSD` save (`SaveNN.lsd`).
140    load_save, load_save_with, save_save, Save, wire::LSD_HEADER, false
141}
142
143/// Load the `LMT` map tree (`RPG_RT.lmt`).
144///
145/// Separate from the others because [`TreeMap`] is not a chunk stream: it is a bare sequence of
146/// values read straight from the file.
147///
148/// # Errors
149///
150/// [`ReadError::UnexpectedEof`] if the buffer is too short to hold a header.
151pub fn load_tree_map(buf: &[u8]) -> Result<Loaded<'_, TreeMap<'_>>, ReadError> {
152    let mut sink = NullSink;
153    load_tree_map_with(buf, &mut sink)
154}
155
156/// Load the `LMT` map tree, reporting recoverable problems to `diag`.
157///
158/// # Errors
159///
160/// As [`load_tree_map`].
161pub fn load_tree_map_with<'a>(buf: &'a [u8], diag: &mut dyn DiagSink) -> Result<Loaded<'a, TreeMap<'a>>, ReadError> {
162    let mut cur = Cursor::new(buf);
163    let header = read_magic(&mut cur)?;
164
165    let mut ctx = Ctx::new(Engine::R2K, diag);
166    if header != wire::LMT_HEADER {
167        ctx.report("TreeMap", 0, 0, DiagKind::BadMagic);
168    }
169
170    let value = TreeMap::read_inline(&mut cur, &mut ctx);
171    Ok(Loaded { value, header })
172}
173
174/// Save the `LMT` map tree.
175///
176/// # Errors
177///
178/// Propagates the sink's error.
179pub fn save_tree_map<S: Sink>(
180    value: &TreeMap<'_>,
181    sink: &mut S,
182    engine: Engine,
183    opt: SaveOpt,
184    header: &[u8],
185) -> Result<(), S::Error> {
186    let header = if opt.preserve_header && !header.is_empty() {
187        header
188    } else {
189        wire::LMT_HEADER
190    };
191    wire::write_varint(sink, header.len() as u32)?;
192    sink.write(header)?;
193    value.write_inline(sink, engine)
194}
195
196/// Serialize a value into a fresh `Vec`.
197///
198/// A convenience over the `save_*` functions for the common case; they take a
199/// [`Sink`] so they also work against a fixed buffer with no allocator.
200#[must_use]
201pub fn to_vec<T, F>(save: F) -> Vec<u8>
202where
203    F: FnOnce(&mut Vec<u8>) -> Result<T, core::convert::Infallible>,
204{
205    let mut out = Vec::new();
206    let _ = save(&mut out);
207    out
208}