Skip to main content

mlua/
conversion.rs

1use std::borrow::Cow;
2use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
3use std::ffi::{CStr, CString, OsStr, OsString};
4use std::hash::{BuildHasher, Hash};
5use std::os::raw::c_int;
6use std::path::{Path, PathBuf};
7use std::string::String as StdString;
8use std::{mem, slice, str};
9
10use bstr::{BStr, BString, ByteSlice, ByteVec};
11use num_traits::cast;
12
13use crate::error::{Error, Result};
14use crate::function::Function;
15use crate::state::{Lua, RawLua};
16use crate::string::{BorrowedBytes, BorrowedStr, String};
17use crate::table::Table;
18use crate::thread::Thread;
19use crate::traits::{FromLua, IntoLua, ShortTypeName as _};
20use crate::types::{Either, LightUserData, MaybeSend, RegistryKey};
21use crate::userdata::{AnyUserData, UserData};
22use crate::value::{Nil, Value};
23
24impl IntoLua for Value {
25    #[inline]
26    fn into_lua(self, _: &Lua) -> Result<Value> {
27        Ok(self)
28    }
29}
30
31impl IntoLua for &Value {
32    #[inline]
33    fn into_lua(self, _: &Lua) -> Result<Value> {
34        Ok(self.clone())
35    }
36
37    #[inline]
38    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
39        lua.push_value(self)
40    }
41}
42
43impl FromLua for Value {
44    #[inline]
45    fn from_lua(lua_value: Value, _: &Lua) -> Result<Self> {
46        Ok(lua_value)
47    }
48}
49
50impl IntoLua for String {
51    #[inline]
52    fn into_lua(self, _: &Lua) -> Result<Value> {
53        Ok(Value::String(self))
54    }
55}
56
57impl IntoLua for &String {
58    #[inline]
59    fn into_lua(self, _: &Lua) -> Result<Value> {
60        Ok(Value::String(self.clone()))
61    }
62
63    #[inline]
64    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
65        lua.push_ref(&self.0);
66        Ok(())
67    }
68}
69
70impl FromLua for String {
71    #[inline]
72    fn from_lua(value: Value, lua: &Lua) -> Result<String> {
73        let ty = value.type_name();
74        lua.coerce_string(value)?
75            .ok_or_else(|| Error::FromLuaConversionError {
76                from: ty,
77                to: "string".to_string(),
78                message: Some("expected string or number".to_string()),
79            })
80    }
81
82    unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
83        let state = lua.state();
84        let type_id = ffi::lua_type(state, idx);
85        if type_id == ffi::LUA_TSTRING {
86            ffi::lua_xpush(state, lua.ref_thread(), idx);
87            return Ok(String(lua.pop_ref_thread()));
88        }
89        // Fallback to default
90        Self::from_lua(lua.stack_value(idx, Some(type_id)), lua.lua())
91    }
92}
93
94impl IntoLua for BorrowedStr<'_> {
95    #[inline]
96    fn into_lua(self, _: &Lua) -> Result<Value> {
97        Ok(Value::String(self.borrow.into_owned()))
98    }
99
100    #[inline]
101    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
102        lua.push_ref(&self.borrow.0);
103        Ok(())
104    }
105}
106
107impl IntoLua for &BorrowedStr<'_> {
108    #[inline]
109    fn into_lua(self, _: &Lua) -> Result<Value> {
110        Ok(Value::String(self.borrow.clone().into_owned()))
111    }
112
113    #[inline]
114    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
115        lua.push_ref(&self.borrow.0);
116        Ok(())
117    }
118}
119
120impl FromLua for BorrowedStr<'_> {
121    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
122        let s = String::from_lua(value, lua)?;
123        let BorrowedStr { buf, _lua, .. } = BorrowedStr::try_from(&s)?;
124        let buf = unsafe { mem::transmute::<&str, &'static str>(buf) };
125        let borrow = Cow::Owned(s);
126        Ok(Self { buf, borrow, _lua })
127    }
128
129    unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
130        let s = String::from_stack(idx, lua)?;
131        let BorrowedStr { buf, _lua, .. } = BorrowedStr::try_from(&s)?;
132        let buf = unsafe { mem::transmute::<&str, &'static str>(buf) };
133        let borrow = Cow::Owned(s);
134        Ok(Self { buf, borrow, _lua })
135    }
136}
137
138impl IntoLua for BorrowedBytes<'_> {
139    #[inline]
140    fn into_lua(self, _: &Lua) -> Result<Value> {
141        Ok(Value::String(self.borrow.into_owned()))
142    }
143
144    #[inline]
145    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
146        lua.push_ref(&self.borrow.0);
147        Ok(())
148    }
149}
150
151impl IntoLua for &BorrowedBytes<'_> {
152    #[inline]
153    fn into_lua(self, _: &Lua) -> Result<Value> {
154        Ok(Value::String(self.borrow.clone().into_owned()))
155    }
156
157    #[inline]
158    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
159        lua.push_ref(&self.borrow.0);
160        Ok(())
161    }
162}
163
164impl FromLua for BorrowedBytes<'_> {
165    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
166        let s = String::from_lua(value, lua)?;
167        let BorrowedBytes { buf, _lua, .. } = BorrowedBytes::from(&s);
168        let buf = unsafe { mem::transmute::<&[u8], &'static [u8]>(buf) };
169        let borrow = Cow::Owned(s);
170        Ok(Self { buf, borrow, _lua })
171    }
172
173    unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
174        let s = String::from_stack(idx, lua)?;
175        let BorrowedBytes { buf, _lua, .. } = BorrowedBytes::from(&s);
176        let buf = unsafe { mem::transmute::<&[u8], &'static [u8]>(buf) };
177        let borrow = Cow::Owned(s);
178        Ok(Self { buf, borrow, _lua })
179    }
180}
181
182impl IntoLua for Table {
183    #[inline]
184    fn into_lua(self, _: &Lua) -> Result<Value> {
185        Ok(Value::Table(self))
186    }
187}
188
189impl IntoLua for &Table {
190    #[inline]
191    fn into_lua(self, _: &Lua) -> Result<Value> {
192        Ok(Value::Table(self.clone()))
193    }
194
195    #[inline]
196    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
197        lua.push_ref(&self.0);
198        Ok(())
199    }
200}
201
202impl FromLua for Table {
203    #[inline]
204    fn from_lua(value: Value, _: &Lua) -> Result<Table> {
205        match value {
206            Value::Table(table) => Ok(table),
207            _ => Err(Error::FromLuaConversionError {
208                from: value.type_name(),
209                to: "table".to_string(),
210                message: None,
211            }),
212        }
213    }
214}
215
216impl IntoLua for Function {
217    #[inline]
218    fn into_lua(self, _: &Lua) -> Result<Value> {
219        Ok(Value::Function(self))
220    }
221}
222
223impl IntoLua for &Function {
224    #[inline]
225    fn into_lua(self, _: &Lua) -> Result<Value> {
226        Ok(Value::Function(self.clone()))
227    }
228
229    #[inline]
230    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
231        lua.push_ref(&self.0);
232        Ok(())
233    }
234}
235
236impl FromLua for Function {
237    #[inline]
238    fn from_lua(value: Value, _: &Lua) -> Result<Function> {
239        match value {
240            Value::Function(table) => Ok(table),
241            _ => Err(Error::FromLuaConversionError {
242                from: value.type_name(),
243                to: "function".to_string(),
244                message: None,
245            }),
246        }
247    }
248}
249
250impl IntoLua for Thread {
251    #[inline]
252    fn into_lua(self, _: &Lua) -> Result<Value> {
253        Ok(Value::Thread(self))
254    }
255}
256
257impl IntoLua for &Thread {
258    #[inline]
259    fn into_lua(self, _: &Lua) -> Result<Value> {
260        Ok(Value::Thread(self.clone()))
261    }
262
263    #[inline]
264    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
265        lua.push_ref(&self.0);
266        Ok(())
267    }
268}
269
270impl FromLua for Thread {
271    #[inline]
272    fn from_lua(value: Value, _: &Lua) -> Result<Thread> {
273        match value {
274            Value::Thread(t) => Ok(t),
275            _ => Err(Error::FromLuaConversionError {
276                from: value.type_name(),
277                to: "thread".to_string(),
278                message: None,
279            }),
280        }
281    }
282}
283
284impl IntoLua for AnyUserData {
285    #[inline]
286    fn into_lua(self, _: &Lua) -> Result<Value> {
287        Ok(Value::UserData(self))
288    }
289}
290
291impl IntoLua for &AnyUserData {
292    #[inline]
293    fn into_lua(self, _: &Lua) -> Result<Value> {
294        Ok(Value::UserData(self.clone()))
295    }
296
297    #[inline]
298    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
299        lua.push_ref(&self.0);
300        Ok(())
301    }
302}
303
304impl FromLua for AnyUserData {
305    #[inline]
306    fn from_lua(value: Value, _: &Lua) -> Result<AnyUserData> {
307        match value {
308            Value::UserData(ud) => Ok(ud),
309            _ => Err(Error::FromLuaConversionError {
310                from: value.type_name(),
311                to: "userdata".to_string(),
312                message: None,
313            }),
314        }
315    }
316}
317
318impl<T: UserData + MaybeSend + 'static> IntoLua for T {
319    #[inline]
320    fn into_lua(self, lua: &Lua) -> Result<Value> {
321        Ok(Value::UserData(lua.create_userdata(self)?))
322    }
323}
324
325impl IntoLua for Error {
326    #[inline]
327    fn into_lua(self, _: &Lua) -> Result<Value> {
328        Ok(Value::Error(Box::new(self)))
329    }
330}
331
332impl FromLua for Error {
333    #[inline]
334    fn from_lua(value: Value, _: &Lua) -> Result<Error> {
335        match value {
336            Value::Error(err) => Ok(*err),
337            val => Ok(Error::runtime(val.to_string()?)),
338        }
339    }
340}
341
342#[cfg(feature = "anyhow")]
343impl IntoLua for anyhow::Error {
344    #[inline]
345    fn into_lua(self, _: &Lua) -> Result<Value> {
346        Ok(Value::Error(Box::new(Error::from(self))))
347    }
348}
349
350impl IntoLua for RegistryKey {
351    #[inline]
352    fn into_lua(self, lua: &Lua) -> Result<Value> {
353        lua.registry_value(&self)
354    }
355
356    #[inline]
357    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
358        <&RegistryKey>::push_into_stack(&self, lua)
359    }
360}
361
362impl IntoLua for &RegistryKey {
363    #[inline]
364    fn into_lua(self, lua: &Lua) -> Result<Value> {
365        lua.registry_value(self)
366    }
367
368    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
369        if !lua.owns_registry_value(self) {
370            return Err(Error::MismatchedRegistryKey);
371        }
372
373        match self.id() {
374            ffi::LUA_REFNIL => ffi::lua_pushnil(lua.state()),
375            id => {
376                ffi::lua_rawgeti(lua.state(), ffi::LUA_REGISTRYINDEX, id as _);
377            }
378        }
379        Ok(())
380    }
381}
382
383impl FromLua for RegistryKey {
384    #[inline]
385    fn from_lua(value: Value, lua: &Lua) -> Result<RegistryKey> {
386        lua.create_registry_value(value)
387    }
388}
389
390impl IntoLua for bool {
391    #[inline]
392    fn into_lua(self, _: &Lua) -> Result<Value> {
393        Ok(Value::Boolean(self))
394    }
395
396    #[inline]
397    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
398        ffi::lua_pushboolean(lua.state(), self as c_int);
399        Ok(())
400    }
401}
402
403impl FromLua for bool {
404    #[inline]
405    fn from_lua(v: Value, _: &Lua) -> Result<Self> {
406        match v {
407            Value::Nil => Ok(false),
408            Value::Boolean(b) => Ok(b),
409            _ => Ok(true),
410        }
411    }
412
413    #[inline]
414    unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
415        Ok(ffi::lua_toboolean(lua.state(), idx) != 0)
416    }
417}
418
419impl IntoLua for LightUserData {
420    #[inline]
421    fn into_lua(self, _: &Lua) -> Result<Value> {
422        Ok(Value::LightUserData(self))
423    }
424}
425
426impl FromLua for LightUserData {
427    #[inline]
428    fn from_lua(value: Value, _: &Lua) -> Result<Self> {
429        match value {
430            Value::LightUserData(ud) => Ok(ud),
431            _ => Err(Error::FromLuaConversionError {
432                from: value.type_name(),
433                to: "lightuserdata".to_string(),
434                message: None,
435            }),
436        }
437    }
438}
439
440#[cfg(feature = "luau")]
441impl IntoLua for crate::Vector {
442    #[inline]
443    fn into_lua(self, _: &Lua) -> Result<Value> {
444        Ok(Value::Vector(self))
445    }
446}
447
448#[cfg(feature = "luau")]
449impl FromLua for crate::Vector {
450    #[inline]
451    fn from_lua(value: Value, _: &Lua) -> Result<Self> {
452        match value {
453            Value::Vector(v) => Ok(v),
454            _ => Err(Error::FromLuaConversionError {
455                from: value.type_name(),
456                to: "vector".to_string(),
457                message: None,
458            }),
459        }
460    }
461}
462
463#[cfg(feature = "luau")]
464impl IntoLua for crate::Buffer {
465    #[inline]
466    fn into_lua(self, _: &Lua) -> Result<Value> {
467        Ok(Value::Buffer(self))
468    }
469}
470
471#[cfg(feature = "luau")]
472impl IntoLua for &crate::Buffer {
473    #[inline]
474    fn into_lua(self, _: &Lua) -> Result<Value> {
475        Ok(Value::Buffer(self.clone()))
476    }
477
478    #[inline]
479    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
480        lua.push_ref(&self.0);
481        Ok(())
482    }
483}
484
485#[cfg(feature = "luau")]
486impl FromLua for crate::Buffer {
487    #[inline]
488    fn from_lua(value: Value, _: &Lua) -> Result<Self> {
489        match value {
490            Value::Buffer(buf) => Ok(buf),
491            _ => Err(Error::FromLuaConversionError {
492                from: value.type_name(),
493                to: "buffer".to_string(),
494                message: None,
495            }),
496        }
497    }
498}
499
500impl IntoLua for StdString {
501    #[inline]
502    fn into_lua(self, lua: &Lua) -> Result<Value> {
503        #[cfg(feature = "lua55")]
504        if true {
505            return Ok(Value::String(lua.create_external_string(self)?));
506        }
507
508        Ok(Value::String(lua.create_string(self)?))
509    }
510
511    #[inline]
512    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
513        #[cfg(feature = "lua55")]
514        if lua.unlikely_memory_error() {
515            return crate::util::push_external_string(lua.state(), self.into(), false);
516        }
517
518        push_bytes_into_stack(self, lua)
519    }
520}
521
522impl FromLua for StdString {
523    #[inline]
524    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
525        let ty = value.type_name();
526        Ok(lua
527            .coerce_string(value)?
528            .ok_or_else(|| Error::FromLuaConversionError {
529                from: ty,
530                to: Self::type_name(),
531                message: Some("expected string or number".to_string()),
532            })?
533            .to_str()?
534            .to_owned())
535    }
536
537    #[inline]
538    unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
539        let state = lua.state();
540        let type_id = ffi::lua_type(state, idx);
541        if type_id == ffi::LUA_TSTRING {
542            let mut size = 0;
543            let data = ffi::lua_tolstring(state, idx, &mut size);
544            let bytes = slice::from_raw_parts(data as *const u8, size);
545            return str::from_utf8(bytes)
546                .map(|s| s.to_owned())
547                .map_err(|e| Error::FromLuaConversionError {
548                    from: "string",
549                    to: Self::type_name(),
550                    message: Some(e.to_string()),
551                });
552        }
553        // Fallback to default
554        Self::from_lua(lua.stack_value(idx, Some(type_id)), lua.lua())
555    }
556}
557
558impl IntoLua for &str {
559    #[inline]
560    fn into_lua(self, lua: &Lua) -> Result<Value> {
561        Ok(Value::String(lua.create_string(self)?))
562    }
563
564    #[inline]
565    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
566        push_bytes_into_stack(self, lua)
567    }
568}
569
570impl IntoLua for Cow<'_, str> {
571    #[inline]
572    fn into_lua(self, lua: &Lua) -> Result<Value> {
573        Ok(Value::String(lua.create_string(self.as_bytes())?))
574    }
575}
576
577impl IntoLua for Box<str> {
578    #[inline]
579    fn into_lua(self, lua: &Lua) -> Result<Value> {
580        Ok(Value::String(lua.create_string(&*self)?))
581    }
582}
583
584impl FromLua for Box<str> {
585    #[inline]
586    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
587        let ty = value.type_name();
588        Ok(lua
589            .coerce_string(value)?
590            .ok_or_else(|| Error::FromLuaConversionError {
591                from: ty,
592                to: Self::type_name(),
593                message: Some("expected string or number".to_string()),
594            })?
595            .to_str()?
596            .to_owned()
597            .into_boxed_str())
598    }
599}
600
601impl IntoLua for CString {
602    #[inline]
603    fn into_lua(self, lua: &Lua) -> Result<Value> {
604        #[cfg(feature = "lua55")]
605        if true {
606            return Ok(Value::String(lua.create_external_string(self)?));
607        }
608
609        Ok(Value::String(lua.create_string(self.as_bytes())?))
610    }
611}
612
613impl FromLua for CString {
614    #[inline]
615    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
616        let ty = value.type_name();
617        let string = lua
618            .coerce_string(value)?
619            .ok_or_else(|| Error::FromLuaConversionError {
620                from: ty,
621                to: Self::type_name(),
622                message: Some("expected string or number".to_string()),
623            })?;
624
625        match CStr::from_bytes_with_nul(&string.as_bytes_with_nul()) {
626            Ok(s) => Ok(s.into()),
627            Err(_) => Err(Error::FromLuaConversionError {
628                from: ty,
629                to: Self::type_name(),
630                message: Some("invalid C-style string".to_string()),
631            }),
632        }
633    }
634}
635
636impl IntoLua for &CStr {
637    #[inline]
638    fn into_lua(self, lua: &Lua) -> Result<Value> {
639        Ok(Value::String(lua.create_string(self.to_bytes())?))
640    }
641}
642
643impl IntoLua for Cow<'_, CStr> {
644    #[inline]
645    fn into_lua(self, lua: &Lua) -> Result<Value> {
646        Ok(Value::String(lua.create_string(self.to_bytes())?))
647    }
648}
649
650impl IntoLua for BString {
651    #[inline]
652    fn into_lua(self, lua: &Lua) -> Result<Value> {
653        #[cfg(feature = "lua55")]
654        if true {
655            return Ok(Value::String(lua.create_external_string(self)?));
656        }
657
658        Ok(Value::String(lua.create_string(self)?))
659    }
660}
661
662impl FromLua for BString {
663    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
664        let ty = value.type_name();
665        match value {
666            Value::String(s) => Ok((*s.as_bytes()).into()),
667            #[cfg(feature = "luau")]
668            Value::Buffer(buf) => Ok(buf.to_vec().into()),
669            _ => Ok((*lua
670                .coerce_string(value)?
671                .ok_or_else(|| Error::FromLuaConversionError {
672                    from: ty,
673                    to: Self::type_name(),
674                    message: Some("expected string or number".to_string()),
675                })?
676                .as_bytes())
677            .into()),
678        }
679    }
680
681    unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
682        let state = lua.state();
683        match ffi::lua_type(state, idx) {
684            ffi::LUA_TSTRING => {
685                let mut size = 0;
686                let data = ffi::lua_tolstring(state, idx, &mut size);
687                Ok(slice::from_raw_parts(data as *const u8, size).into())
688            }
689            #[cfg(feature = "luau")]
690            ffi::LUA_TBUFFER => {
691                let mut size = 0;
692                let buf = ffi::lua_tobuffer(state, idx, &mut size);
693                mlua_assert!(!buf.is_null(), "invalid Luau buffer");
694                Ok(slice::from_raw_parts(buf as *const u8, size).into())
695            }
696            type_id => {
697                // Fallback to default
698                Self::from_lua(lua.stack_value(idx, Some(type_id)), lua.lua())
699            }
700        }
701    }
702}
703
704impl IntoLua for &BStr {
705    #[inline]
706    fn into_lua(self, lua: &Lua) -> Result<Value> {
707        Ok(Value::String(lua.create_string(self)?))
708    }
709}
710
711impl IntoLua for OsString {
712    #[inline]
713    fn into_lua(self, lua: &Lua) -> Result<Value> {
714        self.as_os_str().into_lua(lua)
715    }
716}
717
718impl FromLua for OsString {
719    #[inline]
720    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
721        let ty = value.type_name();
722        let bs = BString::from_lua(value, lua)?;
723        Vec::from(bs)
724            .into_os_string()
725            .map_err(|err| Error::FromLuaConversionError {
726                from: ty,
727                to: "OsString".into(),
728                message: Some(err.to_string()),
729            })
730    }
731}
732
733impl IntoLua for &OsStr {
734    #[inline]
735    fn into_lua(self, lua: &Lua) -> Result<Value> {
736        let s = <[u8]>::from_os_str(self).ok_or_else(|| Error::ToLuaConversionError {
737            from: "OsStr".into(),
738            to: "string",
739            message: Some("invalid utf-8 encoding".into()),
740        })?;
741        Ok(Value::String(lua.create_string(s)?))
742    }
743}
744
745impl IntoLua for PathBuf {
746    #[inline]
747    fn into_lua(self, lua: &Lua) -> Result<Value> {
748        self.as_os_str().into_lua(lua)
749    }
750}
751
752impl FromLua for PathBuf {
753    #[inline]
754    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
755        OsString::from_lua(value, lua).map(PathBuf::from)
756    }
757}
758
759impl IntoLua for &Path {
760    #[inline]
761    fn into_lua(self, lua: &Lua) -> Result<Value> {
762        self.as_os_str().into_lua(lua)
763    }
764}
765
766impl IntoLua for char {
767    #[inline]
768    fn into_lua(self, lua: &Lua) -> Result<Value> {
769        let mut char_bytes = [0; 4];
770        self.encode_utf8(&mut char_bytes);
771        Ok(Value::String(lua.create_string(&char_bytes[..self.len_utf8()])?))
772    }
773}
774
775impl FromLua for char {
776    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
777        let ty = value.type_name();
778        match value {
779            Value::Integer(i) => {
780                cast(i)
781                    .and_then(char::from_u32)
782                    .ok_or_else(|| Error::FromLuaConversionError {
783                        from: ty,
784                        to: "char".to_string(),
785                        message: Some("integer out of range when converting to char".to_string()),
786                    })
787            }
788            Value::String(s) => {
789                let str = s.to_str()?;
790                let mut str_iter = str.chars();
791                match (str_iter.next(), str_iter.next()) {
792                    (Some(char), None) => Ok(char),
793                    _ => Err(Error::FromLuaConversionError {
794                        from: ty,
795                        to: "char".to_string(),
796                        message: Some(
797                            "expected string to have exactly one char when converting to char".to_string(),
798                        ),
799                    }),
800                }
801            }
802            _ => Err(Error::FromLuaConversionError {
803                from: ty,
804                to: Self::type_name(),
805                message: Some("expected string or integer".to_string()),
806            }),
807        }
808    }
809}
810
811#[inline]
812unsafe fn push_bytes_into_stack<T>(this: T, lua: &RawLua) -> Result<()>
813where
814    T: IntoLua + AsRef<[u8]>,
815{
816    let bytes = this.as_ref();
817    if lua.unlikely_memory_error() && bytes.len() < (1 << 30) {
818        // Fast path: push directly into the Lua stack.
819        ffi::lua_pushlstring(lua.state(), bytes.as_ptr() as *const _, bytes.len());
820        return Ok(());
821    }
822    // Fallback to default
823    lua.push_value(&T::into_lua(this, lua.lua())?)
824}
825
826macro_rules! lua_convert_int {
827    ($x:ty) => {
828        impl IntoLua for $x {
829            #[inline]
830            fn into_lua(self, _: &Lua) -> Result<Value> {
831                Ok(cast(self)
832                    .map(Value::Integer)
833                    .unwrap_or_else(|| Value::Number(self as ffi::lua_Number)))
834            }
835
836            #[inline]
837            unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
838                match cast(self) {
839                    Some(i) => ffi::lua_pushinteger(lua.state(), i),
840                    None => ffi::lua_pushnumber(lua.state(), self as ffi::lua_Number),
841                }
842                Ok(())
843            }
844        }
845
846        impl FromLua for $x {
847            #[inline]
848            fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
849                let ty = value.type_name();
850                (match value {
851                    Value::Integer(i) => cast(i),
852                    Value::Number(n) => cast(n),
853                    _ => {
854                        if let Some(i) = lua.coerce_integer(value.clone())? {
855                            cast(i)
856                        } else {
857                            cast(
858                                lua.coerce_number(value)?
859                                    .ok_or_else(|| Error::FromLuaConversionError {
860                                        from: ty,
861                                        to: stringify!($x).to_string(),
862                                        message: Some(
863                                            "expected number or string coercible to number".to_string(),
864                                        ),
865                                    })?,
866                            )
867                        }
868                    }
869                })
870                .ok_or_else(|| Error::FromLuaConversionError {
871                    from: ty,
872                    to: stringify!($x).to_string(),
873                    message: Some("out of range".to_owned()),
874                })
875            }
876
877            unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
878                let state = lua.state();
879                let type_id = ffi::lua_type(state, idx);
880                if type_id == ffi::LUA_TNUMBER {
881                    let mut ok = 0;
882                    let i = ffi::lua_tointegerx(state, idx, &mut ok);
883                    if ok != 0 {
884                        return cast(i).ok_or_else(|| Error::FromLuaConversionError {
885                            from: "integer",
886                            to: stringify!($x).to_string(),
887                            message: Some("out of range".to_owned()),
888                        });
889                    }
890                }
891                // Fallback to default
892                Self::from_lua(lua.stack_value(idx, Some(type_id)), lua.lua())
893            }
894        }
895    };
896}
897
898lua_convert_int!(i8);
899lua_convert_int!(u8);
900lua_convert_int!(i16);
901lua_convert_int!(u16);
902lua_convert_int!(i32);
903lua_convert_int!(u32);
904lua_convert_int!(i64);
905lua_convert_int!(u64);
906lua_convert_int!(i128);
907lua_convert_int!(u128);
908lua_convert_int!(isize);
909lua_convert_int!(usize);
910
911macro_rules! lua_convert_float {
912    ($x:ty) => {
913        impl IntoLua for $x {
914            #[inline]
915            fn into_lua(self, _: &Lua) -> Result<Value> {
916                Ok(Value::Number(self as _))
917            }
918        }
919
920        impl FromLua for $x {
921            #[inline]
922            fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
923                let ty = value.type_name();
924                lua.coerce_number(value)?
925                    .map(|n| n as $x)
926                    .ok_or_else(|| Error::FromLuaConversionError {
927                        from: ty,
928                        to: stringify!($x).to_string(),
929                        message: Some("expected number or string coercible to number".to_string()),
930                    })
931            }
932
933            unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
934                let state = lua.state();
935                let type_id = ffi::lua_type(state, idx);
936                if type_id == ffi::LUA_TNUMBER {
937                    return Ok(ffi::lua_tonumber(state, idx) as _);
938                }
939                // Fallback to default
940                Self::from_lua(lua.stack_value(idx, Some(type_id)), lua.lua())
941            }
942        }
943    };
944}
945
946lua_convert_float!(f32);
947lua_convert_float!(f64);
948
949impl<T> IntoLua for &[T]
950where
951    T: IntoLua + Clone,
952{
953    #[inline]
954    fn into_lua(self, lua: &Lua) -> Result<Value> {
955        Ok(Value::Table(lua.create_sequence_from(self.iter().cloned())?))
956    }
957}
958
959impl<T, const N: usize> IntoLua for [T; N]
960where
961    T: IntoLua,
962{
963    #[inline]
964    fn into_lua(self, lua: &Lua) -> Result<Value> {
965        Ok(Value::Table(lua.create_sequence_from(self)?))
966    }
967}
968
969impl<T, const N: usize> FromLua for [T; N]
970where
971    T: FromLua,
972{
973    #[inline]
974    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
975        match value {
976            #[cfg(feature = "luau")]
977            #[rustfmt::skip]
978            Value::Vector(v) if N == crate::Vector::SIZE => unsafe {
979                use std::{mem, ptr};
980                let mut arr: [mem::MaybeUninit<T>; N] = mem::MaybeUninit::uninit().assume_init();
981                ptr::write(arr[0].as_mut_ptr() , T::from_lua(Value::Number(v.x() as _), _lua)?);
982                ptr::write(arr[1].as_mut_ptr(), T::from_lua(Value::Number(v.y() as _), _lua)?);
983                ptr::write(arr[2].as_mut_ptr(), T::from_lua(Value::Number(v.z() as _), _lua)?);
984                #[cfg(feature = "luau-vector4")]
985                ptr::write(arr[3].as_mut_ptr(), T::from_lua(Value::Number(v.w() as _), _lua)?);
986                Ok(mem::transmute_copy(&arr))
987            },
988            Value::Table(table) => {
989                let vec = table.sequence_values().collect::<Result<Vec<_>>>()?;
990                vec.try_into()
991                    .map_err(|vec: Vec<T>| Error::FromLuaConversionError {
992                        from: "table",
993                        to: Self::type_name(),
994                        message: Some(format!("expected table of length {N}, got {}", vec.len())),
995                    })
996            }
997            _ => Err(Error::FromLuaConversionError {
998                from: value.type_name(),
999                to: Self::type_name(),
1000                message: Some("expected table".to_string()),
1001            }),
1002        }
1003    }
1004}
1005
1006impl<T: IntoLua> IntoLua for Box<[T]> {
1007    #[inline]
1008    fn into_lua(self, lua: &Lua) -> Result<Value> {
1009        Ok(Value::Table(lua.create_sequence_from(self.into_vec())?))
1010    }
1011}
1012
1013impl<T: FromLua> FromLua for Box<[T]> {
1014    #[inline]
1015    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
1016        Ok(Vec::<T>::from_lua(value, lua)?.into_boxed_slice())
1017    }
1018}
1019
1020impl<T: IntoLua> IntoLua for Vec<T> {
1021    #[inline]
1022    fn into_lua(self, lua: &Lua) -> Result<Value> {
1023        Ok(Value::Table(lua.create_sequence_from(self)?))
1024    }
1025}
1026
1027impl<T: FromLua> FromLua for Vec<T> {
1028    #[inline]
1029    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
1030        match value {
1031            Value::Table(table) => table.sequence_values().collect(),
1032            _ => Err(Error::FromLuaConversionError {
1033                from: value.type_name(),
1034                to: Self::type_name(),
1035                message: Some("expected table".to_string()),
1036            }),
1037        }
1038    }
1039}
1040
1041impl<K: Eq + Hash + IntoLua, V: IntoLua, S: BuildHasher> IntoLua for HashMap<K, V, S> {
1042    #[inline]
1043    fn into_lua(self, lua: &Lua) -> Result<Value> {
1044        Ok(Value::Table(lua.create_table_from(self)?))
1045    }
1046}
1047
1048impl<K: Eq + Hash + FromLua, V: FromLua, S: BuildHasher + Default> FromLua for HashMap<K, V, S> {
1049    #[inline]
1050    fn from_lua(value: Value, _: &Lua) -> Result<Self> {
1051        if let Value::Table(table) = value {
1052            table.pairs().collect()
1053        } else {
1054            Err(Error::FromLuaConversionError {
1055                from: value.type_name(),
1056                to: Self::type_name(),
1057                message: Some("expected table".to_string()),
1058            })
1059        }
1060    }
1061}
1062
1063impl<K: Ord + IntoLua, V: IntoLua> IntoLua for BTreeMap<K, V> {
1064    #[inline]
1065    fn into_lua(self, lua: &Lua) -> Result<Value> {
1066        Ok(Value::Table(lua.create_table_from(self)?))
1067    }
1068}
1069
1070impl<K: Ord + FromLua, V: FromLua> FromLua for BTreeMap<K, V> {
1071    #[inline]
1072    fn from_lua(value: Value, _: &Lua) -> Result<Self> {
1073        if let Value::Table(table) = value {
1074            table.pairs().collect()
1075        } else {
1076            Err(Error::FromLuaConversionError {
1077                from: value.type_name(),
1078                to: Self::type_name(),
1079                message: Some("expected table".to_string()),
1080            })
1081        }
1082    }
1083}
1084
1085impl<T: Eq + Hash + IntoLua, S: BuildHasher> IntoLua for HashSet<T, S> {
1086    #[inline]
1087    fn into_lua(self, lua: &Lua) -> Result<Value> {
1088        Ok(Value::Table(
1089            lua.create_table_from(self.into_iter().map(|val| (val, true)))?,
1090        ))
1091    }
1092}
1093
1094impl<T: Eq + Hash + FromLua, S: BuildHasher + Default> FromLua for HashSet<T, S> {
1095    #[inline]
1096    fn from_lua(value: Value, _: &Lua) -> Result<Self> {
1097        match value {
1098            Value::Table(table) if table.raw_len() > 0 => table.sequence_values().collect(),
1099            Value::Table(table) => table.pairs::<T, Value>().map(|res| res.map(|(k, _)| k)).collect(),
1100            _ => Err(Error::FromLuaConversionError {
1101                from: value.type_name(),
1102                to: Self::type_name(),
1103                message: Some("expected table".to_string()),
1104            }),
1105        }
1106    }
1107}
1108
1109impl<T: Ord + IntoLua> IntoLua for BTreeSet<T> {
1110    #[inline]
1111    fn into_lua(self, lua: &Lua) -> Result<Value> {
1112        Ok(Value::Table(
1113            lua.create_table_from(self.into_iter().map(|val| (val, true)))?,
1114        ))
1115    }
1116}
1117
1118impl<T: Ord + FromLua> FromLua for BTreeSet<T> {
1119    #[inline]
1120    fn from_lua(value: Value, _: &Lua) -> Result<Self> {
1121        match value {
1122            Value::Table(table) if table.raw_len() > 0 => table.sequence_values().collect(),
1123            Value::Table(table) => table.pairs::<T, Value>().map(|res| res.map(|(k, _)| k)).collect(),
1124            _ => Err(Error::FromLuaConversionError {
1125                from: value.type_name(),
1126                to: Self::type_name(),
1127                message: Some("expected table".to_string()),
1128            }),
1129        }
1130    }
1131}
1132
1133impl<T: IntoLua> IntoLua for Option<T> {
1134    #[inline]
1135    fn into_lua(self, lua: &Lua) -> Result<Value> {
1136        match self {
1137            Some(val) => val.into_lua(lua),
1138            None => Ok(Nil),
1139        }
1140    }
1141
1142    #[inline]
1143    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
1144        match self {
1145            Some(val) => val.push_into_stack(lua)?,
1146            None => ffi::lua_pushnil(lua.state()),
1147        }
1148        Ok(())
1149    }
1150}
1151
1152impl<T: FromLua> FromLua for Option<T> {
1153    #[inline]
1154    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
1155        match value {
1156            Nil => Ok(None),
1157            value => Ok(Some(T::from_lua(value, lua)?)),
1158        }
1159    }
1160
1161    #[inline]
1162    unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
1163        match ffi::lua_type(lua.state(), idx) {
1164            ffi::LUA_TNIL => Ok(None),
1165            _ => Ok(Some(T::from_stack(idx, lua)?)),
1166        }
1167    }
1168}
1169
1170impl<L: IntoLua, R: IntoLua> IntoLua for Either<L, R> {
1171    #[inline]
1172    fn into_lua(self, lua: &Lua) -> Result<Value> {
1173        match self {
1174            Either::Left(l) => l.into_lua(lua),
1175            Either::Right(r) => r.into_lua(lua),
1176        }
1177    }
1178
1179    #[inline]
1180    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
1181        match self {
1182            Either::Left(l) => l.push_into_stack(lua),
1183            Either::Right(r) => r.push_into_stack(lua),
1184        }
1185    }
1186}
1187
1188impl<L: FromLua, R: FromLua> FromLua for Either<L, R> {
1189    #[inline]
1190    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
1191        let value_type_name = value.type_name();
1192        // Try the left type first
1193        match L::from_lua(value.clone(), lua) {
1194            Ok(l) => Ok(Either::Left(l)),
1195            // Try the right type
1196            Err(_) => match R::from_lua(value, lua).map(Either::Right) {
1197                Ok(r) => Ok(r),
1198                Err(_) => Err(Error::FromLuaConversionError {
1199                    from: value_type_name,
1200                    to: Self::type_name(),
1201                    message: None,
1202                }),
1203            },
1204        }
1205    }
1206
1207    #[inline]
1208    unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
1209        match L::from_stack(idx, lua) {
1210            Ok(l) => Ok(Either::Left(l)),
1211            Err(_) => match R::from_stack(idx, lua).map(Either::Right) {
1212                Ok(r) => Ok(r),
1213                Err(_) => {
1214                    let value_type_name =
1215                        CStr::from_ptr(ffi::lua_typename(lua.state(), ffi::lua_type(lua.state(), idx)));
1216                    Err(Error::FromLuaConversionError {
1217                        from: value_type_name.to_str().unwrap(),
1218                        to: Self::type_name(),
1219                        message: None,
1220                    })
1221                }
1222            },
1223        }
1224    }
1225}