Skip to main content

rm2k/
schema.rs

1//! The `lcf_struct!`, `lcf_flags!` and `lcf_enum!` schema macros: the declarations that build
2//! every struct, flag bundle and enum in [`crate::rpg`].
3//!
4//! ```rust
5//! # use rm2k::lcf_struct;
6//! lcf_struct! {
7//!     /// RPG::Learning
8//!     #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
9//!     pub struct Learning indexed {
10//!         0x01 level:    i32 = 1,
11//!         0x02 skill_id: i32 = 1,
12//!     }
13//! }
14//! ```
15//!
16//! Every generated struct carries a `pub unknown_chunks` field of type
17//! [`UnknownChunks`](crate::field::UnknownChunks). A chunk whose id matches no field is kept verbatim, anchored next to the last field
18//! that *was* recognised, and written back in that position - so a file carrying ids this schema
19//! does not know still round-trips byte-for-byte. It is still reported as a
20//! [`DiagKind::UnknownChunk`](crate::diag::DiagKind::UnknownChunk): preserved is not understood.
21//!
22//! Two consequences for callers of this macro:
23//!
24//! - A struct literal must initialise `unknown_chunks` (`UnknownChunks::new()` for a fresh
25//!   value). [`defaults`](crate::field::LcfStruct::defaults) already does.
26//! - With the `serde` feature enabled, the struct **must** derive `Serialize`/`Deserialize`, as
27//!   above. The generated field carries `serde` attributes, and that attribute only exists where
28//!   a `serde` derive registers it.
29//!
30//! Field types are ordinary Rust types, and the codec is chosen
31//! by [`LcfField`](crate::field::LcfField). [`Packed<i16>`](crate::field::Packed) (a raw packed
32//! array) and [`List<T>`](crate::field::List) (a counted list of id-prefixed chunk streams) are
33//! distinct types precisely because they are different wire forms.
34//!
35//! | Declaration | Wire form |
36//! |---|---|
37//! | `i32` | compressed integer |
38//! | `bool` | compressed integer on read, one byte on write |
39//! | `u8`, `i8`, `i16`, `u32`, `f64` | fixed-width little-endian |
40//! | `DbStr<'a>` | raw bytes; the chunk length *is* the length |
41//! | `BitArray<'a>` | one byte per boolean |
42//! | `Packed<T>` | packed array, count derived from chunk length |
43//! | `List<T>` | `varint(count)` then id-prefixed chunk streams |
44//! | any `LcfStruct` | a nested chunk stream |
45//! | a `lcf_flags!` struct | bit-packed booleans, LSB first |
46//!
47//! # Per-field modifiers
48//!
49//! - `= expr` - explicit default. Without it the field's
50//!   [`field_default`](crate::field::LcfField::field_default) is used.
51//! - `persist` - write the chunk even when it equals its default.
52//! - `persist2k` - `persist`, but only under RPG Maker 2000; under 2003 the field is elided at
53//!   its default like any other. Exactly two fields need it: `Terms::encounter` (chunk 0x01) and
54//!   `Terms::escape_success` (chunk 0x03).
55//! - `is2k3` - the field exists only in RPG Maker 2003; skip it entirely when writing 2000.
56//! - `size = 0xNN` - emit a companion chunk `0xNN` holding this field's **byte length**.
57//! - `count = 0xNN` - emit a companion chunk `0xNN` holding this field's **element count**.
58//! - `size_persist` / `count_persist` - as above, but never elided.
59//! - `db_version` - the one field ([`DatabaseVersion`](crate::raw::DatabaseVersion)) that is
60//!   always written under RPG Maker 2003 and elided under 2000.
61//!
62//! A companion chunk is read and discarded (the chunk length already gives the payload size) but
63//! written back, and elided by its own element count, not its sibling's value. Its id is one below
64//! the sibling's, so declaring it as a modifier keeps the emitted order without a separate field.
65//!
66//! # No engine-dependent defaults
67//!
68//! Three `Actor` fields look, from the schema tables, as though their default depends on the
69//! engine ("50 under 2000, 99 under 2003"). It does not: the schema stores a `-1` sentinel for
70//! all three, and the per-engine value is substituted afterwards by
71//! [`Setup::setup`](crate::setup::Setup::setup), a separate, opt-in step.
72
73/// Define a chunked LCF struct.
74///
75/// See the [module docs](self) for the syntax.
76#[macro_export]
77macro_rules! lcf_struct {
78    // Four entry forms: with or without a lifetime, indexed or not. They differ only in what they
79    // prepend to the struct and which generics they hand down, so each delegates to `@def`
80    // immediately.
81    //
82    // A struct with no borrowed field takes no lifetime parameter - an unused one is a hard
83    // error, and `PhantomData` would leak into every struct literal.
84
85    (
86        $(#[$meta:meta])*
87        $vis:vis struct $name:ident<$lt:lifetime> indexed { $($body:tt)* }
88    ) => {
89        $crate::lcf_struct!(@def $(#[$meta])* $vis $name $lt [<$lt>] [$name<$lt>] [static]
90            [
91                /// This element's id, stored ahead of its chunk stream by the containing
92                /// [`List`](crate::field::List). Not a chunk of its own.
93                pub id: i32,
94            ]
95            [ id: 0, ] [indexed]
96            { $($body)* });
97        $crate::lcf_struct!(@indexed $lt [$name<$lt>]);
98    };
99
100    (
101        $(#[$meta:meta])*
102        $vis:vis struct $name:ident<$lt:lifetime> { $($body:tt)* }
103    ) => {
104        $crate::lcf_struct!(@def $(#[$meta])* $vis $name $lt [<$lt>] [$name<$lt>] [static] [] [] []
105            { $($body)* });
106    };
107
108    (
109        $(#[$meta:meta])*
110        $vis:vis struct $name:ident indexed { $($body:tt)* }
111    ) => {
112        $crate::lcf_struct!(@def $(#[$meta])* $vis $name 'lcf [] [$name] []
113            [
114                /// This element's id, stored ahead of its chunk stream by the containing
115                /// [`List`](crate::field::List). Not a chunk of its own.
116                pub id: i32,
117            ]
118            [ id: 0, ] [indexed]
119            { $($body)* });
120        $crate::lcf_struct!(@indexed 'lcf [$name]);
121    };
122
123    (
124        $(#[$meta:meta])*
125        $vis:vis struct $name:ident { $($body:tt)* }
126    ) => {
127        $crate::lcf_struct!(@def $(#[$meta])* $vis $name 'lcf [] [$name] [] [] [] []
128            { $($body)* });
129    };
130
131    // A macro call cannot expand into struct-field position, so the optional `id` field travels
132    // down as a bracketed token list rather than as a nested invocation. The field list is
133    // re-parsed here; that is one extra parse of the token stream, not a recursive walk over it,
134    // so expansion stays linear even for the 127-field `Terms`.
135
136    (@indexed $lt:lifetime [$($ty:tt)*]) => {
137        impl<$lt> $crate::field::LcfIndexed<$lt> for $($ty)* {
138            #[inline]
139            fn id(&self) -> i32 {
140                self.id
141            }
142            #[inline]
143            fn set_id(&mut self, id: i32) {
144                self.id = id;
145            }
146        }
147    };
148
149    (@def
150        $(#[$meta:meta])*
151        $vis:vis $name:ident $lt:lifetime
152        [$($gen:tt)*] [$($ty:tt)*] [$($owned_lt:tt)*]
153        [ $($id_field:tt)* ]
154        [ $($id_init:tt)* ]
155        [ $($id_marker:tt)* ]
156        {
157            $(
158                $(#[$fmeta:meta])*
159                $id:literal $fname:ident : $fty:ty
160                    $(= $default:expr)?
161                    $(, $flag:ident $(= $fval:literal)? )*
162            ),* $(,)?
163        }
164    ) => {
165        $(#[$meta])*
166        // Some fields are `f64`, so `Eq` does not hold for every instance.
167        #[allow(clippy::derive_partial_eq_without_eq)]
168        #[derive(Clone, Debug, PartialEq)]
169        $vis struct $name$($gen)* {
170            $($id_field)*
171            $(
172                $(#[$fmeta])*
173                pub $fname: $fty,
174            )*
175            /// Chunks this schema has no field for, kept verbatim so they survive a load/save
176            /// cycle. See [`UnknownChunk`](crate::field::UnknownChunk).
177            #[cfg_attr(feature = "serde", serde(default))]
178            #[cfg_attr(feature = "serde",
179                serde(skip_serializing_if = "rm2k::field::UnknownChunks::is_empty"))]
180            pub unknown_chunks: $crate::field::UnknownChunks,
181        }
182
183        impl<$lt> $crate::field::LcfStruct<$lt> for $($ty)* {
184            const NAME: &'static str = stringify!($name);
185
186            #[allow(unused_variables)]
187            fn defaults(engine: $crate::engine::Engine) -> Self {
188                Self {
189                    $($id_init)*
190                    $(
191                        $fname: $crate::lcf_struct!(@default engine, $fty $(, $default)?),
192                    )*
193                    unknown_chunks: $crate::field::UnknownChunks::new(),
194                }
195            }
196
197            fn apply_chunk(
198                &mut self,
199                id: u32,
200                data: &$lt [u8],
201                ctx: &mut $crate::cursor::Ctx<'_>,
202            ) -> ::core::option::Option<u32> {
203                match id {
204                    $(
205                        $id => {
206                            self.$fname = <$fty as $crate::field::LcfField<$lt>>::read(
207                                data, ctx, <Self as $crate::field::LcfStruct>::NAME, $id,
208                            );
209                            ::core::option::Option::Some($id)
210                        }
211                    )*
212                    _ => {
213                        let _ = (data, ctx);
214                        // Companion size/count chunks are discarded: the chunk framing already
215                        // carries the length. Off the matched path, so the ~39 structs without
216                        // companions pay nothing.
217                        //
218                        // A companion reports its *sibling's* id, the id the writer emits it
219                        // next to, so an unknown chunk after it anchors to the same place.
220                        $($(
221                            if $crate::lcf_struct!(@is_companion id, $flag $(= $fval)?) {
222                                return ::core::option::Option::Some($id);
223                            }
224                        )*)*
225                        ::core::option::Option::None
226                    }
227                }
228            }
229
230            #[inline]
231            fn unknown_chunks(&self) -> &$crate::field::UnknownChunks {
232                &self.unknown_chunks
233            }
234
235            #[inline]
236            fn unknown_chunks_mut(&mut self) -> &mut $crate::field::UnknownChunks {
237                &mut self.unknown_chunks
238            }
239
240            #[allow(unused_variables)]
241            fn write_body<S: $crate::sink::Sink>(
242                &self,
243                sink: &mut S,
244                engine: $crate::engine::Engine,
245            ) -> ::core::result::Result<(), S::Error> {
246                // Anything that preceded the first recognised chunk. See `UnknownChunk::anchor`.
247                self.unknown_chunks.write_anchored(sink, 0)?;
248                $(
249                    {
250                        // Each modifier contributes one term, so the rules stay linear in the
251                        // number of modifiers rather than combinatorial in them.
252                        let allowed = true
253                            $( && $crate::lcf_struct!(@allow engine, $flag $(= $fval)?) )*;
254
255                        if allowed {
256                            // Only this field's default is materialised, and only when reachable.
257                            // liblcf builds a whole default struct per object written
258                            // (`StructDefault<S>::make`), allocating per array-valued default.
259                            let fdefault =
260                                $crate::lcf_struct!(@default engine, $fty $(, $default)?);
261
262                            // A companion's id is always directly below its sibling's, so
263                            // emitting it here keeps the stream in the order liblcf produces.
264                            $(
265                                $crate::lcf_struct!(@companion
266                                    sink, self, fdefault, engine, $fname, $flag $(= $fval)?);
267                            )*
268
269                            let force = false
270                                $( || $crate::lcf_struct!(@force engine, $flag $(= $fval)?) )*;
271                            if force || $crate::field::LcfField::lcf_differs(&self.$fname, &fdefault) {
272                                let len =
273                                    $crate::field::LcfField::lcf_size(&self.$fname, engine);
274                                $crate::wire::write_varint(sink, $id)?;
275                                $crate::wire::write_varint(sink, len)?;
276                                $crate::field::LcfField::write(&self.$fname, sink, engine)?;
277                            }
278                        }
279
280                        // Outside the `allowed`/`force` guards on purpose: an unknown chunk keeps
281                        // its place relative to the chunks that *are* written, whether or not the
282                        // field it anchors to was elided or skipped for this engine.
283                        self.unknown_chunks.write_anchored(sink, $id)?;
284                    }
285                )*
286                ::core::result::Result::Ok(())
287            }
288        }
289
290        $crate::lcf_struct!(@owned_impl
291            $lt [$($ty)*] [$($owned_lt)*] $name [$($id_marker)*] [$($fname),*]);
292    };
293
294    // Emitted as one rule rather than inline in `@def` because the struct literal mentions
295    // `self`, and a `self` token written at a different expansion site would not resolve to the
296    // `self` bound by this `fn` - the same hygiene wall that keeps `engine` out of a call-site
297    // default expression.
298    (@owned_impl $lt:lifetime [$($ty:tt)*] [$($owned_lt:tt)*] $n:ident [indexed] [$($f:ident),*]) => {
299        impl<$lt> $crate::owned::IntoOwned for $($ty)* {
300            type Owned = $crate::lcf_struct!(@owned_ty $n $($owned_lt)*);
301
302            fn into_owned(self) -> Self::Owned {
303                // The literal needs no explicit lifetime; inference takes it from the return type.
304                $n {
305                    id: self.id,
306                    $( $f: $crate::owned::IntoOwned::into_owned(self.$f), )*
307                    unknown_chunks: self.unknown_chunks,
308                }
309            }
310        }
311    };
312
313    (@owned_impl $lt:lifetime [$($ty:tt)*] [$($owned_lt:tt)*] $n:ident [] [$($f:ident),*]) => {
314        impl<$lt> $crate::owned::IntoOwned for $($ty)* {
315            type Owned = $crate::lcf_struct!(@owned_ty $n $($owned_lt)*);
316
317            fn into_owned(self) -> Self::Owned {
318                $n {
319                    $( $f: $crate::owned::IntoOwned::into_owned(self.$f), )*
320                    unknown_chunks: self.unknown_chunks,
321                }
322            }
323        }
324    };
325
326    // A struct that borrows detaches to `Name<'static>`; one that does not is already owned.
327    // The marker exists because `'static` cannot travel inside a macro invocation's argument
328    // list - the parser reads it as a label there - but is perfectly fine in type position.
329    (@owned_ty $n:ident static) => { $n<'static> };
330    (@owned_ty $n:ident) => { $n };
331
332    // This field's default: the schema's explicit value, or the type's own.
333    //
334    // Per field, not a whole default struct: liblcf's `StructDefault<S>::make` allocates per object.
335    (@default $e:ident, $fty:ty, $default:expr) => { $default };
336    (@default $e:ident, $fty:ty) => {
337        <$fty as $crate::field::LcfField<'_>>::field_default($e)
338    };
339
340    // May this field be written at all? Only `is2k3` ever says no.
341    (@allow $e:ident, is2k3) => { $e.is_2k3() };
342    (@allow $e:ident, persist) => { true };
343    (@allow $e:ident, persist2k) => { true };
344    (@allow $e:ident, db_version) => { true };
345    (@allow $e:ident, size = $c:literal) => { true };
346    (@allow $e:ident, count = $c:literal) => { true };
347    (@allow $e:ident, size_persist = $c:literal) => { true };
348    (@allow $e:ident, count_persist = $c:literal) => { true };
349
350    // Must this field be written even at its default value?
351    //
352    // `persist` always says yes. `db_version` says yes only under RPG Maker 2003, where
353    // `DatabaseVersionField::IsDefault` returns `false` unconditionally so the chunk is always
354    // emitted - with an empty payload when the version is 0 (`src/reader_struct.h`).
355    (@force $e:ident, persist) => { true };
356    (@force $e:ident, persist2k) => { !$e.is_2k3() };
357    (@force $e:ident, db_version) => { $e.is_2k3() };
358    (@force $e:ident, is2k3) => { false };
359    (@force $e:ident, size = $c:literal) => { false };
360    (@force $e:ident, count = $c:literal) => { false };
361    (@force $e:ident, size_persist = $c:literal) => { false };
362    (@force $e:ident, count_persist = $c:literal) => { false };
363
364    // Is this chunk id a companion of the field carrying this modifier?
365    (@is_companion $id:ident, size = $c:literal) => { $id == $c };
366    (@is_companion $id:ident, count = $c:literal) => { $id == $c };
367    (@is_companion $id:ident, size_persist = $c:literal) => { $id == $c };
368    (@is_companion $id:ident, count_persist = $c:literal) => { $id == $c };
369    (@is_companion $id:ident, persist) => { false };
370    (@is_companion $id:ident, persist2k) => { false };
371    (@is_companion $id:ident, db_version) => { false };
372    (@is_companion $id:ident, is2k3) => { false };
373
374    // Emit the companion chunk, if this modifier is one.
375    //
376    // liblcf elides it when the sibling's *element count* matches the default's, decided separately
377    // from whether the sibling is written. Seven of the 32 companions carry `PersistIfDefault`,
378    // hence the `_persist` variants.
379    (@companion $s:ident, $self:ident, $d:ident, $e:ident, $f:ident, size = $c:literal) => {
380        if $crate::field::LcfField::element_count(&$self.$f)
381            != $crate::field::LcfField::element_count(&$d)
382        {
383            $crate::lcf_struct!(@emit_companion $s, $c,
384                $crate::field::LcfField::lcf_size(&$self.$f, $e));
385        }
386    };
387    (@companion $s:ident, $self:ident, $d:ident, $e:ident, $f:ident, size_persist = $c:literal) => {
388        $crate::lcf_struct!(@emit_companion $s, $c,
389            $crate::field::LcfField::lcf_size(&$self.$f, $e));
390    };
391    (@companion $s:ident, $self:ident, $d:ident, $e:ident, $f:ident, count = $c:literal) => {
392        if $crate::field::LcfField::element_count(&$self.$f)
393            != $crate::field::LcfField::element_count(&$d)
394        {
395            $crate::lcf_struct!(@emit_companion $s, $c,
396                $crate::field::LcfField::element_count(&$self.$f));
397        }
398    };
399    (@companion $s:ident, $self:ident, $d:ident, $e:ident, $f:ident, count_persist = $c:literal) => {
400        $crate::lcf_struct!(@emit_companion $s, $c,
401            $crate::field::LcfField::element_count(&$self.$f));
402    };
403    (@companion $s:ident, $self:ident, $d:ident, $e:ident, $f:ident, persist) => {};
404    (@companion $s:ident, $self:ident, $d:ident, $e:ident, $f:ident, persist2k) => {};
405    (@companion $s:ident, $self:ident, $d:ident, $e:ident, $f:ident, db_version) => {};
406    (@companion $s:ident, $self:ident, $d:ident, $e:ident, $f:ident, is2k3) => {};
407
408    (@emit_companion $s:ident, $c:literal, $payload:expr) => {{
409        let payload = $payload;
410        $crate::wire::write_varint($s, $c)?;
411        $crate::wire::write_varint($s, $crate::wire::varint_len(payload))?;
412        $crate::wire::write_varint($s, payload)?;
413    }};
414}
415
416/// Define a bit-packed boolean bundle.
417///
418/// Flag bundles are the one place LCF really does pack bits, eight to a byte, least significant
419/// first. Not to be confused with [`BitArray`](crate::field::BitArray), whose misleading liblcf
420/// which stores one whole byte per boolean.
421///
422/// ```
423/// # use rm2k::lcf_flags;
424/// lcf_flags! {
425///     /// RPG::TroopPageCondition flags.
426///     pub struct TroopPageConditionFlags {
427///         switch_a,
428///         switch_b,
429///         turn_enemy is2k3,
430///     }
431/// }
432/// ```
433///
434/// Writing a 2000 file **skips** 2003-only flags, shifting every later flag down a bit. Reading
435/// does **not** skip them: fields fill in declaration order from consecutive bits, whatever the
436/// engine. So a 2003 bundle written as 2000 and read back does not round-trip its *values*. That
437/// is a liblcf bug, but files in the wild carry it, and reproducing it keeps *bytes* round-tripping.
438/// Do not "fix" this without a corpus to check against.
439#[macro_export]
440macro_rules! lcf_flags {
441    (
442        $(#[$meta:meta])*
443        $vis:vis struct $name:ident {
444            $(
445                $(#[$fmeta:meta])*
446                $fname:ident $($f2k3:ident)?
447            ),* $(,)?
448        }
449    ) => {
450        $(#[$meta])*
451        #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
452        $vis struct $name {
453            $(
454                $(#[$fmeta])*
455                pub $fname: bool,
456            )*
457        }
458
459        $crate::impl_identity_owned!($name);
460
461        impl $name {
462            /// Every flag clear.
463            ///
464            /// A `const` rather than only `Default` so it can seed a struct-update expression in
465            /// a const context - which is how the schema spells a bundle whose default is a raw
466            /// bit pattern (`SavePicture::flags` defaults to 97).
467            pub const DEFAULT: Self = Self { $( $fname: false, )* };
468        }
469
470        impl<'lcf> $crate::field::LcfField<'lcf> for $name {
471            #[inline]
472            fn field_default(_engine: $crate::engine::Engine) -> Self {
473                Self::DEFAULT
474            }
475
476            fn read(
477                data: &'lcf [u8],
478                _ctx: &mut $crate::cursor::Ctx<'_>,
479                _owner: &'static str,
480                _id: u32,
481            ) -> Self {
482                let mut out = Self::default();
483                let mut bit = 0usize;
484                $(
485                    // Bits past the end of the payload read as `false`, which is how liblcf's
486                    // `byteidx >= length` break leaves them.
487                    out.$fname = data
488                        .get(bit / 8)
489                        .is_some_and(|byte| (byte >> (bit % 8)) & 1 != 0);
490                    bit += 1;
491                )*
492                let _ = bit;
493                out
494            }
495
496            #[allow(unused_variables)]
497            fn lcf_size(&self, engine: $crate::engine::Engine) -> u32 {
498                let mut bits = 0u32;
499                $(
500                    if $crate::lcf_flags!(@allow engine $(, $f2k3)?) {
501                        bits += 1;
502                    }
503                )*
504                bits.div_ceil(8)
505            }
506
507            #[allow(unused_variables)]
508            fn write<S: $crate::sink::Sink>(
509                &self,
510                sink: &mut S,
511                engine: $crate::engine::Engine,
512            ) -> ::core::result::Result<(), S::Error> {
513                let mut byte = 0u8;
514                let mut bit = 0u32;
515                $(
516                    if $crate::lcf_flags!(@allow engine $(, $f2k3)?) {
517                        byte |= u8::from(self.$fname) << bit;
518                        bit += 1;
519                        if bit == 8 {
520                            sink.write(&[byte])?;
521                            byte = 0;
522                            bit = 0;
523                        }
524                    }
525                )*
526                if bit != 0 {
527                    sink.write(&[byte])?;
528                }
529                ::core::result::Result::Ok(())
530            }
531        }
532    };
533
534    (@allow $e:ident, is2k3) => { $e.is_2k3() };
535    (@allow $e:ident) => { true };
536}
537
538/// Define the named constants for an LCF enumeration.
539///
540/// LCF stores every enumeration as a plain compressed integer and RPG Maker writes values this
541/// schema does not know about, so this generates a transparent `i32` newtype plus associated
542/// constants rather than a real `enum`. An unrecognised value is preserved exactly and written
543/// back unchanged - a real `enum` would have to either reject it or lose it, and both break
544/// round-tripping.
545///
546/// ```
547/// # use rm2k::lcf_enum;
548/// lcf_enum! {
549///     /// RPG::Actor::Condition
550///     pub struct ActorCondition {
551///         NORMAL = 0,
552///         POISON = 1,
553///     }
554/// }
555/// # assert_eq!(ActorCondition::POISON.get(), 1);
556/// # assert_eq!(ActorCondition(7).name(), None);
557/// ```
558#[macro_export]
559macro_rules! lcf_enum {
560    (
561        $(#[$meta:meta])*
562        $vis:vis struct $name:ident {
563            $(
564                $(#[$vmeta:meta])*
565                $vname:ident = $value:literal
566            ),* $(,)?
567        }
568    ) => {
569        $(#[$meta])*
570        #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
571        #[repr(transparent)]
572        $vis struct $name(pub i32);
573
574        $crate::impl_identity_owned!($name);
575
576        impl $name {
577            $(
578                $(#[$vmeta])*
579                pub const $vname: Self = Self($value);
580            )*
581
582            /// The underlying value, including one this schema does not name.
583            #[must_use]
584            #[inline]
585            pub const fn get(self) -> i32 {
586                self.0
587            }
588
589            /// The constant's name, or `None` if the value is not one this schema knows.
590            #[must_use]
591            pub const fn name(self) -> Option<&'static str> {
592                match self.0 {
593                    $( $value => Some(stringify!($vname)), )*
594                    _ => None,
595                }
596            }
597        }
598
599        impl From<i32> for $name {
600            #[inline]
601            fn from(value: i32) -> Self {
602                Self(value)
603            }
604        }
605
606        impl<'lcf> $crate::field::LcfField<'lcf> for $name {
607            #[inline]
608            fn field_default(engine: $crate::engine::Engine) -> Self {
609                Self(<i32 as $crate::field::LcfField<'lcf>>::field_default(engine))
610            }
611
612            #[inline]
613            fn read(
614                data: &'lcf [u8],
615                ctx: &mut $crate::cursor::Ctx<'_>,
616                owner: &'static str,
617                id: u32,
618            ) -> Self {
619                Self(<i32 as $crate::field::LcfField<'lcf>>::read(data, ctx, owner, id))
620            }
621
622            #[inline]
623            fn lcf_size(&self, engine: $crate::engine::Engine) -> u32 {
624                $crate::field::LcfField::lcf_size(&self.0, engine)
625            }
626
627            #[inline]
628            fn write<S: $crate::sink::Sink>(
629                &self,
630                sink: &mut S,
631                engine: $crate::engine::Engine,
632            ) -> ::core::result::Result<(), S::Error> {
633                $crate::field::LcfField::write(&self.0, sink, engine)
634            }
635        }
636    };
637}
638
639/// Declare which of a struct's fields hold text.
640///
641/// Generates [`Strings`](crate::field::Strings), which is what a translation tool needs to walk a
642/// struct's text without naming all 127 fields of `Terms` by hand.
643///
644/// Separate from `lcf_struct!` because the macro cannot tell a `DbStr` field from an `i32` one -
645/// field types are opaque `ty` fragments to it. The schema translator knows, so it emits this
646/// alongside each struct.
647///
648/// ```
649/// # use rm2k::{lcf_struct, lcf_strings, DbStr, UnknownChunks, field::Strings};
650/// lcf_struct! {
651///     #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
652///     #[cfg_attr(feature = "serde", serde(bound(deserialize = "")))]
653///     pub struct Actor<'a> indexed {
654///         0x01 name:  DbStr<'a>,
655///         0x02 title: DbStr<'a>,
656///         0x04 index: i32 = 0,
657///     }
658/// }
659/// lcf_strings!(Actor<'a> { name, title });
660///
661/// # let actor = Actor { id: 1, name: DbStr::from_bytes(b"Alex"), title: DbStr::from_bytes(b"Hero"),
662/// #                     index: 0, unknown_chunks: UnknownChunks::new() };
663/// let mut found = Vec::new();
664/// actor.visit_strings(&mut |field, value| found.push((field, value.as_bytes().to_vec())));
665/// assert_eq!(found[0].0, "name");
666/// ```
667#[macro_export]
668macro_rules! lcf_strings {
669    ($name:ident<$lt:lifetime> { $($field:ident),* $(,)? }) => {
670        impl<$lt> $crate::field::Strings<$lt> for $name<$lt> {
671            fn visit_strings(
672                &self,
673                f: &mut dyn FnMut(&'static str, &$crate::field::DbStr<$lt>),
674            ) {
675                $( f(stringify!($field), &self.$field); )*
676            }
677        }
678    };
679}