ezlua/
serde.rs

1//! [serde](https://crates.io/crates/serde) utilities for lua
2
3use core::ops::Range;
4
5use crate::{
6    error::{Error as LuaError, Result as LuaResult},
7    ffi::lua_Integer,
8    luaapi::Type,
9    prelude::*,
10    state::State,
11};
12use alloc::{
13    fmt::Display,
14    format,
15    string::{String, ToString},
16};
17use serde::de::{DeserializeOwned, EnumAccess, IntoDeserializer, VariantAccess};
18#[rustfmt::skip]
19use ::serde::{
20    de::{Deserialize, DeserializeSeed, Deserializer, Error as DeErr, MapAccess, SeqAccess, Visitor},
21    ser::{
22        Error, Serialize, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant,
23        SerializeTuple, SerializeTupleStruct, SerializeTupleVariant, Serializer,
24    },
25};
26
27#[derive(Clone, Debug, PartialEq, Display)]
28pub enum DesErr {
29    // One or more variants that can be created by data structures through the
30    // `ser::Error` and `de::Error` traits. For example the Serialize impl for
31    // Mutex<T> might return an error because the mutex is poisoned, or the
32    // Deserialize impl for a struct may return an error because a required
33    // field is missing.
34    Message(String),
35
36    // Zero or more variants that can be created directly by the Serializer and
37    // Deserializer without going through `ser::Error` and `de::Error`. These
38    // are specific to the format, in this case JSON.
39    Eof,
40    Syntax,
41    ExpectedBoolean,
42    ExpectedInteger,
43    ExpectedString,
44    ExpectedNull,
45    ExpectedArray,
46    ExpectedArrayComma,
47    ExpectedArrayEnd,
48    ExpectedMap,
49    ExpectedMapColon,
50    ExpectedMapComma,
51    ExpectedMapEnd,
52    ExpectedEnum,
53    TrailingCharacters,
54}
55
56#[cfg(feature = "std")]
57impl std::error::Error for DesErr {}
58
59impl DeErr for DesErr {
60    fn custom<T: Display>(msg: T) -> Self {
61        DesErr::Message(msg.to_string())
62    }
63}
64
65impl DesErr {
66    pub fn context(self, info: impl Into<String>) -> Self {
67        match self {
68            Self::Message(msg) => Self::Message(format!("{}\n{msg}", info.into())),
69            _ => Self::Message(format!("{}\n{self:?}", info.into())),
70        }
71    }
72}
73
74impl State {
75    /// convert a serializable value into a lua value
76    #[inline(always)]
77    pub fn serialize_to_val<V: Serialize>(&self, v: V) -> LuaResult<ValRef> {
78        v.serialize(LuaSerializer(self))
79    }
80
81    /// transcode a serializable value from deserializer into a lua value
82    #[inline(always)]
83    pub fn load_from_deserializer<'l: 'de, 'de, D: Deserializer<'de>>(
84        &'l self,
85        deserializer: D,
86    ) -> Result<ValRef<'l>, LuaError> {
87        serde_transcode::transcode(deserializer, LuaSerializer(self))
88    }
89
90    /// A metatable attachable to a Lua table to systematically encode it as Array (instead of Map).
91    /// As result, encoded Array will contain only sequence part of the table, with the same length as the # operator on that table.
92    pub fn array_metatable(&self) -> LuaResult<LuaTable> {
93        fn key(_: &LuaTable) -> LuaResult<()> {
94            Ok(())
95        }
96
97        self.get_or_init_metatable(key)?;
98        self.top_val().try_into()
99    }
100
101    /// A special value to encode/decode optional (none) values.
102    pub fn null_value(&self) -> LuaValue {
103        LuaValue::light_userdata(Self::null_value as *const ())
104    }
105}
106
107/// Wrapper to serializable value
108#[derive(Copy, Clone, Deref, DerefMut)]
109pub struct SerdeValue<T>(pub T);
110
111#[derive(Copy, Clone, Deref, DerefMut)]
112pub struct SerdeOwnedValue<T>(pub T);
113
114impl<T: Default> Default for SerdeValue<T> {
115    fn default() -> Self {
116        Self(Default::default())
117    }
118}
119
120impl<T: Default> Default for SerdeOwnedValue<T> {
121    fn default() -> Self {
122        Self(Default::default())
123    }
124}
125
126impl<T: Serialize> ToLua for SerdeValue<T> {
127    #[inline(always)]
128    fn to_lua<'a>(self, s: &'a State) -> LuaResult<ValRef<'a>> {
129        Ok(self.serialize(LuaSerializer(s))?)
130    }
131}
132
133impl<'a, T: Deserialize<'a> + 'a> FromLua<'a> for SerdeValue<T> {
134    #[inline(always)]
135    fn from_lua(lua: &'a State, val: ValRef<'a>) -> LuaResult<SerdeValue<T>> {
136        val.check_safe_index()?;
137        unsafe {
138            // Safety: check_safe_index
139            let val: &'a ValRef = core::mem::transmute(&val);
140            T::deserialize(val).map(SerdeValue).lua_result()
141        }
142    }
143}
144
145impl<'a, T: DeserializeOwned + 'a> FromLua<'a> for SerdeOwnedValue<T> {
146    #[inline(always)]
147    fn from_lua(lua: &'a State, val: ValRef<'a>) -> LuaResult<SerdeOwnedValue<T>> {
148        T::deserialize(&val).map(SerdeOwnedValue).lua_result()
149    }
150}
151
152impl<'a> ValRef<'a> {
153    /// Deserialize a lua value
154    #[inline(always)]
155    pub fn deserialize<T: Deserialize<'a>>(&'a self) -> Result<T, DesErr> {
156        T::deserialize(self)
157    }
158
159    /// Transcode a lua value to another serialize format
160    #[inline(always)]
161    pub fn transcode<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
162        serde_transcode::transcode(self, serializer)
163    }
164}
165
166struct LuaSerializer<'a>(&'a State);
167struct LuaTableSerializer<'a> {
168    t: LuaTable<'a>,
169    k: Option<ValRef<'a>>,
170    // nil range in lua array part
171    nil: Range<i64>,
172}
173
174impl<'a> LuaTableSerializer<'a> {
175    fn restore_nil(&mut self) -> LuaResult<()> {
176        for i in self.nil.clone() {
177            self.t.raw_seti(i + 1, ())?;
178        }
179        Ok(())
180    }
181}
182
183impl<'a> SerializeSeq for LuaTableSerializer<'a> {
184    type Ok = ValRef<'a>;
185    type Error = LuaError;
186
187    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
188    where
189        T: Serialize,
190    {
191        use crate::luaapi::UnsafeLuaApi;
192
193        let state = self.t.state;
194        state.check_stack(2)?;
195        state.push(SerdeValue(value))?;
196
197        let top_is_nil = state.is_nil(-1);
198        if top_is_nil {
199            state.pop(1);
200            state.push(false)?;
201        }
202        state.raw_seti(self.t.index, self.nil.end + 1);
203        if top_is_nil {
204            self.nil.end += 1
205        } else {
206            self.restore_nil()?;
207            self.nil.end += 1;
208            self.nil.start = self.nil.end;
209        }
210
211        Ok(())
212    }
213
214    fn end(mut self) -> Result<Self::Ok, Self::Error> {
215        self.restore_nil()?;
216        Ok(self.t.into())
217    }
218}
219
220impl<'a> SerializeTuple for LuaTableSerializer<'a> {
221    type Ok = ValRef<'a>;
222    type Error = LuaError;
223
224    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
225    where
226        T: Serialize,
227    {
228        SerializeSeq::serialize_element(self, value)
229    }
230
231    fn end(self) -> Result<Self::Ok, Self::Error> {
232        SerializeSeq::end(self)
233    }
234}
235
236impl<'a> SerializeTupleStruct for LuaTableSerializer<'a> {
237    type Ok = ValRef<'a>;
238    type Error = LuaError;
239
240    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
241    where
242        T: Serialize,
243    {
244        self.k
245            .as_ref()
246            .and_then(ValRef::as_table)
247            .ok_or("variant value not set")
248            .lua_result()?
249            .push(SerdeValue(value))
250    }
251
252    fn end(self) -> Result<Self::Ok, Self::Error> {
253        SerializeSeq::end(self)
254    }
255}
256
257impl<'a> SerializeTupleVariant for LuaTableSerializer<'a> {
258    type Ok = ValRef<'a>;
259    type Error = LuaError;
260
261    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
262    where
263        T: Serialize,
264    {
265        SerializeTupleStruct::serialize_field(self, value)
266    }
267
268    fn end(self) -> Result<Self::Ok, Self::Error> {
269        SerializeTupleStruct::end(self)
270    }
271}
272
273impl<'a> LuaTableSerializer<'a> {
274    fn begin(s: &'a State, len: usize) -> LuaResult<Self> {
275        s.new_table_with_size(0, len as _).map(|val| Self {
276            t: val,
277            k: None,
278            nil: 0..0,
279        })
280    }
281
282    fn begin_array(s: &'a State, len: usize) -> LuaResult<Self> {
283        let t = s.new_array_table(len)?;
284        Ok(Self {
285            t,
286            k: None,
287            nil: 0..0,
288        })
289    }
290}
291
292impl<'a> SerializeStruct for LuaTableSerializer<'a> {
293    type Ok = ValRef<'a>;
294    type Error = LuaError;
295
296    fn serialize_field<T: ?Sized>(
297        &mut self,
298        key: &'static str,
299        value: &T,
300    ) -> Result<(), Self::Error>
301    where
302        T: Serialize,
303    {
304        self.t.raw_set(key, SerdeValue(value))
305    }
306
307    fn end(self) -> Result<Self::Ok, Self::Error> {
308        SerializeMap::end(self)
309    }
310}
311
312impl<'a> SerializeMap for LuaTableSerializer<'a> {
313    type Ok = ValRef<'a>;
314    type Error = LuaError;
315
316    fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error>
317    where
318        T: Serialize,
319    {
320        self.k.replace(self.t.state.new_val(SerdeValue(key))?);
321        Ok(())
322    }
323
324    fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
325    where
326        T: Serialize,
327    {
328        self.t.raw_set(
329            self.k.take().ok_or("no key").lua_result()?,
330            SerdeValue(value),
331        )
332    }
333
334    fn serialize_entry<K: ?Sized, V: ?Sized>(
335        &mut self,
336        key: &K,
337        value: &V,
338    ) -> Result<(), Self::Error>
339    where
340        K: Serialize,
341        V: Serialize,
342    {
343        self.t.raw_set(SerdeValue(key), SerdeValue(value))
344    }
345
346    fn end(self) -> Result<Self::Ok, Self::Error> {
347        Ok(self.t.into())
348    }
349}
350
351impl<'a> SerializeStructVariant for LuaTableSerializer<'a> {
352    type Ok = ValRef<'a>;
353    type Error = LuaError;
354
355    fn serialize_field<T: ?Sized>(
356        &mut self,
357        key: &'static str,
358        value: &T,
359    ) -> Result<(), Self::Error>
360    where
361        T: Serialize,
362    {
363        self.k
364            .as_ref()
365            .and_then(ValRef::as_table)
366            .ok_or("variant value not set")
367            .lua_result()?
368            .raw_set(key, SerdeValue(value))
369    }
370
371    fn end(self) -> Result<Self::Ok, Self::Error> {
372        SerializeStruct::end(self)
373    }
374}
375
376impl<'a> Serializer for LuaSerializer<'a> {
377    type Ok = ValRef<'a>;
378    type Error = LuaError;
379
380    type SerializeSeq = LuaTableSerializer<'a>;
381    type SerializeMap = LuaTableSerializer<'a>;
382    type SerializeTuple = LuaTableSerializer<'a>;
383    type SerializeStruct = LuaTableSerializer<'a>;
384    type SerializeStructVariant = LuaTableSerializer<'a>;
385    type SerializeTupleStruct = LuaTableSerializer<'a>;
386    type SerializeTupleVariant = LuaTableSerializer<'a>;
387
388    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
389        self.0.new_val(v)
390    }
391    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
392        self.serialize_i64(v as _)
393    }
394    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
395        self.serialize_i64(v as _)
396    }
397    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
398        self.serialize_i64(v as _)
399    }
400    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
401        self.0.new_val(v)
402    }
403    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
404        self.serialize_i64(v as _)
405    }
406    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
407        self.serialize_i64(v as _)
408    }
409    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
410        self.serialize_i64(v as _)
411    }
412    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
413        self.serialize_i64(v as _)
414    }
415    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
416        self.serialize_f64(v as _)
417    }
418    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
419        self.0.new_val(v)
420    }
421    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
422        let mut dst = [0u8; 10];
423        self.0.new_val(v.encode_utf8(&mut dst).as_bytes())
424    }
425    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
426        self.serialize_bytes(v.as_bytes())
427    }
428    fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
429        self.0.new_val(v)
430    }
431    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
432        self.0.new_val(())
433    }
434    fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
435    where
436        T: Serialize,
437    {
438        self.0.new_val(SerdeValue(value))
439    }
440
441    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
442        self.0.new_val(())
443    }
444    fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error> {
445        let mut s = LuaTableSerializer::begin(self.0, 1)?;
446        SerializeStruct::serialize_field(&mut s, "__unit_struct", name)?;
447        SerializeStruct::end(s)
448    }
449
450    fn serialize_newtype_struct<T: ?Sized>(
451        self,
452        name: &'static str,
453        value: &T,
454    ) -> Result<Self::Ok, Self::Error>
455    where
456        T: Serialize,
457    {
458        value.serialize(self)
459    }
460
461    fn serialize_unit_variant(
462        self,
463        name: &'static str,
464        variant_index: u32,
465        variant: &'static str,
466    ) -> Result<Self::Ok, Self::Error> {
467        let t = self.0.new_table_with_size(0, 4)?;
468        // t.raw_set(-1, variant_index)?;
469        // use [0] store variant name
470        // t.raw_set(0, variant)?;
471        // use false instead of nil for unit variant to prevent the variant key disappear when deserializing
472        t.raw_set(variant, false)?;
473        Ok(t.into())
474    }
475
476    fn serialize_newtype_variant<T: ?Sized>(
477        self,
478        name: &'static str,
479        variant_index: u32,
480        variant: &'static str,
481        value: &T,
482    ) -> Result<Self::Ok, Self::Error>
483    where
484        T: Serialize,
485    {
486        let t = self.0.new_table_with_size(0, 4)?;
487        // t.raw_set(-1, variant_index)?;
488        // use [0] store variant name
489        // t.raw_set(0, variant)?;
490        t.raw_set(variant, SerdeValue(value))?;
491        Ok(t.into())
492    }
493
494    fn serialize_tuple_variant(
495        self,
496        _name: &'static str,
497        variant_index: u32,
498        variant: &'static str,
499        len: usize,
500    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
501        let mut s = LuaTableSerializer::begin(self.0, 3)?;
502        // s.t.raw_set(-1, variant_index)?;
503        // use [0] store variant name
504        // s.t.raw_set(0, variant)?;
505        let t = self.0.new_array_table(len)?;
506        s.k.replace(t.0.clone());
507        s.t.raw_set(variant, t)?;
508        Ok(s)
509    }
510
511    fn serialize_struct_variant(
512        self,
513        name: &'static str,
514        variant_index: u32,
515        variant: &'static str,
516        len: usize,
517    ) -> Result<Self::SerializeStructVariant, Self::Error> {
518        let mut s = LuaTableSerializer::begin(self.0, 1)?;
519        // s.t.raw_set(-1, variant_index)?;
520        // use [0] store variant name
521        // s.t.raw_set(0, variant)?;
522        let t = self.0.new_table()?;
523        s.k.replace(t.0.clone());
524        s.t.raw_set(variant, t)?;
525        Ok(s)
526    }
527
528    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
529        Ok(LuaTableSerializer::begin_array(self.0, len.unwrap_or(0))?)
530    }
531
532    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
533        Ok(LuaTableSerializer::begin_array(self.0, len)?)
534    }
535
536    fn serialize_tuple_struct(
537        self,
538        _name: &'static str,
539        len: usize,
540    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
541        Ok(LuaTableSerializer::begin_array(self.0, len)?)
542    }
543
544    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
545        Ok(LuaTableSerializer::begin(self.0, len.unwrap_or(0))?)
546    }
547
548    fn serialize_struct(
549        self,
550        name: &'static str,
551        len: usize,
552    ) -> Result<Self::SerializeStruct, Self::Error> {
553        Ok(LuaTableSerializer::begin(self.0, len)?)
554    }
555
556    // TODO:
557    fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
558        self.serialize_i64(v as _)
559    }
560
561    // TODO:
562    fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {
563        self.serialize_u64(v as _)
564    }
565
566    // fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
567    // where
568    //     T: core::fmt::Display,
569    // {
570    //     Err(core::fmt::Error)
571    // }
572}
573
574impl<'de> Deserializer<'de> for &'de ValRef<'_> {
575    type Error = DesErr;
576
577    /// Require the `Deserializer` to figure out how to drive the visitor based
578    /// on what data type is in the input.
579    ///
580    /// When implementing `Deserialize`, you should avoid relying on
581    /// `Deserializer::deserialize_any` unless you need to be told by the
582    /// Deserializer what type is in the input. Know that relying on
583    /// `Deserializer::deserialize_any` means your data type will be able to
584    /// deserialize from self-describing formats only, ruling out Bincode and
585    /// many others.
586    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
587    where
588        V: Visitor<'de>,
589    {
590        match self.type_of() {
591            Type::Number => {
592                if self.is_integer() {
593                    visitor.visit_i64(self.to_integer())
594                } else {
595                    visitor.visit_f64(self.to_number())
596                }
597            }
598            Type::String => self.deserialize_str(visitor),
599            Type::Boolean if self.to_bool() => self.deserialize_bool(visitor),
600            Type::Boolean => self.deserialize_unit(visitor),
601            _ => {
602                if let Some(t) = self.as_table() {
603                    let is_array = t
604                        .metatable()
605                        .map_err(DeErr::custom)?
606                        .filter(|mt| {
607                            self.state
608                                .array_metatable()
609                                .map(|a| a.raw_equal(mt))
610                                .unwrap_or_default()
611                        })
612                        .is_some();
613
614                    if is_array || t.raw_len() > 0 {
615                        self.deserialize_seq(visitor)
616                    } else {
617                        self.deserialize_map(visitor)
618                    }
619                } else {
620                    visitor.visit_unit()
621                }
622            }
623        }
624    }
625
626    /// Hint that the `Deserialize` type is expecting a `bool` value.
627    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
628    where
629        V: Visitor<'de>,
630    {
631        // TODO: check strict boolean type
632        visitor.visit_bool(self.cast().map_err(|_| DesErr::ExpectedBoolean)?)
633    }
634
635    /// Hint that the `Deserialize` type is expecting an `i8` value.
636    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
637    where
638        V: Visitor<'de>,
639    {
640        // TODO: check strict integer type
641        visitor.visit_i8(self.cast().map_err(|_| DesErr::ExpectedInteger)?)
642    }
643
644    /// Hint that the `Deserialize` type is expecting an `i16` value.
645    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
646    where
647        V: Visitor<'de>,
648    {
649        visitor.visit_i16(self.cast().map_err(|_| DesErr::ExpectedInteger)?)
650    }
651
652    /// Hint that the `Deserialize` type is expecting an `i32` value.
653    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
654    where
655        V: Visitor<'de>,
656    {
657        visitor.visit_i32(self.cast().map_err(|_| DesErr::ExpectedInteger)?)
658    }
659
660    /// Hint that the `Deserialize` type is expecting an `i64` value.
661    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
662    where
663        V: Visitor<'de>,
664    {
665        visitor.visit_i64(self.cast().map_err(|_| DesErr::ExpectedInteger)?)
666    }
667
668    /// Hint that the `Deserialize` type is expecting a `u8` value.
669    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
670    where
671        V: Visitor<'de>,
672    {
673        visitor.visit_u8(self.cast().map_err(|_| DesErr::ExpectedInteger)?)
674    }
675
676    /// Hint that the `Deserialize` type is expecting a `u16` value.
677    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
678    where
679        V: Visitor<'de>,
680    {
681        visitor.visit_u16(self.cast().map_err(|_| DesErr::ExpectedInteger)?)
682    }
683
684    /// Hint that the `Deserialize` type is expecting a `u32` value.
685    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
686    where
687        V: Visitor<'de>,
688    {
689        visitor.visit_u32(self.cast().map_err(|_| DesErr::ExpectedInteger)?)
690    }
691
692    /// Hint that the `Deserialize` type is expecting a `u64` value.
693    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
694    where
695        V: Visitor<'de>,
696    {
697        visitor.visit_u64(self.cast().map_err(|_| DesErr::ExpectedInteger)?)
698    }
699
700    /// Hint that the `Deserialize` type is expecting a `f32` value.
701    fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
702    where
703        V: Visitor<'de>,
704    {
705        visitor.visit_f32(self.cast().map_err(|_| DesErr::ExpectedInteger)?)
706    }
707
708    /// Hint that the `Deserialize` type is expecting a `f64` value.
709    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
710    where
711        V: Visitor<'de>,
712    {
713        visitor.visit_f64(self.cast().map_err(|_| DesErr::ExpectedInteger)?)
714    }
715
716    /// Hint that the `Deserialize` type is expecting a `char` value.
717    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
718    where
719        V: Visitor<'de>,
720    {
721        match self.type_of() {
722            Type::Number => visitor.visit_char(self.cast::<u8>().unwrap() as _),
723            Type::String => visitor.visit_char(
724                self.to_str()
725                    .map(|s| s.chars())
726                    .into_iter()
727                    .flatten()
728                    .next()
729                    .ok_or(DesErr::Message("empty char".into()))?,
730            ),
731            _ => Err(DesErr::Message("invalid char type".into())),
732        }
733    }
734
735    /// Hint that the `Deserialize` type is expecting a string value and does
736    /// not benefit from taking ownership of buffered data owned by the
737    /// `Deserializer`.
738    ///
739    /// If the `Visitor` would benefit from taking ownership of `String` data,
740    /// indiciate this to the `Deserializer` by using `deserialize_string`
741    /// instead.
742    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
743    where
744        V: Visitor<'de>,
745    {
746        visitor.visit_borrowed_str(self.to_str().ok_or(DesErr::ExpectedString)?)
747    }
748
749    /// Hint that the `Deserialize` type is expecting a string value and would
750    /// benefit from taking ownership of buffered data owned by the
751    /// `Deserializer`.
752    ///
753    /// If the `Visitor` would not benefit from taking ownership of `String`
754    /// data, indicate that to the `Deserializer` by using `deserialize_str`
755    /// instead.
756    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
757    where
758        V: Visitor<'de>,
759    {
760        self.deserialize_str(visitor)
761    }
762
763    /// Hint that the `Deserialize` type is expecting a byte array and does not
764    /// benefit from taking ownership of buffered data owned by the
765    /// `Deserializer`.
766    ///
767    /// If the `Visitor` would benefit from taking ownership of `Vec<u8>` data,
768    /// indicate this to the `Deserializer` by using `deserialize_byte_buf`
769    /// instead.
770    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
771    where
772        V: Visitor<'de>,
773    {
774        visitor.visit_borrowed_bytes(self.to_bytes().ok_or(DesErr::ExpectedString)?)
775    }
776
777    /// Hint that the `Deserialize` type is expecting a byte array and would
778    /// benefit from taking ownership of buffered data owned by the
779    /// `Deserializer`.
780    ///
781    /// If the `Visitor` would not benefit from taking ownership of `Vec<u8>`
782    /// data, indicate that to the `Deserializer` by using `deserialize_bytes`
783    /// instead.
784    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
785    where
786        V: Visitor<'de>,
787    {
788        self.deserialize_bytes(visitor)
789    }
790
791    /// Hint that the `Deserialize` type is expecting an optional value.
792    ///
793    /// This allows deserializers that encode an optional value as a nullable
794    /// value to convert the null value into `None` and a regular value into
795    /// `Some(value)`.
796    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
797    where
798        V: Visitor<'de>,
799    {
800        if self.type_of().is_none_or_nil() {
801            visitor.visit_none()
802        } else {
803            visitor.visit_some(self)
804        }
805    }
806
807    /// Hint that the `Deserialize` type is expecting a unit value.
808    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
809    where
810        V: Visitor<'de>,
811    {
812        visitor.visit_unit()
813        // if self.type_of().is_none_or_nil() {
814        // } else {
815        //     Err(DesErr::ExpectedNull)
816        // }
817    }
818
819    /// Hint that the `Deserialize` type is expecting a unit struct with a
820    /// particular name.
821    fn deserialize_unit_struct<V>(
822        self,
823        name: &'static str,
824        visitor: V,
825    ) -> Result<V::Value, Self::Error>
826    where
827        V: Visitor<'de>,
828    {
829        self.deserialize_unit(visitor)
830            .map_err(|err| err.context(format!("unit_struct {name}:")))
831    }
832
833    /// Hint that the `Deserialize` type is expecting a newtype struct with a
834    /// particular name.
835    fn deserialize_newtype_struct<V>(
836        self,
837        name: &'static str,
838        visitor: V,
839    ) -> Result<V::Value, Self::Error>
840    where
841        V: Visitor<'de>,
842    {
843        visitor
844            .visit_newtype_struct(self)
845            .map_err(|err| err.context(format!("newtype_struct {name}:")))
846    }
847
848    /// Hint that the `Deserialize` type is expecting a sequence of values.
849    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
850    where
851        V: Visitor<'de>,
852    {
853        if let Some(t) = self.as_table() {
854            let len = t.raw_len();
855            visitor.visit_seq(SeqDes(t, 1, len))
856        } else {
857            Err(DesErr::ExpectedArray)
858        }
859    }
860
861    /// Hint that the `Deserialize` type is expecting a sequence of values and
862    /// knows how many values there are without looking at the serialized data.
863    fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
864    where
865        V: Visitor<'de>,
866    {
867        if let Some(t) = self.as_table() {
868            visitor.visit_seq(SeqDes(t, 1, len))
869        } else {
870            Err(DesErr::ExpectedArray)
871        }
872    }
873
874    /// Hint that the `Deserialize` type is expecting a tuple struct with a
875    /// particular name and number of fields.
876    fn deserialize_tuple_struct<V>(
877        self,
878        name: &'static str,
879        len: usize,
880        visitor: V,
881    ) -> Result<V::Value, Self::Error>
882    where
883        V: Visitor<'de>,
884    {
885        self.deserialize_seq(visitor)
886            .map_err(|err| err.context(format!("tuple_struct {name}:")))
887    }
888
889    /// Hint that the `Deserialize` type is expecting a map of key-value pairs.
890    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
891    where
892        V: Visitor<'de>,
893    {
894        struct ValIter<'a, I: Iterator<Item = (ValRef<'a>, ValRef<'a>)> + 'a>(
895            I,
896            Option<ValRef<'a>>,
897        );
898
899        impl<'a, I: Iterator<Item = (ValRef<'a>, ValRef<'a>)> + 'a> MapAccess<'a> for ValIter<'a, I> {
900            type Error = DesErr;
901
902            fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
903            where
904                T: DeserializeSeed<'a>,
905            {
906                self.0
907                    .next()
908                    .map(|(k, v)| {
909                        self.1.replace(v);
910                        // Safety: k is also referenced by the parent table
911                        let val: &'a ValRef = unsafe { core::mem::transmute(&k) };
912                        seed.deserialize(val)
913                    })
914                    .transpose()
915            }
916
917            fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
918            where
919                V: DeserializeSeed<'a>,
920            {
921                let val = self.1.take().ok_or(DesErr::Eof)?;
922                // Safety: val is also referenced by the parent table
923                let val: &'a ValRef = unsafe { core::mem::transmute(&val) };
924                seed.deserialize(val)
925            }
926        }
927
928        // crash if index is not a table
929        if let Some(t) = self.as_table() {
930            visitor.visit_map(ValIter(t.iter().map_err(DeErr::custom)?, None))
931        } else {
932            Err(DesErr::ExpectedMap)
933        }
934    }
935
936    /// Hint that the `Deserialize` type is expecting a struct with a particular
937    /// name and fields.
938    fn deserialize_struct<V>(
939        self,
940        name: &'static str,
941        fields: &'static [&'static str],
942        visitor: V,
943    ) -> Result<V::Value, Self::Error>
944    where
945        V: Visitor<'de>,
946    {
947        self.deserialize_map(visitor)
948            .map_err(|err| err.context(format!("struct {name}:")))
949    }
950
951    /// Hint that the `Deserialize` type is expecting an enum value with a
952    /// particular name and possible variants.
953    fn deserialize_enum<V>(
954        self,
955        name: &'static str,
956        variants: &'static [&'static str],
957        visitor: V,
958    ) -> Result<V::Value, Self::Error>
959    where
960        V: Visitor<'de>,
961    {
962        struct EnumDeser<'a> {
963            variant: String,
964            value: Option<ValRef<'a>>,
965        }
966
967        impl<'lua> EnumAccess<'lua> for EnumDeser<'lua> {
968            type Error = DesErr;
969            type Variant = VariantDeser<'lua>;
970
971            fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
972            where
973                T: DeserializeSeed<'lua>,
974            {
975                // std::println!("[variant] {}", self.variant);
976                let variant = self.variant.into_deserializer();
977                let variant_access = VariantDeser { value: self.value };
978                seed.deserialize(variant).map(|v| (v, variant_access))
979            }
980        }
981
982        struct VariantDeser<'a> {
983            value: Option<ValRef<'a>>,
984        }
985
986        impl<'de> VariantAccess<'de> for VariantDeser<'de> {
987            type Error = DesErr;
988
989            fn unit_variant(self) -> Result<(), Self::Error> {
990                // unit_variant can be any type
991                // match self.value {
992                //     Some(_) => Err(DesErr::custom(format!("unit_variant"))),
993                //     None => Ok(()),
994                // }
995                Ok(())
996            }
997
998            fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
999            where
1000                T: DeserializeSeed<'de>,
1001            {
1002                match self.value {
1003                    Some(value) => {
1004                        // Safety: val is also referenced by the self table
1005                        let val: &'de ValRef = unsafe { core::mem::transmute(&value) };
1006                        seed.deserialize(val)
1007                    }
1008                    None => Err(DesErr::custom(format!("newtype variant"))),
1009                }
1010            }
1011
1012            fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
1013            where
1014                V: Visitor<'de>,
1015            {
1016                match self.value {
1017                    Some(value) => {
1018                        // Safety: val is also referenced by the self table
1019                        let val: &'de ValRef = unsafe { core::mem::transmute(&value) };
1020                        if let Some(t) = val.as_table() {
1021                            visitor.visit_seq(SeqDes(t, 1, len))
1022                        } else {
1023                            Err(DesErr::ExpectedArray)
1024                        }
1025                    }
1026                    None => Err(DesErr::custom(format!("tuple variant"))),
1027                }
1028            }
1029
1030            fn struct_variant<V>(
1031                self,
1032                _fields: &'static [&'static str],
1033                visitor: V,
1034            ) -> Result<V::Value, Self::Error>
1035            where
1036                V: Visitor<'de>,
1037            {
1038                match self.value {
1039                    Some(value) => {
1040                        // Safety: val is also referenced by the self table
1041                        let val: &'de ValRef = unsafe { core::mem::transmute(&value) };
1042                        serde::Deserializer::deserialize_map(val, visitor)
1043                    }
1044                    None => Err(DesErr::custom(format!("struct variant"))),
1045                }
1046            }
1047        }
1048
1049        visitor
1050            .visit_enum(if let Some(s) = self.to_str() {
1051                EnumDeser {
1052                    variant: s.into(),
1053                    value: None,
1054                }
1055            } else if let Some((k, v)) = self
1056                .as_table()
1057                .and_then(|t| t.iter().ok()?.find(|(k, _)| k.type_of() == Type::String))
1058                .and_then(|(k, v)| String::from_lua(k.state(), k).ok().map(|k| (k, v)))
1059            {
1060                EnumDeser {
1061                    variant: k,
1062                    value: Some(v),
1063                }
1064            } else {
1065                return Err(DesErr::ExpectedEnum);
1066            })
1067            .map_err(|err| err.context(format!("enum {name}:")))
1068    }
1069
1070    /// Hint that the `Deserialize` type is expecting the name of a struct
1071    /// field or the discriminant of an enum variant.
1072    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1073    where
1074        V: Visitor<'de>,
1075    {
1076        self.deserialize_str(visitor)
1077    }
1078
1079    /// Hint that the `Deserialize` type needs to deserialize a value whose type
1080    /// doesn't matter because it is ignored.
1081    ///
1082    /// Deserializers for non-self-describing formats may not support this mode.
1083    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1084    where
1085        V: Visitor<'de>,
1086    {
1087        self.deserialize_any(visitor)
1088    }
1089}
1090
1091struct SeqDes<'a, 'b>(&'a LuaTable<'b>, usize, usize);
1092
1093impl<'de> SeqAccess<'de> for SeqDes<'de, '_> {
1094    type Error = DesErr;
1095
1096    #[inline]
1097    fn size_hint(&self) -> Option<usize> {
1098        Some(self.2)
1099    }
1100
1101    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
1102    where
1103        T: DeserializeSeed<'de>,
1104    {
1105        if self.1 > self.2 {
1106            return Ok(None);
1107        }
1108        let val = self
1109            .0
1110            .raw_geti(self.1 as lua_Integer)
1111            .map_err(DesErr::custom)?;
1112        self.1 += 1;
1113        // Safety: val is also referenced by the self table
1114        let val: &'de ValRef = unsafe { core::mem::transmute(&val) };
1115        let r = seed.deserialize(val)?;
1116        Ok(Some(r))
1117    }
1118}
1119
1120impl Serialize for ValRef<'_> {
1121    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1122        use core::cell::RefCell;
1123        use core::ffi::c_void;
1124        use std::collections::HashSet;
1125
1126        std::thread_local! {
1127            static VISITED: RefCell<HashSet<*const c_void>> = RefCell::new(HashSet::default());
1128        }
1129
1130        match self.type_of() {
1131            Type::String => {
1132                let bytes = self.to_bytes().unwrap_or_default();
1133                // TODO: serde option
1134                // if bytes.len() > 0x1000 {
1135                //     serializer.serialize_bytes(bytes)
1136                // } else {
1137                match core::str::from_utf8(bytes) {
1138                    Ok(s) => serializer.serialize_str(s),
1139                    Err(_) => serializer.serialize_bytes(bytes),
1140                }
1141                // }
1142            }
1143            Type::Number => {
1144                if self.is_integer() {
1145                    serializer.serialize_i64(self.to_integer())
1146                } else {
1147                    serializer.serialize_f64(self.to_number())
1148                }
1149            }
1150            // TODO: serde option
1151            Type::Function => serializer.serialize_bool(true),
1152            Type::Boolean => serializer.serialize_bool(self.to_bool()),
1153            Type::LightUserdata => {
1154                if self.to_pointer() == State::null_value as *const c_void {
1155                    serializer.serialize_none()
1156                } else {
1157                    serializer.serialize_none()
1158                }
1159            }
1160            _ => {
1161                if let Some(t) = self.as_table() {
1162                    let ptr = t.to_pointer();
1163                    let result = VISITED.with(|visited| {
1164                        {
1165                            let mut visited = visited.borrow_mut();
1166                            if visited.contains(&ptr) {
1167                                return Err(Error::custom("recursive table detected"));
1168                            }
1169                            visited.insert(ptr);
1170                        }
1171
1172                        let len = t.raw_len() as usize;
1173                        let is_array = t
1174                            .metatable()
1175                            .map_err(Error::custom)?
1176                            .filter(|mt| {
1177                                self.state
1178                                    .array_metatable()
1179                                    .map(|a| a.raw_equal(mt))
1180                                    .unwrap_or_default()
1181                            })
1182                            .is_some();
1183
1184                        t.state.check_stack(3).map_err(Error::custom)?;
1185
1186                        if is_array || len > 0 {
1187                            let mut seq = serializer.serialize_seq(Some(len))?;
1188                            for i in 1..=len {
1189                                seq.serialize_element(
1190                                    &t.raw_geti(i as lua_Integer).map_err(Error::custom)?,
1191                                )?;
1192                            }
1193                            seq.end()
1194                        } else {
1195                            let mut map = serializer.serialize_map(None)?;
1196                            for (k, v) in t.iter().map_err(Error::custom)? {
1197                                map.serialize_entry(&k, &v)?;
1198                            }
1199                            map.end()
1200                        }
1201                    });
1202                    VISITED.with(|v| v.borrow_mut().remove(&ptr));
1203                    result
1204                } else {
1205                    serializer.serialize_none()
1206                }
1207            }
1208        }
1209    }
1210}
1211
1212impl Error for LuaError {
1213    fn custom<T>(msg: T) -> Self
1214    where
1215        T: Display,
1216    {
1217        Self::Runtime(msg.to_string())
1218    }
1219}