omnilua 0.4.1

Every Lua, everywhere — pure-Rust Lua 5.1–5.5, suite-passing, LuaRocks-compatible, wasm-ready.
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
//! serde integration: convert any `Serialize` Rust value into a Lua [`Value`],
//! and any Lua [`Value`] into a `Deserialize` Rust type.
//!
//! Mirrors `mlua`'s `LuaSerdeExt` so a project migrating from `mlua` finds the
//! same `to_value` / `from_value` shape. This is a pure additive layer over the
//! existing [`Value`] model and the public `Table`/`LuaString` API — no VM, GC,
//! or `unsafe` involvement.
//!
//! Conventions (see the crate docs and the embedding spec):
//! - structs / maps become string-or-mixed-keyed tables; sequences and tuples
//!   become `1..n` array tables.
//! - Rust strings and byte strings both become Lua strings (Lua strings are
//!   bytes); on the way back, `&str`/`String` require valid UTF-8 while
//!   `&[u8]`/`Vec<u8>` accept any bytes.
//! - `None` / unit become `nil`; `nil` becomes `None` / unit.
//! - enums are externally tagged, matching `mlua`: a unit variant serializes to
//!   its name as a string; any other variant to a single-key table
//!   `{ "Variant" = payload }`.
//! - host integers cross the version number-model seam through
//!   [`crate::LossyIntPolicy`], identical to every other host→Lua integer.
//!
//! Known limitations:
//! - An *empty* serde array is distinguished from an empty map only by the
//!   array-marker metatable ([`LuaSerdeExt::array_metatable`]); since
//!   [`crate::Lua::marshal_from`] copies raw pairs without metatables, an empty
//!   array marshaled to another instance comes back as an empty map. Non-empty
//!   arrays are unaffected (the dense-key heuristic recovers them). Preserving
//!   the marker across `marshal_from` is a follow-up.
//! - A `u64` larger than `i64::MAX` has no exact Lua integer and is rejected
//!   rather than silently widened to a float.

use std::cell::Cell;
use std::fmt::Display;

use serde::de::{
    self, DeserializeOwned, DeserializeSeed, Deserializer, EnumAccess, MapAccess, SeqAccess,
    VariantAccess, Visitor,
};
use serde::ser::{
    self, Serialize, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant,
    SerializeTuple, SerializeTupleStruct, SerializeTupleVariant, Serializer,
};

use crate::{lower_host_int, Error, LoweredInt, Lua, LuaError, Result, Table, Value};

/// The canonical "null" marker. Lua tables cannot store `nil` as a value, so a
/// `None` / unit / JSON `null` in a *nested* position would silently delete the
/// table slot (corrupting sequences and dropping map keys). Instead those
/// serialize to this sentinel — a light-userdata at the address of a private
/// static, recognized on the way back. Mirrors `mlua`'s `Lua::null`.
static NULL_SENTINEL: u8 = 0;

/// The null sentinel as a [`Value`].
fn null_value() -> Value {
    Value::LightUserData(&NULL_SENTINEL as *const u8 as *mut core::ffi::c_void)
}

/// Whether `value` is the null sentinel from [`null_value`].
fn is_null(value: &Value) -> bool {
    matches!(value, Value::LightUserData(p) if std::ptr::eq(*p as *const u8, &NULL_SENTINEL))
}

/// Extract a host `i64` from an integer or an exactly-integral, in-range finite
/// float — the float case is how 5.1/5.2 (float-only) store integers. The range
/// guard avoids the saturating `as i64` cast (e.g. `1e20 as i64` would silently
/// become `i64::MAX`).
fn as_i64(value: &Value) -> Result<i64> {
    const MIN_F: f64 = -9_223_372_036_854_775_808.0;
    const MAX_PLUS_1_F: f64 = 9_223_372_036_854_775_808.0;
    match value {
        Value::Integer(i) => Ok(*i),
        Value::Number(n) if n.is_finite() && n.fract() == 0.0 => {
            if *n >= MIN_F && *n < MAX_PLUS_1_F {
                Ok(*n as i64)
            } else {
                Err(serde_error(format_args!(
                    "Lua number {n} is out of range for a 64-bit integer"
                )))
            }
        }
        other => Err(serde_error(format_args!(
            "expected an integer, found Lua {}",
            value_type_name(other)
        ))),
    }
}

/// The registry key under which each instance caches its serde array-marker
/// metatable.
const ARRAY_METATABLE_KEY: &str = "__omnilua_serde_array_metatable";

/// The per-instance array-marker metatable: an empty table (no metamethods) used
/// only as an identity tag so a Lua table that came from a serde sequence is
/// recognized as an array even when empty — otherwise an empty array and an
/// empty map are indistinguishable. Mirrors `mlua`'s `array_metatable`.
fn array_metatable(lua: &Lua) -> Result<Table> {
    let existing: Value = lua.named_registry_value(ARRAY_METATABLE_KEY)?;
    if let Value::Table(t) = existing {
        return Ok(t);
    }
    let mt = lua.create_table()?;
    lua.set_named_registry_value(ARRAY_METATABLE_KEY, &mt)?;
    Ok(mt)
}

/// Tag `table` as a serde array (give it the array-marker metatable).
fn mark_as_array(lua: &Lua, table: &Table) -> Result<()> {
    let mt = array_metatable(lua)?;
    table.set_metatable(Some(&mt))
}

/// Whether `table` carries the array-marker metatable.
fn is_marked_array(lua: &Lua, table: &Table) -> Result<bool> {
    match table.get_metatable()? {
        Some(mt) => Ok(mt.to_pointer()? == array_metatable(lua)?.to_pointer()?),
        None => Ok(false),
    }
}

/// Maximum container-nesting depth honored during deserialization. Bounds
/// recursion so a self-referential Lua table (`t.self = t`) reports an error
/// instead of overflowing the stack — important when the input is untrusted.
const MAX_DEPTH: u32 = 128;

thread_local! {
    static DEPTH: Cell<u32> = const { Cell::new(0) };
}

/// RAII depth counter for the recursive value deserializer. Entering a container
/// increments it (erroring past [`MAX_DEPTH`]); dropping the guard decrements.
struct DepthGuard;

impl DepthGuard {
    fn enter() -> Result<DepthGuard> {
        DEPTH.with(|d| {
            if d.get() >= MAX_DEPTH {
                return Err(serde_error(
                    "maximum table nesting depth exceeded (possible cyclic table)",
                ));
            }
            d.set(d.get() + 1);
            Ok(DepthGuard)
        })
    }
}

impl Drop for DepthGuard {
    fn drop(&mut self) {
        DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
    }
}

impl ser::Error for Error {
    fn custom<T: Display>(msg: T) -> Self {
        LuaError::runtime(format_args!("{msg}")).into()
    }
}

impl de::Error for Error {
    fn custom<T: Display>(msg: T) -> Self {
        LuaError::runtime(format_args!("{msg}")).into()
    }
}

/// serde conversions between Rust types and Lua [`Value`]s, available on [`Lua`]
/// when the `serde` feature is enabled. The naming mirrors `mlua`'s
/// `LuaSerdeExt`.
pub trait LuaSerdeExt {
    /// Serialize any [`Serialize`] value into a Lua [`Value`] owned by this
    /// instance.
    fn to_value<T>(&self, value: &T) -> Result<Value>
    where
        T: Serialize + ?Sized;

    /// Deserialize a Lua [`Value`] into any owned [`DeserializeOwned`] type.
    fn from_value<T>(&self, value: Value) -> Result<T>
    where
        T: DeserializeOwned;

    /// The null sentinel (see the module docs): a non-`nil` marker for JSON
    /// `null` / `None` so it can be stored in a table slot. Deserializing it
    /// yields `None` / unit / `null` again.
    fn null(&self) -> Value;

    /// The array-marker metatable. Tables produced from serde sequences carry it
    /// so they round-trip as arrays even when empty; set it on a table yourself
    /// to force `from_value` to treat it as a sequence.
    fn array_metatable(&self) -> Result<Table>;
}

impl LuaSerdeExt for Lua {
    fn to_value<T>(&self, value: &T) -> Result<Value>
    where
        T: Serialize + ?Sized,
    {
        value.serialize(LuaSerializer { lua: self })
    }

    fn from_value<T>(&self, value: Value) -> Result<T>
    where
        T: DeserializeOwned,
    {
        T::deserialize(LuaDeserializer { lua: self, value })
    }

    fn null(&self) -> Value {
        null_value()
    }

    fn array_metatable(&self) -> Result<Table> {
        array_metatable(self)
    }
}

/// A serde [`Serializer`] producing Lua [`Value`]s in `lua`.
struct LuaSerializer<'a> {
    lua: &'a Lua,
}

impl<'a> LuaSerializer<'a> {
    /// Lower a host `i64` to the instance's number model (integer on 5.3+, float
    /// on 5.1/5.2, honoring the lossy-int policy) — the single host→Lua integer
    /// seam shared with the rest of the API.
    fn integer(&self, i: i64) -> Result<Value> {
        Ok(
            match lower_host_int(self.lua.version(), self.lua.lossy_int_policy(), i)? {
                LoweredInt::Int(i) => Value::Integer(i),
                LoweredInt::Float(f) => Value::Number(f),
            },
        )
    }

    /// Build a Lua string from raw bytes.
    fn string(&self, bytes: &[u8]) -> Result<Value> {
        Ok(Value::String(self.lua.create_string(bytes)?))
    }
}

impl<'a> Serializer for LuaSerializer<'a> {
    type Ok = Value;
    type Error = Error;

    type SerializeSeq = SeqSerializer<'a>;
    type SerializeTuple = SeqSerializer<'a>;
    type SerializeTupleStruct = SeqSerializer<'a>;
    type SerializeTupleVariant = TupleVariantSerializer<'a>;
    type SerializeMap = MapSerializer<'a>;
    type SerializeStruct = StructSerializer<'a>;
    type SerializeStructVariant = StructVariantSerializer<'a>;

    fn serialize_bool(self, v: bool) -> Result<Value> {
        Ok(Value::Boolean(v))
    }

    fn serialize_i8(self, v: i8) -> Result<Value> {
        self.integer(i64::from(v))
    }

    fn serialize_i16(self, v: i16) -> Result<Value> {
        self.integer(i64::from(v))
    }

    fn serialize_i32(self, v: i32) -> Result<Value> {
        self.integer(i64::from(v))
    }

    fn serialize_i64(self, v: i64) -> Result<Value> {
        self.integer(v)
    }

    fn serialize_u8(self, v: u8) -> Result<Value> {
        self.integer(i64::from(v))
    }

    fn serialize_u16(self, v: u16) -> Result<Value> {
        self.integer(i64::from(v))
    }

    fn serialize_u32(self, v: u32) -> Result<Value> {
        self.integer(i64::from(v))
    }

    /// A `u64` above `i64::MAX` has no exact Lua integer representation (Lua
    /// integers are signed 64-bit), so rather than silently widen it to a lossy
    /// float, reject it — the caller can opt into a lossless encoding (e.g. a
    /// string) on their own type.
    fn serialize_u64(self, v: u64) -> Result<Value> {
        match i64::try_from(v) {
            Ok(i) => self.integer(i),
            Err(_) => Err(serde_error(format_args!(
                "u64 value {v} exceeds the i64 range Lua can represent exactly"
            ))),
        }
    }

    /// `i128` is accepted when it fits Lua's signed-64-bit integer, else
    /// rejected (rather than serde's default "unsupported" error).
    fn serialize_i128(self, v: i128) -> Result<Value> {
        match i64::try_from(v) {
            Ok(i) => self.integer(i),
            Err(_) => Err(serde_error(format_args!(
                "i128 value {v} exceeds the i64 range Lua can represent exactly"
            ))),
        }
    }

    /// `u128` is accepted when it fits Lua's signed-64-bit integer, else rejected.
    fn serialize_u128(self, v: u128) -> Result<Value> {
        match i64::try_from(v) {
            Ok(i) => self.integer(i),
            Err(_) => Err(serde_error(format_args!(
                "u128 value {v} exceeds the i64 range Lua can represent exactly"
            ))),
        }
    }

    fn serialize_f32(self, v: f32) -> Result<Value> {
        Ok(Value::Number(f64::from(v)))
    }

    fn serialize_f64(self, v: f64) -> Result<Value> {
        Ok(Value::Number(v))
    }

    fn serialize_char(self, v: char) -> Result<Value> {
        let mut buf = [0u8; 4];
        let encoded = v.encode_utf8(&mut buf);
        self.string(encoded.as_bytes())
    }

    fn serialize_str(self, v: &str) -> Result<Value> {
        self.string(v.as_bytes())
    }

    fn serialize_bytes(self, v: &[u8]) -> Result<Value> {
        self.string(v)
    }

    /// `None` serializes to the null sentinel, not `nil`, so it survives in a
    /// nested table slot (a `nil` value would delete the slot).
    fn serialize_none(self) -> Result<Value> {
        Ok(null_value())
    }

    fn serialize_some<T>(self, value: &T) -> Result<Value>
    where
        T: Serialize + ?Sized,
    {
        value.serialize(self)
    }

    fn serialize_unit(self) -> Result<Value> {
        Ok(null_value())
    }

    fn serialize_unit_struct(self, _name: &'static str) -> Result<Value> {
        Ok(null_value())
    }

    fn serialize_unit_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
    ) -> Result<Value> {
        self.string(variant.as_bytes())
    }

    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<Value>
    where
        T: Serialize + ?Sized,
    {
        value.serialize(self)
    }

    fn serialize_newtype_variant<T>(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        value: &T,
    ) -> Result<Value>
    where
        T: Serialize + ?Sized,
    {
        let inner = value.serialize(LuaSerializer { lua: self.lua })?;
        let outer = self.lua.create_table()?;
        outer.raw_set(variant, inner)?;
        Ok(Value::Table(outer))
    }

    fn serialize_seq(self, _len: Option<usize>) -> Result<SeqSerializer<'a>> {
        let table = self.lua.create_table()?;
        mark_as_array(self.lua, &table)?;
        Ok(SeqSerializer {
            lua: self.lua,
            table,
            idx: 1,
        })
    }

    fn serialize_tuple(self, _len: usize) -> Result<SeqSerializer<'a>> {
        self.serialize_seq(None)
    }

    fn serialize_tuple_struct(
        self,
        _name: &'static str,
        _len: usize,
    ) -> Result<SeqSerializer<'a>> {
        self.serialize_seq(None)
    }

    fn serialize_tuple_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        _len: usize,
    ) -> Result<TupleVariantSerializer<'a>> {
        let table = self.lua.create_table()?;
        mark_as_array(self.lua, &table)?;
        Ok(TupleVariantSerializer {
            lua: self.lua,
            variant,
            table,
            idx: 1,
        })
    }

    fn serialize_map(self, _len: Option<usize>) -> Result<MapSerializer<'a>> {
        Ok(MapSerializer {
            lua: self.lua,
            table: self.lua.create_table()?,
            pending_key: None,
        })
    }

    fn serialize_struct(
        self,
        _name: &'static str,
        _len: usize,
    ) -> Result<StructSerializer<'a>> {
        Ok(StructSerializer {
            lua: self.lua,
            table: self.lua.create_table()?,
        })
    }

    fn serialize_struct_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        _len: usize,
    ) -> Result<StructVariantSerializer<'a>> {
        Ok(StructVariantSerializer {
            lua: self.lua,
            variant,
            table: self.lua.create_table()?,
        })
    }
}

/// Builds an array table for sequences, tuples, and tuple structs.
struct SeqSerializer<'a> {
    lua: &'a Lua,
    table: Table,
    idx: i64,
}

impl<'a> SeqSerializer<'a> {
    fn push<T>(&mut self, value: &T) -> Result<()>
    where
        T: Serialize + ?Sized,
    {
        let v = value.serialize(LuaSerializer { lua: self.lua })?;
        self.table.raw_set(self.idx, v)?;
        self.idx += 1;
        Ok(())
    }
}

impl<'a> SerializeSeq for SeqSerializer<'a> {
    type Ok = Value;
    type Error = Error;

    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
    where
        T: Serialize + ?Sized,
    {
        self.push(value)
    }

    fn end(self) -> Result<Value> {
        Ok(Value::Table(self.table))
    }
}

impl<'a> SerializeTuple for SeqSerializer<'a> {
    type Ok = Value;
    type Error = Error;

    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
    where
        T: Serialize + ?Sized,
    {
        self.push(value)
    }

    fn end(self) -> Result<Value> {
        Ok(Value::Table(self.table))
    }
}

impl<'a> SerializeTupleStruct for SeqSerializer<'a> {
    type Ok = Value;
    type Error = Error;

    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
    where
        T: Serialize + ?Sized,
    {
        self.push(value)
    }

    fn end(self) -> Result<Value> {
        Ok(Value::Table(self.table))
    }
}

/// Builds the inner array of a tuple enum variant and wraps it as
/// `{ "Variant" = { ... } }`.
struct TupleVariantSerializer<'a> {
    lua: &'a Lua,
    variant: &'static str,
    table: Table,
    idx: i64,
}

impl<'a> SerializeTupleVariant for TupleVariantSerializer<'a> {
    type Ok = Value;
    type Error = Error;

    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
    where
        T: Serialize + ?Sized,
    {
        let v = value.serialize(LuaSerializer { lua: self.lua })?;
        self.table.raw_set(self.idx, v)?;
        self.idx += 1;
        Ok(())
    }

    fn end(self) -> Result<Value> {
        let outer = self.lua.create_table()?;
        outer.raw_set(self.variant, Value::Table(self.table))?;
        Ok(Value::Table(outer))
    }
}

/// Builds a table from a map, holding each key until its value arrives.
struct MapSerializer<'a> {
    lua: &'a Lua,
    table: Table,
    pending_key: Option<Value>,
}

impl<'a> SerializeMap for MapSerializer<'a> {
    type Ok = Value;
    type Error = Error;

    fn serialize_key<T>(&mut self, key: &T) -> Result<()>
    where
        T: Serialize + ?Sized,
    {
        self.pending_key = Some(key.serialize(LuaSerializer { lua: self.lua })?);
        Ok(())
    }

    fn serialize_value<T>(&mut self, value: &T) -> Result<()>
    where
        T: Serialize + ?Sized,
    {
        let key = self
            .pending_key
            .take()
            .ok_or_else(|| serde_error("serialize_value called before serialize_key"))?;
        if matches!(key, Value::Nil) {
            return Err(serde_error("map key serialized to nil, which Lua cannot store"));
        }
        let v = value.serialize(LuaSerializer { lua: self.lua })?;
        self.table.raw_set(key, v)?;
        Ok(())
    }

    fn end(self) -> Result<Value> {
        Ok(Value::Table(self.table))
    }
}

/// Builds a string-keyed table from a struct.
struct StructSerializer<'a> {
    lua: &'a Lua,
    table: Table,
}

impl<'a> SerializeStruct for StructSerializer<'a> {
    type Ok = Value;
    type Error = Error;

    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
    where
        T: Serialize + ?Sized,
    {
        let v = value.serialize(LuaSerializer { lua: self.lua })?;
        self.table.raw_set(key, v)?;
        Ok(())
    }

    fn end(self) -> Result<Value> {
        Ok(Value::Table(self.table))
    }
}

/// Builds the inner struct of a struct enum variant and wraps it as
/// `{ "Variant" = { ... } }`.
struct StructVariantSerializer<'a> {
    lua: &'a Lua,
    variant: &'static str,
    table: Table,
}

impl<'a> SerializeStructVariant for StructVariantSerializer<'a> {
    type Ok = Value;
    type Error = Error;

    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
    where
        T: Serialize + ?Sized,
    {
        let v = value.serialize(LuaSerializer { lua: self.lua })?;
        self.table.raw_set(key, v)?;
        Ok(())
    }

    fn end(self) -> Result<Value> {
        let outer = self.lua.create_table()?;
        outer.raw_set(self.variant, Value::Table(self.table))?;
        Ok(Value::Table(outer))
    }
}

/// Construct an embedding [`Error`] carrying a serde diagnostic message.
fn serde_error(msg: impl Display) -> Error {
    LuaError::runtime(format_args!("{msg}")).into()
}

/// A serde [`Deserializer`] reading a Lua [`Value`]. Owns its value and never
/// borrows from a `'de` input, so it deserializes only owned types.
struct LuaDeserializer<'a> {
    lua: &'a Lua,
    value: Value,
}

/// Whether `pairs` forms a dense `1..=n` array (integer or integral-float keys,
/// no gaps, no duplicates, no other keys). An empty table is *not* a sequence —
/// it is treated as an empty map, the only consistent default given Lua cannot
/// distinguish an empty array from an empty map.
fn sequence_len(pairs: &[(Value, Value)]) -> Option<u64> {
    let n = pairs.len() as u64;
    if n == 0 {
        return None;
    }
    let mut seen = vec![false; pairs.len()];
    for (key, _) in pairs {
        let idx = match key {
            Value::Integer(i) if *i >= 1 => *i as u64,
            Value::Number(f) if f.fract() == 0.0 && *f >= 1.0 && *f <= n as f64 => *f as u64,
            _ => return None,
        };
        if idx < 1 || idx > n {
            return None;
        }
        let slot = (idx - 1) as usize;
        if seen[slot] {
            return None;
        }
        seen[slot] = true;
    }
    Some(n)
}

/// Read a Lua array table's values in `1..=len` order.
fn table_seq_values(table: &Table) -> Result<Vec<Value>> {
    let len = table.len()?;
    let mut out = Vec::with_capacity(len as usize);
    for idx in 1..=len {
        out.push(table.raw_get::<i64, Value>(idx as i64)?);
    }
    Ok(out)
}

/// Values of a table that a caller explicitly asked to read as a sequence. A
/// marked array or a dense `1..=n` (or empty) table is accepted; a table with
/// non-array keys is rejected rather than silently dropping those entries.
fn require_sequence_values(lua: &Lua, table: &Table) -> Result<Vec<Value>> {
    if is_marked_array(lua, table)? {
        return table_seq_values(table);
    }
    let pairs = table.raw_pairs()?;
    if pairs.is_empty() || sequence_len(&pairs).is_some() {
        table_seq_values(table)
    } else {
        Err(serde_error(
            "expected a Lua array (dense 1..n integer keys); found a table with non-array keys",
        ))
    }
}

impl<'a, 'de> Deserializer<'de> for LuaDeserializer<'a> {
    type Error = Error;

    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        let _depth = DepthGuard::enter()?;
        if is_null(&self.value) {
            return visitor.visit_unit();
        }
        match self.value {
            Value::Nil => visitor.visit_unit(),
            Value::Boolean(b) => visitor.visit_bool(b),
            Value::Integer(i) => visitor.visit_i64(i),
            Value::Number(n) => visitor.visit_f64(n),
            Value::String(s) => {
                let bytes = s.as_bytes()?;
                match std::str::from_utf8(&bytes) {
                    Ok(text) => visitor.visit_str(text),
                    Err(_) => visitor.visit_bytes(&bytes),
                }
            }
            Value::Table(t) => {
                if is_marked_array(self.lua, &t)? {
                    return visitor.visit_seq(SeqAccessor {
                        lua: self.lua,
                        items: table_seq_values(&t)?.into_iter(),
                    });
                }
                let pairs = t.raw_pairs()?;
                match sequence_len(&pairs) {
                    Some(_) => visitor.visit_seq(SeqAccessor {
                        lua: self.lua,
                        items: table_seq_values(&t)?.into_iter(),
                    }),
                    None => visitor.visit_map(MapAccessor {
                        lua: self.lua,
                        pairs: pairs.into_iter(),
                        pending_value: None,
                    }),
                }
            }
            other => Err(serde_error(format_args!(
                "cannot deserialize Lua {} into a serde value",
                value_type_name(&other)
            ))),
        }
    }

    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        if matches!(self.value, Value::Nil) || is_null(&self.value) {
            visitor.visit_none()
        } else {
            visitor.visit_some(self)
        }
    }

    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        if matches!(self.value, Value::Nil) || is_null(&self.value) {
            visitor.visit_unit()
        } else {
            Err(serde_error(format_args!(
                "expected nil or the null sentinel for unit, found Lua {}",
                value_type_name(&self.value)
            )))
        }
    }

    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        visitor.visit_i64(as_i64(&self.value)?)
    }

    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        visitor.visit_i64(as_i64(&self.value)?)
    }

    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        visitor.visit_i64(as_i64(&self.value)?)
    }

    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        visitor.visit_i64(as_i64(&self.value)?)
    }

    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        visitor.visit_i64(as_i64(&self.value)?)
    }

    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        visitor.visit_i64(as_i64(&self.value)?)
    }

    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        visitor.visit_i64(as_i64(&self.value)?)
    }

    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        visitor.visit_i64(as_i64(&self.value)?)
    }

    fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        self.deserialize_unit(visitor)
    }

    fn deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        visitor.visit_newtype_struct(self)
    }

    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        match self.value {
            Value::String(s) => visitor.visit_bytes(&s.as_bytes()?),
            other => Err(serde_error(format_args!(
                "expected string for bytes, found Lua {}",
                value_type_name(&other)
            ))),
        }
    }

    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        match self.value {
            Value::String(s) => visitor.visit_byte_buf(s.as_bytes()?),
            other => Err(serde_error(format_args!(
                "expected string for byte buffer, found Lua {}",
                value_type_name(&other)
            ))),
        }
    }

    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        let _depth = DepthGuard::enter()?;
        match self.value {
            Value::Table(t) => visitor.visit_seq(SeqAccessor {
                lua: self.lua,
                items: require_sequence_values(self.lua, &t)?.into_iter(),
            }),
            other => Err(serde_error(format_args!(
                "expected table for sequence, found Lua {}",
                value_type_name(&other)
            ))),
        }
    }

    fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        self.deserialize_seq(visitor)
    }

    fn deserialize_tuple_struct<V>(
        self,
        _name: &'static str,
        _len: usize,
        visitor: V,
    ) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        self.deserialize_seq(visitor)
    }

    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        let _depth = DepthGuard::enter()?;
        match self.value {
            Value::Table(t) => visitor.visit_map(MapAccessor {
                lua: self.lua,
                pairs: t.raw_pairs()?.into_iter(),
                pending_value: None,
            }),
            other => Err(serde_error(format_args!(
                "expected table for map, found Lua {}",
                value_type_name(&other)
            ))),
        }
    }

    fn deserialize_struct<V>(
        self,
        _name: &'static str,
        _fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        self.deserialize_map(visitor)
    }

    fn deserialize_enum<V>(
        self,
        _name: &'static str,
        _variants: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        let _depth = DepthGuard::enter()?;
        match self.value {
            Value::String(_) => visitor.visit_enum(EnumAccessor {
                lua: self.lua,
                variant: self.value,
                payload: None,
            }),
            Value::Table(t) => {
                let pairs = t.raw_pairs()?;
                if pairs.len() != 1 {
                    return Err(serde_error(
                        "expected a single-key table for an externally tagged enum variant",
                    ));
                }
                let (variant, payload) = pairs
                    .into_iter()
                    .next()
                    .ok_or_else(|| serde_error("enum variant table is empty"))?;
                visitor.visit_enum(EnumAccessor {
                    lua: self.lua,
                    variant,
                    payload: Some(payload),
                })
            }
            other => Err(serde_error(format_args!(
                "expected string or single-key table for enum, found Lua {}",
                value_type_name(&other)
            ))),
        }
    }

    /// Skip an ignored field without materializing it: the value is already
    /// owned, so drop it. This avoids failing a struct just because an *unknown*
    /// extra field holds a function/userdata/thread, and avoids descending into
    /// (possibly cyclic) extras.
    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        visitor.visit_unit()
    }

    serde::forward_to_deserialize_any! {
        bool i128 u128 f32 f64 char str string identifier
    }
}

/// Yields a Lua array table's elements to a serde sequence visitor.
struct SeqAccessor<'a> {
    lua: &'a Lua,
    items: std::vec::IntoIter<Value>,
}

impl<'a, 'de> SeqAccess<'de> for SeqAccessor<'a> {
    type Error = Error;

    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
    where
        T: DeserializeSeed<'de>,
    {
        match self.items.next() {
            Some(value) => seed
                .deserialize(LuaDeserializer {
                    lua: self.lua,
                    value,
                })
                .map(Some),
            None => Ok(None),
        }
    }

    fn size_hint(&self) -> Option<usize> {
        Some(self.items.len())
    }
}

/// Yields a Lua table's key/value pairs to a serde map visitor.
struct MapAccessor<'a> {
    lua: &'a Lua,
    pairs: std::vec::IntoIter<(Value, Value)>,
    pending_value: Option<Value>,
}

impl<'a, 'de> MapAccess<'de> for MapAccessor<'a> {
    type Error = Error;

    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
    where
        K: DeserializeSeed<'de>,
    {
        match self.pairs.next() {
            Some((key, value)) => {
                self.pending_value = Some(value);
                seed.deserialize(LuaDeserializer {
                    lua: self.lua,
                    value: key,
                })
                .map(Some)
            }
            None => Ok(None),
        }
    }

    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
    where
        V: DeserializeSeed<'de>,
    {
        let value = self
            .pending_value
            .take()
            .ok_or_else(|| serde_error("next_value_seed called before next_key_seed"))?;
        seed.deserialize(LuaDeserializer {
            lua: self.lua,
            value,
        })
    }

    fn size_hint(&self) -> Option<usize> {
        Some(self.pairs.len())
    }
}

/// Drives an externally tagged enum: the variant name, then its payload.
struct EnumAccessor<'a> {
    lua: &'a Lua,
    variant: Value,
    payload: Option<Value>,
}

impl<'a, 'de> EnumAccess<'de> for EnumAccessor<'a> {
    type Error = Error;
    type Variant = VariantAccessor<'a>;

    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)>
    where
        V: DeserializeSeed<'de>,
    {
        let variant = seed.deserialize(LuaDeserializer {
            lua: self.lua,
            value: self.variant,
        })?;
        Ok((
            variant,
            VariantAccessor {
                lua: self.lua,
                payload: self.payload,
            },
        ))
    }
}

/// The payload side of an externally tagged enum variant.
struct VariantAccessor<'a> {
    lua: &'a Lua,
    payload: Option<Value>,
}

impl<'a> VariantAccessor<'a> {
    /// Take the variant payload or report that one was required.
    fn take_payload(self) -> Result<Value> {
        self.payload
            .ok_or_else(|| serde_error("expected a payload for this enum variant"))
    }
}

impl<'a, 'de> VariantAccess<'de> for VariantAccessor<'a> {
    type Error = Error;

    fn unit_variant(self) -> Result<()> {
        match self.payload {
            None => Ok(()),
            Some(_) => Err(serde_error("expected a unit variant, found a payload")),
        }
    }

    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value>
    where
        T: DeserializeSeed<'de>,
    {
        let lua = self.lua;
        let value = self.take_payload()?;
        seed.deserialize(LuaDeserializer { lua, value })
    }

    fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        let lua = self.lua;
        let value = self.take_payload()?;
        LuaDeserializer { lua, value }.deserialize_seq(visitor)
    }

    fn struct_variant<V>(
        self,
        _fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        let lua = self.lua;
        let value = self.take_payload()?;
        LuaDeserializer { lua, value }.deserialize_map(visitor)
    }
}

/// A human-readable Lua type name for diagnostics.
fn value_type_name(value: &Value) -> &'static str {
    match value {
        Value::Nil => "nil",
        Value::Boolean(_) => "boolean",
        Value::Integer(_) | Value::Number(_) => "number",
        Value::String(_) => "string",
        Value::Table(_) => "table",
        Value::Function(_) => "function",
        Value::UserData(_) => "userdata",
        Value::LightUserData(_) => "light userdata",
        Value::Thread(_) => "thread",
    }
}

// ──────────────────────────────────────────────────────────────────────────
// PORT STATUS
//   source:        (no C analog — Rust-native serde integration)
//   target_crate:  omnilua
//   confidence:    high
//   todos:         0
//   port_notes:    0
//   unsafe_blocks: 0
//   notes:         serde Serializer/Deserializer over Value; mirrors mlua's
//                  LuaSerdeExt. Pure additive layer on the public Value/Table
//                  API; integer lowering reuses lower_host_int. Feature-gated
//                  behind `serde`.
// ──────────────────────────────────────────────────────────────────────────