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        Ok(Value::String(lua.create_string(self)?))
504    }
505
506    #[inline]
507    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
508        push_bytes_into_stack(self, lua)
509    }
510}
511
512impl FromLua for StdString {
513    #[inline]
514    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
515        let ty = value.type_name();
516        Ok(lua
517            .coerce_string(value)?
518            .ok_or_else(|| Error::FromLuaConversionError {
519                from: ty,
520                to: Self::type_name(),
521                message: Some("expected string or number".to_string()),
522            })?
523            .to_str()?
524            .to_owned())
525    }
526
527    #[inline]
528    unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
529        let state = lua.state();
530        let type_id = ffi::lua_type(state, idx);
531        if type_id == ffi::LUA_TSTRING {
532            let mut size = 0;
533            let data = ffi::lua_tolstring(state, idx, &mut size);
534            let bytes = slice::from_raw_parts(data as *const u8, size);
535            return str::from_utf8(bytes)
536                .map(|s| s.to_owned())
537                .map_err(|e| Error::FromLuaConversionError {
538                    from: "string",
539                    to: Self::type_name(),
540                    message: Some(e.to_string()),
541                });
542        }
543        // Fallback to default
544        Self::from_lua(lua.stack_value(idx, Some(type_id)), lua.lua())
545    }
546}
547
548impl IntoLua for &str {
549    #[inline]
550    fn into_lua(self, lua: &Lua) -> Result<Value> {
551        Ok(Value::String(lua.create_string(self)?))
552    }
553
554    #[inline]
555    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
556        push_bytes_into_stack(self, lua)
557    }
558}
559
560impl IntoLua for Cow<'_, str> {
561    #[inline]
562    fn into_lua(self, lua: &Lua) -> Result<Value> {
563        Ok(Value::String(lua.create_string(self.as_bytes())?))
564    }
565}
566
567impl IntoLua for Box<str> {
568    #[inline]
569    fn into_lua(self, lua: &Lua) -> Result<Value> {
570        Ok(Value::String(lua.create_string(&*self)?))
571    }
572}
573
574impl FromLua for Box<str> {
575    #[inline]
576    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
577        let ty = value.type_name();
578        Ok(lua
579            .coerce_string(value)?
580            .ok_or_else(|| Error::FromLuaConversionError {
581                from: ty,
582                to: Self::type_name(),
583                message: Some("expected string or number".to_string()),
584            })?
585            .to_str()?
586            .to_owned()
587            .into_boxed_str())
588    }
589}
590
591impl IntoLua for CString {
592    #[inline]
593    fn into_lua(self, lua: &Lua) -> Result<Value> {
594        Ok(Value::String(lua.create_string(self.as_bytes())?))
595    }
596}
597
598impl FromLua for CString {
599    #[inline]
600    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
601        let ty = value.type_name();
602        let string = lua
603            .coerce_string(value)?
604            .ok_or_else(|| Error::FromLuaConversionError {
605                from: ty,
606                to: Self::type_name(),
607                message: Some("expected string or number".to_string()),
608            })?;
609
610        match CStr::from_bytes_with_nul(&string.as_bytes_with_nul()) {
611            Ok(s) => Ok(s.into()),
612            Err(_) => Err(Error::FromLuaConversionError {
613                from: ty,
614                to: Self::type_name(),
615                message: Some("invalid C-style string".to_string()),
616            }),
617        }
618    }
619}
620
621impl IntoLua for &CStr {
622    #[inline]
623    fn into_lua(self, lua: &Lua) -> Result<Value> {
624        Ok(Value::String(lua.create_string(self.to_bytes())?))
625    }
626}
627
628impl IntoLua for Cow<'_, CStr> {
629    #[inline]
630    fn into_lua(self, lua: &Lua) -> Result<Value> {
631        Ok(Value::String(lua.create_string(self.to_bytes())?))
632    }
633}
634
635impl IntoLua for BString {
636    #[inline]
637    fn into_lua(self, lua: &Lua) -> Result<Value> {
638        Ok(Value::String(lua.create_string(self)?))
639    }
640}
641
642impl FromLua for BString {
643    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
644        let ty = value.type_name();
645        match value {
646            Value::String(s) => Ok((*s.as_bytes()).into()),
647            #[cfg(feature = "luau")]
648            Value::Buffer(buf) => Ok(buf.to_vec().into()),
649            _ => Ok((*lua
650                .coerce_string(value)?
651                .ok_or_else(|| Error::FromLuaConversionError {
652                    from: ty,
653                    to: Self::type_name(),
654                    message: Some("expected string or number".to_string()),
655                })?
656                .as_bytes())
657            .into()),
658        }
659    }
660
661    unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
662        let state = lua.state();
663        match ffi::lua_type(state, idx) {
664            ffi::LUA_TSTRING => {
665                let mut size = 0;
666                let data = ffi::lua_tolstring(state, idx, &mut size);
667                Ok(slice::from_raw_parts(data as *const u8, size).into())
668            }
669            #[cfg(feature = "luau")]
670            ffi::LUA_TBUFFER => {
671                let mut size = 0;
672                let buf = ffi::lua_tobuffer(state, idx, &mut size);
673                mlua_assert!(!buf.is_null(), "invalid Luau buffer");
674                Ok(slice::from_raw_parts(buf as *const u8, size).into())
675            }
676            type_id => {
677                // Fallback to default
678                Self::from_lua(lua.stack_value(idx, Some(type_id)), lua.lua())
679            }
680        }
681    }
682}
683
684impl IntoLua for &BStr {
685    #[inline]
686    fn into_lua(self, lua: &Lua) -> Result<Value> {
687        Ok(Value::String(lua.create_string(self)?))
688    }
689}
690
691impl IntoLua for OsString {
692    #[inline]
693    fn into_lua(self, lua: &Lua) -> Result<Value> {
694        self.as_os_str().into_lua(lua)
695    }
696}
697
698impl FromLua for OsString {
699    #[inline]
700    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
701        let ty = value.type_name();
702        let bs = BString::from_lua(value, lua)?;
703        Vec::from(bs)
704            .into_os_string()
705            .map_err(|err| Error::FromLuaConversionError {
706                from: ty,
707                to: "OsString".into(),
708                message: Some(err.to_string()),
709            })
710    }
711}
712
713impl IntoLua for &OsStr {
714    #[inline]
715    fn into_lua(self, lua: &Lua) -> Result<Value> {
716        let s = <[u8]>::from_os_str(self).ok_or_else(|| Error::ToLuaConversionError {
717            from: "OsStr".into(),
718            to: "string",
719            message: Some("invalid utf-8 encoding".into()),
720        })?;
721        Ok(Value::String(lua.create_string(s)?))
722    }
723}
724
725impl IntoLua for PathBuf {
726    #[inline]
727    fn into_lua(self, lua: &Lua) -> Result<Value> {
728        self.as_os_str().into_lua(lua)
729    }
730}
731
732impl FromLua for PathBuf {
733    #[inline]
734    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
735        OsString::from_lua(value, lua).map(PathBuf::from)
736    }
737}
738
739impl IntoLua for &Path {
740    #[inline]
741    fn into_lua(self, lua: &Lua) -> Result<Value> {
742        self.as_os_str().into_lua(lua)
743    }
744}
745
746impl IntoLua for char {
747    #[inline]
748    fn into_lua(self, lua: &Lua) -> Result<Value> {
749        let mut char_bytes = [0; 4];
750        self.encode_utf8(&mut char_bytes);
751        Ok(Value::String(lua.create_string(&char_bytes[..self.len_utf8()])?))
752    }
753}
754
755impl FromLua for char {
756    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
757        let ty = value.type_name();
758        match value {
759            Value::Integer(i) => {
760                cast(i)
761                    .and_then(char::from_u32)
762                    .ok_or_else(|| Error::FromLuaConversionError {
763                        from: ty,
764                        to: "char".to_string(),
765                        message: Some("integer out of range when converting to char".to_string()),
766                    })
767            }
768            Value::String(s) => {
769                let str = s.to_str()?;
770                let mut str_iter = str.chars();
771                match (str_iter.next(), str_iter.next()) {
772                    (Some(char), None) => Ok(char),
773                    _ => Err(Error::FromLuaConversionError {
774                        from: ty,
775                        to: "char".to_string(),
776                        message: Some(
777                            "expected string to have exactly one char when converting to char".to_string(),
778                        ),
779                    }),
780                }
781            }
782            _ => Err(Error::FromLuaConversionError {
783                from: ty,
784                to: Self::type_name(),
785                message: Some("expected string or integer".to_string()),
786            }),
787        }
788    }
789}
790
791#[inline]
792unsafe fn push_bytes_into_stack<T>(this: T, lua: &RawLua) -> Result<()>
793where
794    T: IntoLua + AsRef<[u8]>,
795{
796    let bytes = this.as_ref();
797    if lua.unlikely_memory_error() && bytes.len() < (1 << 30) {
798        // Fast path: push directly into the Lua stack.
799        ffi::lua_pushlstring(lua.state(), bytes.as_ptr() as *const _, bytes.len());
800        return Ok(());
801    }
802    // Fallback to default
803    lua.push_value(&T::into_lua(this, lua.lua())?)
804}
805
806macro_rules! lua_convert_int {
807    ($x:ty) => {
808        impl IntoLua for $x {
809            #[inline]
810            fn into_lua(self, _: &Lua) -> Result<Value> {
811                Ok(cast(self)
812                    .map(Value::Integer)
813                    .unwrap_or_else(|| Value::Number(self as ffi::lua_Number)))
814            }
815
816            #[inline]
817            unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
818                match cast(self) {
819                    Some(i) => ffi::lua_pushinteger(lua.state(), i),
820                    None => ffi::lua_pushnumber(lua.state(), self as ffi::lua_Number),
821                }
822                Ok(())
823            }
824        }
825
826        impl FromLua for $x {
827            #[inline]
828            fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
829                let ty = value.type_name();
830                (match value {
831                    Value::Integer(i) => cast(i),
832                    Value::Number(n) => cast(n),
833                    _ => {
834                        if let Some(i) = lua.coerce_integer(value.clone())? {
835                            cast(i)
836                        } else {
837                            cast(
838                                lua.coerce_number(value)?
839                                    .ok_or_else(|| Error::FromLuaConversionError {
840                                        from: ty,
841                                        to: stringify!($x).to_string(),
842                                        message: Some(
843                                            "expected number or string coercible to number".to_string(),
844                                        ),
845                                    })?,
846                            )
847                        }
848                    }
849                })
850                .ok_or_else(|| Error::FromLuaConversionError {
851                    from: ty,
852                    to: stringify!($x).to_string(),
853                    message: Some("out of range".to_owned()),
854                })
855            }
856
857            unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
858                let state = lua.state();
859                let type_id = ffi::lua_type(state, idx);
860                if type_id == ffi::LUA_TNUMBER {
861                    let mut ok = 0;
862                    let i = ffi::lua_tointegerx(state, idx, &mut ok);
863                    if ok != 0 {
864                        return cast(i).ok_or_else(|| Error::FromLuaConversionError {
865                            from: "integer",
866                            to: stringify!($x).to_string(),
867                            message: Some("out of range".to_owned()),
868                        });
869                    }
870                }
871                // Fallback to default
872                Self::from_lua(lua.stack_value(idx, Some(type_id)), lua.lua())
873            }
874        }
875    };
876}
877
878lua_convert_int!(i8);
879lua_convert_int!(u8);
880lua_convert_int!(i16);
881lua_convert_int!(u16);
882lua_convert_int!(i32);
883lua_convert_int!(u32);
884lua_convert_int!(i64);
885lua_convert_int!(u64);
886lua_convert_int!(i128);
887lua_convert_int!(u128);
888lua_convert_int!(isize);
889lua_convert_int!(usize);
890
891macro_rules! lua_convert_float {
892    ($x:ty) => {
893        impl IntoLua for $x {
894            #[inline]
895            fn into_lua(self, _: &Lua) -> Result<Value> {
896                Ok(Value::Number(self as _))
897            }
898        }
899
900        impl FromLua for $x {
901            #[inline]
902            fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
903                let ty = value.type_name();
904                lua.coerce_number(value)?
905                    .map(|n| n as $x)
906                    .ok_or_else(|| Error::FromLuaConversionError {
907                        from: ty,
908                        to: stringify!($x).to_string(),
909                        message: Some("expected number or string coercible to number".to_string()),
910                    })
911            }
912
913            unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
914                let state = lua.state();
915                let type_id = ffi::lua_type(state, idx);
916                if type_id == ffi::LUA_TNUMBER {
917                    return Ok(ffi::lua_tonumber(state, idx) as _);
918                }
919                // Fallback to default
920                Self::from_lua(lua.stack_value(idx, Some(type_id)), lua.lua())
921            }
922        }
923    };
924}
925
926lua_convert_float!(f32);
927lua_convert_float!(f64);
928
929impl<T> IntoLua for &[T]
930where
931    T: IntoLua + Clone,
932{
933    #[inline]
934    fn into_lua(self, lua: &Lua) -> Result<Value> {
935        Ok(Value::Table(lua.create_sequence_from(self.iter().cloned())?))
936    }
937}
938
939impl<T, const N: usize> IntoLua for [T; N]
940where
941    T: IntoLua,
942{
943    #[inline]
944    fn into_lua(self, lua: &Lua) -> Result<Value> {
945        Ok(Value::Table(lua.create_sequence_from(self)?))
946    }
947}
948
949impl<T, const N: usize> FromLua for [T; N]
950where
951    T: FromLua,
952{
953    #[inline]
954    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
955        match value {
956            #[cfg(feature = "luau")]
957            #[rustfmt::skip]
958            Value::Vector(v) if N == crate::Vector::SIZE => unsafe {
959                use std::{mem, ptr};
960                let mut arr: [mem::MaybeUninit<T>; N] = mem::MaybeUninit::uninit().assume_init();
961                ptr::write(arr[0].as_mut_ptr() , T::from_lua(Value::Number(v.x() as _), _lua)?);
962                ptr::write(arr[1].as_mut_ptr(), T::from_lua(Value::Number(v.y() as _), _lua)?);
963                ptr::write(arr[2].as_mut_ptr(), T::from_lua(Value::Number(v.z() as _), _lua)?);
964                #[cfg(feature = "luau-vector4")]
965                ptr::write(arr[3].as_mut_ptr(), T::from_lua(Value::Number(v.w() as _), _lua)?);
966                Ok(mem::transmute_copy(&arr))
967            },
968            Value::Table(table) => {
969                let vec = table.sequence_values().collect::<Result<Vec<_>>>()?;
970                vec.try_into()
971                    .map_err(|vec: Vec<T>| Error::FromLuaConversionError {
972                        from: "table",
973                        to: Self::type_name(),
974                        message: Some(format!("expected table of length {N}, got {}", vec.len())),
975                    })
976            }
977            _ => Err(Error::FromLuaConversionError {
978                from: value.type_name(),
979                to: Self::type_name(),
980                message: Some("expected table".to_string()),
981            }),
982        }
983    }
984}
985
986impl<T: IntoLua> IntoLua for Box<[T]> {
987    #[inline]
988    fn into_lua(self, lua: &Lua) -> Result<Value> {
989        Ok(Value::Table(lua.create_sequence_from(self.into_vec())?))
990    }
991}
992
993impl<T: FromLua> FromLua for Box<[T]> {
994    #[inline]
995    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
996        Ok(Vec::<T>::from_lua(value, lua)?.into_boxed_slice())
997    }
998}
999
1000impl<T: IntoLua> IntoLua for Vec<T> {
1001    #[inline]
1002    fn into_lua(self, lua: &Lua) -> Result<Value> {
1003        Ok(Value::Table(lua.create_sequence_from(self)?))
1004    }
1005}
1006
1007impl<T: FromLua> FromLua for Vec<T> {
1008    #[inline]
1009    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
1010        match value {
1011            Value::Table(table) => table.sequence_values().collect(),
1012            _ => Err(Error::FromLuaConversionError {
1013                from: value.type_name(),
1014                to: Self::type_name(),
1015                message: Some("expected table".to_string()),
1016            }),
1017        }
1018    }
1019}
1020
1021impl<K: Eq + Hash + IntoLua, V: IntoLua, S: BuildHasher> IntoLua for HashMap<K, V, S> {
1022    #[inline]
1023    fn into_lua(self, lua: &Lua) -> Result<Value> {
1024        Ok(Value::Table(lua.create_table_from(self)?))
1025    }
1026}
1027
1028impl<K: Eq + Hash + FromLua, V: FromLua, S: BuildHasher + Default> FromLua for HashMap<K, V, S> {
1029    #[inline]
1030    fn from_lua(value: Value, _: &Lua) -> Result<Self> {
1031        if let Value::Table(table) = value {
1032            table.pairs().collect()
1033        } else {
1034            Err(Error::FromLuaConversionError {
1035                from: value.type_name(),
1036                to: Self::type_name(),
1037                message: Some("expected table".to_string()),
1038            })
1039        }
1040    }
1041}
1042
1043impl<K: Ord + IntoLua, V: IntoLua> IntoLua for BTreeMap<K, V> {
1044    #[inline]
1045    fn into_lua(self, lua: &Lua) -> Result<Value> {
1046        Ok(Value::Table(lua.create_table_from(self)?))
1047    }
1048}
1049
1050impl<K: Ord + FromLua, V: FromLua> FromLua for BTreeMap<K, V> {
1051    #[inline]
1052    fn from_lua(value: Value, _: &Lua) -> Result<Self> {
1053        if let Value::Table(table) = value {
1054            table.pairs().collect()
1055        } else {
1056            Err(Error::FromLuaConversionError {
1057                from: value.type_name(),
1058                to: Self::type_name(),
1059                message: Some("expected table".to_string()),
1060            })
1061        }
1062    }
1063}
1064
1065impl<T: Eq + Hash + IntoLua, S: BuildHasher> IntoLua for HashSet<T, S> {
1066    #[inline]
1067    fn into_lua(self, lua: &Lua) -> Result<Value> {
1068        Ok(Value::Table(
1069            lua.create_table_from(self.into_iter().map(|val| (val, true)))?,
1070        ))
1071    }
1072}
1073
1074impl<T: Eq + Hash + FromLua, S: BuildHasher + Default> FromLua for HashSet<T, S> {
1075    #[inline]
1076    fn from_lua(value: Value, _: &Lua) -> Result<Self> {
1077        match value {
1078            Value::Table(table) if table.raw_len() > 0 => table.sequence_values().collect(),
1079            Value::Table(table) => table.pairs::<T, Value>().map(|res| res.map(|(k, _)| k)).collect(),
1080            _ => Err(Error::FromLuaConversionError {
1081                from: value.type_name(),
1082                to: Self::type_name(),
1083                message: Some("expected table".to_string()),
1084            }),
1085        }
1086    }
1087}
1088
1089impl<T: Ord + IntoLua> IntoLua for BTreeSet<T> {
1090    #[inline]
1091    fn into_lua(self, lua: &Lua) -> Result<Value> {
1092        Ok(Value::Table(
1093            lua.create_table_from(self.into_iter().map(|val| (val, true)))?,
1094        ))
1095    }
1096}
1097
1098impl<T: Ord + FromLua> FromLua for BTreeSet<T> {
1099    #[inline]
1100    fn from_lua(value: Value, _: &Lua) -> Result<Self> {
1101        match value {
1102            Value::Table(table) if table.raw_len() > 0 => table.sequence_values().collect(),
1103            Value::Table(table) => table.pairs::<T, Value>().map(|res| res.map(|(k, _)| k)).collect(),
1104            _ => Err(Error::FromLuaConversionError {
1105                from: value.type_name(),
1106                to: Self::type_name(),
1107                message: Some("expected table".to_string()),
1108            }),
1109        }
1110    }
1111}
1112
1113impl<T: IntoLua> IntoLua for Option<T> {
1114    #[inline]
1115    fn into_lua(self, lua: &Lua) -> Result<Value> {
1116        match self {
1117            Some(val) => val.into_lua(lua),
1118            None => Ok(Nil),
1119        }
1120    }
1121
1122    #[inline]
1123    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
1124        match self {
1125            Some(val) => val.push_into_stack(lua)?,
1126            None => ffi::lua_pushnil(lua.state()),
1127        }
1128        Ok(())
1129    }
1130}
1131
1132impl<T: FromLua> FromLua for Option<T> {
1133    #[inline]
1134    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
1135        match value {
1136            Nil => Ok(None),
1137            value => Ok(Some(T::from_lua(value, lua)?)),
1138        }
1139    }
1140
1141    #[inline]
1142    unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
1143        match ffi::lua_type(lua.state(), idx) {
1144            ffi::LUA_TNIL => Ok(None),
1145            _ => Ok(Some(T::from_stack(idx, lua)?)),
1146        }
1147    }
1148}
1149
1150impl<L: IntoLua, R: IntoLua> IntoLua for Either<L, R> {
1151    #[inline]
1152    fn into_lua(self, lua: &Lua) -> Result<Value> {
1153        match self {
1154            Either::Left(l) => l.into_lua(lua),
1155            Either::Right(r) => r.into_lua(lua),
1156        }
1157    }
1158
1159    #[inline]
1160    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
1161        match self {
1162            Either::Left(l) => l.push_into_stack(lua),
1163            Either::Right(r) => r.push_into_stack(lua),
1164        }
1165    }
1166}
1167
1168impl<L: FromLua, R: FromLua> FromLua for Either<L, R> {
1169    #[inline]
1170    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
1171        let value_type_name = value.type_name();
1172        // Try the left type first
1173        match L::from_lua(value.clone(), lua) {
1174            Ok(l) => Ok(Either::Left(l)),
1175            // Try the right type
1176            Err(_) => match R::from_lua(value, lua).map(Either::Right) {
1177                Ok(r) => Ok(r),
1178                Err(_) => Err(Error::FromLuaConversionError {
1179                    from: value_type_name,
1180                    to: Self::type_name(),
1181                    message: None,
1182                }),
1183            },
1184        }
1185    }
1186
1187    #[inline]
1188    unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
1189        match L::from_stack(idx, lua) {
1190            Ok(l) => Ok(Either::Left(l)),
1191            Err(_) => match R::from_stack(idx, lua).map(Either::Right) {
1192                Ok(r) => Ok(r),
1193                Err(_) => {
1194                    let value_type_name = CStr::from_ptr(ffi::luaL_typename(lua.state(), idx));
1195                    Err(Error::FromLuaConversionError {
1196                        from: value_type_name.to_str().unwrap(),
1197                        to: Self::type_name(),
1198                        message: None,
1199                    })
1200                }
1201            },
1202        }
1203    }
1204}