1use std::cmp::Ordering;
2use std::collections::HashSet;
3use std::os::raw::c_void;
4use std::string::String as StdString;
5use std::{fmt, ptr, str};
6
7use num_traits::FromPrimitive;
8
9use crate::error::{Error, Result};
10use crate::function::Function;
11use crate::string::{BorrowedStr, String};
12use crate::table::Table;
13use crate::thread::Thread;
14use crate::types::{Integer, LightUserData, Number, ValueRef};
15use crate::userdata::AnyUserData;
16use crate::util::{check_stack, StackGuard};
17
18#[cfg(feature = "serialize")]
19use {
20 crate::table::SerializableTable,
21 rustc_hash::FxHashSet,
22 serde::ser::{self, Serialize, Serializer},
23 std::{cell::RefCell, rc::Rc, result::Result as StdResult},
24};
25
26#[derive(Clone)]
32pub enum Value {
33 Nil,
35 Boolean(bool),
37 LightUserData(LightUserData),
39 Integer(Integer),
43 Number(Number),
45 #[cfg(any(feature = "luau", doc))]
47 #[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
48 Vector(crate::Vector),
49 String(String),
53 Table(Table),
55 Function(Function),
57 Thread(Thread),
59 UserData(AnyUserData),
63 #[cfg(any(feature = "luau", doc))]
65 #[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
66 Buffer(crate::Buffer),
67 Error(Box<Error>),
69 Other(#[doc(hidden)] ValueRef),
71}
72
73pub use self::Value::Nil;
74
75impl Value {
76 pub const NULL: Value = Value::LightUserData(LightUserData(ptr::null_mut()));
80
81 pub fn type_name(&self) -> &'static str {
83 match *self {
84 Value::Nil => "nil",
85 Value::Boolean(_) => "boolean",
86 Value::LightUserData(_) => "lightuserdata",
87 Value::Integer(_) => "integer",
88 Value::Number(_) => "number",
89 #[cfg(feature = "luau")]
90 Value::Vector(_) => "vector",
91 Value::String(_) => "string",
92 Value::Table(_) => "table",
93 Value::Function(_) => "function",
94 Value::Thread(_) => "thread",
95 Value::UserData(_) => "userdata",
96 #[cfg(feature = "luau")]
97 Value::Buffer(_) => "buffer",
98 Value::Error(_) => "error",
99 Value::Other(_) => "other",
100 }
101 }
102
103 pub fn equals(&self, other: &Self) -> Result<bool> {
114 match (self, other) {
115 (Value::Table(a), Value::Table(b)) => a.equals(b),
116 (Value::UserData(a), Value::UserData(b)) => a.equals(b),
117 (a, b) => Ok(a == b),
118 }
119 }
120
121 #[inline]
129 pub fn to_pointer(&self) -> *const c_void {
130 match self {
131 Value::String(String(vref)) => {
132 let lua = vref.lua.lock();
135 unsafe { ffi::lua_tostring(lua.ref_thread(), vref.index) as *const c_void }
136 }
137 Value::LightUserData(ud) => ud.0,
138 Value::Table(Table(vref))
139 | Value::Function(Function(vref))
140 | Value::Thread(Thread(vref, ..))
141 | Value::UserData(AnyUserData(vref))
142 | Value::Other(vref) => vref.to_pointer(),
143 #[cfg(feature = "luau")]
144 Value::Buffer(crate::Buffer(vref)) => vref.to_pointer(),
145 _ => ptr::null(),
146 }
147 }
148
149 pub fn to_string(&self) -> Result<StdString> {
154 unsafe fn invoke_to_string(vref: &ValueRef) -> Result<StdString> {
155 let lua = vref.lua.lock();
156 let state = lua.state();
157 let _guard = StackGuard::new(state);
158 check_stack(state, 3)?;
159
160 lua.push_ref(vref);
161 protect_lua!(state, 1, 1, fn(state) {
162 ffi::luaL_tolstring(state, -1, ptr::null_mut());
163 })?;
164 Ok(String(lua.pop_ref()).to_str()?.to_string())
165 }
166
167 match self {
168 Value::Nil => Ok("nil".to_string()),
169 Value::Boolean(b) => Ok(b.to_string()),
170 Value::LightUserData(ud) if ud.0.is_null() => Ok("null".to_string()),
171 Value::LightUserData(ud) => Ok(format!("lightuserdata: {:p}", ud.0)),
172 Value::Integer(i) => Ok(i.to_string()),
173 Value::Number(n) => Ok(n.to_string()),
174 #[cfg(feature = "luau")]
175 Value::Vector(v) => Ok(v.to_string()),
176 Value::String(s) => Ok(s.to_str()?.to_string()),
177 Value::Table(Table(vref))
178 | Value::Function(Function(vref))
179 | Value::Thread(Thread(vref, ..))
180 | Value::UserData(AnyUserData(vref))
181 | Value::Other(vref) => unsafe { invoke_to_string(vref) },
182 #[cfg(feature = "luau")]
183 Value::Buffer(crate::Buffer(vref)) => unsafe { invoke_to_string(vref) },
184 Value::Error(err) => Ok(err.to_string()),
185 }
186 }
187
188 #[inline]
190 pub fn is_nil(&self) -> bool {
191 self == &Nil
192 }
193
194 #[inline]
198 pub fn is_null(&self) -> bool {
199 self == &Self::NULL
200 }
201
202 #[inline]
204 pub fn is_boolean(&self) -> bool {
205 self.as_boolean().is_some()
206 }
207
208 #[inline]
212 pub fn as_boolean(&self) -> Option<bool> {
213 match *self {
214 Value::Boolean(b) => Some(b),
215 _ => None,
216 }
217 }
218
219 #[inline]
221 pub fn is_light_userdata(&self) -> bool {
222 self.as_light_userdata().is_some()
223 }
224
225 #[inline]
229 pub fn as_light_userdata(&self) -> Option<LightUserData> {
230 match *self {
231 Value::LightUserData(l) => Some(l),
232 _ => None,
233 }
234 }
235
236 #[inline]
238 pub fn is_integer(&self) -> bool {
239 self.as_integer().is_some()
240 }
241
242 #[inline]
246 pub fn as_integer(&self) -> Option<Integer> {
247 match *self {
248 Value::Integer(i) => Some(i),
249 _ => None,
250 }
251 }
252
253 #[inline]
257 pub fn as_i32(&self) -> Option<i32> {
258 #[allow(clippy::useless_conversion)]
259 self.as_integer().and_then(|i| i32::try_from(i).ok())
260 }
261
262 #[inline]
266 pub fn as_u32(&self) -> Option<u32> {
267 self.as_integer().and_then(|i| u32::try_from(i).ok())
268 }
269
270 #[inline]
274 pub fn as_i64(&self) -> Option<i64> {
275 self.as_integer().map(i64::from)
276 }
277
278 #[inline]
282 pub fn as_u64(&self) -> Option<u64> {
283 self.as_integer().and_then(|i| u64::try_from(i).ok())
284 }
285
286 #[inline]
290 pub fn as_isize(&self) -> Option<isize> {
291 self.as_integer().and_then(|i| isize::try_from(i).ok())
292 }
293
294 #[inline]
298 pub fn as_usize(&self) -> Option<usize> {
299 self.as_integer().and_then(|i| usize::try_from(i).ok())
300 }
301
302 #[inline]
304 pub fn is_number(&self) -> bool {
305 self.as_number().is_some()
306 }
307
308 #[inline]
312 pub fn as_number(&self) -> Option<Number> {
313 match *self {
314 Value::Number(n) => Some(n),
315 _ => None,
316 }
317 }
318
319 #[inline]
323 pub fn as_f32(&self) -> Option<f32> {
324 self.as_number().and_then(f32::from_f64)
325 }
326
327 #[inline]
331 pub fn as_f64(&self) -> Option<f64> {
332 self.as_number()
333 }
334
335 #[inline]
337 pub fn is_string(&self) -> bool {
338 self.as_string().is_some()
339 }
340
341 #[inline]
345 pub fn as_string(&self) -> Option<&String> {
346 match self {
347 Value::String(s) => Some(s),
348 _ => None,
349 }
350 }
351
352 #[inline]
357 pub fn as_str(&self) -> Option<BorrowedStr> {
358 self.as_string().and_then(|s| s.to_str().ok())
359 }
360
361 #[inline]
365 pub fn as_string_lossy(&self) -> Option<StdString> {
366 self.as_string().map(|s| s.to_string_lossy())
367 }
368
369 #[inline]
371 pub fn is_table(&self) -> bool {
372 self.as_table().is_some()
373 }
374
375 #[inline]
379 pub fn as_table(&self) -> Option<&Table> {
380 match self {
381 Value::Table(t) => Some(t),
382 _ => None,
383 }
384 }
385
386 #[inline]
388 pub fn is_thread(&self) -> bool {
389 self.as_thread().is_some()
390 }
391
392 #[inline]
396 pub fn as_thread(&self) -> Option<&Thread> {
397 match self {
398 Value::Thread(t) => Some(t),
399 _ => None,
400 }
401 }
402
403 #[inline]
405 pub fn is_function(&self) -> bool {
406 self.as_function().is_some()
407 }
408
409 #[inline]
413 pub fn as_function(&self) -> Option<&Function> {
414 match self {
415 Value::Function(f) => Some(f),
416 _ => None,
417 }
418 }
419
420 #[inline]
422 pub fn is_userdata(&self) -> bool {
423 self.as_userdata().is_some()
424 }
425
426 #[inline]
430 pub fn as_userdata(&self) -> Option<&AnyUserData> {
431 match self {
432 Value::UserData(ud) => Some(ud),
433 _ => None,
434 }
435 }
436
437 #[cfg(any(feature = "luau", doc))]
443 #[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
444 #[inline]
445 pub fn as_buffer(&self) -> Option<&crate::Buffer> {
446 match self {
447 Value::Buffer(b) => Some(b),
448 _ => None,
449 }
450 }
451
452 #[cfg(any(feature = "luau", doc))]
456 #[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
457 #[inline]
458 pub fn is_buffer(&self) -> bool {
459 self.as_buffer().is_some()
460 }
461
462 #[inline]
464 pub fn is_error(&self) -> bool {
465 self.as_error().is_some()
466 }
467
468 pub fn as_error(&self) -> Option<&Error> {
472 match self {
473 Value::Error(e) => Some(e),
474 _ => None,
475 }
476 }
477
478 #[cfg(feature = "serialize")]
482 #[cfg_attr(docsrs, doc(cfg(feature = "serialize")))]
483 #[doc(hidden)]
484 pub fn to_serializable(&self) -> SerializableValue {
485 SerializableValue::new(self, Default::default(), None)
486 }
487
488 pub(crate) fn sort_cmp(&self, other: &Self) -> Ordering {
491 fn cmp_num(a: Number, b: Number) -> Ordering {
492 match (a, b) {
493 _ if a < b => Ordering::Less,
494 _ if a > b => Ordering::Greater,
495 _ => Ordering::Equal,
496 }
497 }
498
499 match (self, other) {
500 (Value::Nil, Value::Nil) => Ordering::Equal,
502 (Value::Nil, _) => Ordering::Less,
503 (_, Value::Nil) => Ordering::Greater,
504 (Value::LightUserData(ud1), Value::LightUserData(ud2)) if ud1 == ud2 => Ordering::Equal,
506 (Value::LightUserData(ud1), _) if ud1.0.is_null() => Ordering::Less,
507 (_, Value::LightUserData(ud2)) if ud2.0.is_null() => Ordering::Greater,
508 (Value::Boolean(a), Value::Boolean(b)) => a.cmp(b),
510 (Value::Boolean(_), _) => Ordering::Less,
511 (_, Value::Boolean(_)) => Ordering::Greater,
512 (Value::Integer(a), Value::Integer(b)) => a.cmp(b),
514 (Value::Integer(a), Value::Number(b)) => cmp_num(*a as Number, *b),
515 (Value::Number(a), Value::Integer(b)) => cmp_num(*a, *b as Number),
516 (Value::Number(a), Value::Number(b)) => cmp_num(*a, *b),
517 (Value::Integer(_) | Value::Number(_), _) => Ordering::Less,
518 (_, Value::Integer(_) | Value::Number(_)) => Ordering::Greater,
519 #[cfg(feature = "luau")]
521 (Value::Vector(a), Value::Vector(b)) => a.partial_cmp(b).unwrap_or(Ordering::Equal),
522 (Value::String(a), Value::String(b)) => a.as_bytes().cmp(&b.as_bytes()),
524 (Value::String(_), _) => Ordering::Less,
525 (_, Value::String(_)) => Ordering::Greater,
526 (a, b) => a.to_pointer().cmp(&b.to_pointer()),
528 }
529 }
530
531 pub(crate) fn fmt_pretty(
532 &self,
533 fmt: &mut fmt::Formatter,
534 recursive: bool,
535 ident: usize,
536 visited: &mut HashSet<*const c_void>,
537 ) -> fmt::Result {
538 match self {
539 Value::Nil => write!(fmt, "nil"),
540 Value::Boolean(b) => write!(fmt, "{b}"),
541 Value::LightUserData(ud) if ud.0.is_null() => write!(fmt, "null"),
542 Value::LightUserData(ud) => write!(fmt, "lightuserdata: {:?}", ud.0),
543 Value::Integer(i) => write!(fmt, "{i}"),
544 Value::Number(n) => write!(fmt, "{n}"),
545 #[cfg(feature = "luau")]
546 Value::Vector(v) => write!(fmt, "{v}"),
547 Value::String(s) => write!(fmt, "{s:?}"),
548 Value::Table(t) if recursive && !visited.contains(&t.to_pointer()) => {
549 t.fmt_pretty(fmt, ident, visited)
550 }
551 t @ Value::Table(_) => write!(fmt, "table: {:?}", t.to_pointer()),
552 f @ Value::Function(_) => write!(fmt, "function: {:?}", f.to_pointer()),
553 t @ Value::Thread(_) => write!(fmt, "thread: {:?}", t.to_pointer()),
554 u @ Value::UserData(ud) => {
555 let name = ud.type_name().ok().flatten();
557 let s = name
558 .map(|name| format!("{name}: {:?}", u.to_pointer()))
559 .or_else(|| u.to_string().ok())
560 .unwrap_or_else(|| format!("userdata: {:?}", u.to_pointer()));
561 write!(fmt, "{s}")
562 }
563 #[cfg(feature = "luau")]
564 buf @ Value::Buffer(_) => write!(fmt, "buffer: {:?}", buf.to_pointer()),
565 Value::Error(e) if recursive => write!(fmt, "{e:?}"),
566 Value::Error(_) => write!(fmt, "error"),
567 Value::Other(v) => write!(fmt, "other: {:?}", v.to_pointer()),
568 }
569 }
570}
571
572impl Default for Value {
573 fn default() -> Self {
574 Self::Nil
575 }
576}
577
578impl fmt::Debug for Value {
579 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
580 if fmt.alternate() {
581 return self.fmt_pretty(fmt, true, 0, &mut HashSet::new());
582 }
583
584 match self {
585 Value::Nil => write!(fmt, "Nil"),
586 Value::Boolean(b) => write!(fmt, "Boolean({b})"),
587 Value::LightUserData(ud) => write!(fmt, "{ud:?}"),
588 Value::Integer(i) => write!(fmt, "Integer({i})"),
589 Value::Number(n) => write!(fmt, "Number({n})"),
590 #[cfg(feature = "luau")]
591 Value::Vector(v) => write!(fmt, "{v:?}"),
592 Value::String(s) => write!(fmt, "String({s:?})"),
593 Value::Table(t) => write!(fmt, "{t:?}"),
594 Value::Function(f) => write!(fmt, "{f:?}"),
595 Value::Thread(t) => write!(fmt, "{t:?}"),
596 Value::UserData(ud) => write!(fmt, "{ud:?}"),
597 #[cfg(feature = "luau")]
598 Value::Buffer(buf) => write!(fmt, "{buf:?}"),
599 Value::Error(e) => write!(fmt, "Error({e:?})"),
600 Value::Other(v) => write!(fmt, "Other({v:?})"),
601 }
602 }
603}
604
605impl PartialEq for Value {
606 fn eq(&self, other: &Self) -> bool {
607 match (self, other) {
608 (Value::Nil, Value::Nil) => true,
609 (Value::Boolean(a), Value::Boolean(b)) => a == b,
610 (Value::LightUserData(a), Value::LightUserData(b)) => a == b,
611 (Value::Integer(a), Value::Integer(b)) => *a == *b,
612 (Value::Integer(a), Value::Number(b)) => *a as Number == *b,
613 (Value::Number(a), Value::Integer(b)) => *a == *b as Number,
614 (Value::Number(a), Value::Number(b)) => *a == *b,
615 #[cfg(feature = "luau")]
616 (Value::Vector(v1), Value::Vector(v2)) => v1 == v2,
617 (Value::String(a), Value::String(b)) => a == b,
618 (Value::Table(a), Value::Table(b)) => a == b,
619 (Value::Function(a), Value::Function(b)) => a == b,
620 (Value::Thread(a), Value::Thread(b)) => a == b,
621 (Value::UserData(a), Value::UserData(b)) => a == b,
622 #[cfg(feature = "luau")]
623 (Value::Buffer(a), Value::Buffer(b)) => a == b,
624 _ => false,
625 }
626 }
627}
628
629#[cfg(feature = "serialize")]
631#[cfg_attr(docsrs, doc(cfg(feature = "serialize")))]
632pub struct SerializableValue<'a> {
633 value: &'a Value,
634 options: crate::serde::de::Options,
635 visited: Option<Rc<RefCell<FxHashSet<*const c_void>>>>,
637}
638
639#[cfg(feature = "serialize")]
640impl Serialize for Value {
641 #[inline]
642 fn serialize<S: Serializer>(&self, serializer: S) -> StdResult<S::Ok, S::Error> {
643 SerializableValue::new(self, Default::default(), None).serialize(serializer)
644 }
645}
646
647#[cfg(feature = "serialize")]
648impl<'a> SerializableValue<'a> {
649 #[inline]
650 pub(crate) fn new(
651 value: &'a Value,
652 options: crate::serde::de::Options,
653 visited: Option<&Rc<RefCell<FxHashSet<*const c_void>>>>,
654 ) -> Self {
655 if let Value::Table(_) = value {
656 return Self {
657 value,
658 options,
659 visited: visited.cloned().or_else(|| Some(Default::default())),
661 };
662 }
663 Self {
664 value,
665 options,
666 visited: None,
667 }
668 }
669
670 #[must_use]
676 pub const fn deny_unsupported_types(mut self, enabled: bool) -> Self {
677 self.options.deny_unsupported_types = enabled;
678 self
679 }
680
681 #[must_use]
687 pub const fn deny_recursive_tables(mut self, enabled: bool) -> Self {
688 self.options.deny_recursive_tables = enabled;
689 self
690 }
691
692 #[must_use]
696 pub const fn sort_keys(mut self, enabled: bool) -> Self {
697 self.options.sort_keys = enabled;
698 self
699 }
700
701 #[must_use]
705 pub const fn encode_empty_tables_as_array(mut self, enabled: bool) -> Self {
706 self.options.encode_empty_tables_as_array = enabled;
707 self
708 }
709}
710
711#[cfg(feature = "serialize")]
712impl Serialize for SerializableValue<'_> {
713 fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>
714 where
715 S: Serializer,
716 {
717 match self.value {
718 Value::Nil => serializer.serialize_unit(),
719 Value::Boolean(b) => serializer.serialize_bool(*b),
720 #[allow(clippy::useless_conversion)]
721 Value::Integer(i) => serializer.serialize_i64((*i).into()),
722 Value::Number(n) => serializer.serialize_f64(*n),
723 #[cfg(feature = "luau")]
724 Value::Vector(v) => v.serialize(serializer),
725 Value::String(s) => s.serialize(serializer),
726 Value::Table(t) => {
727 let visited = self.visited.as_ref().unwrap().clone();
728 SerializableTable::new(t, self.options, visited).serialize(serializer)
729 }
730 Value::LightUserData(ud) if ud.0.is_null() => serializer.serialize_none(),
731 Value::UserData(ud) if ud.is_serializable() || self.options.deny_unsupported_types => {
732 ud.serialize(serializer)
733 }
734 #[cfg(feature = "luau")]
735 Value::Buffer(buf) => buf.serialize(serializer),
736 Value::Function(_)
737 | Value::Thread(_)
738 | Value::UserData(_)
739 | Value::LightUserData(_)
740 | Value::Error(_)
741 | Value::Other(_) => {
742 if self.options.deny_unsupported_types {
743 let msg = format!("cannot serialize <{}>", self.value.type_name());
744 Err(ser::Error::custom(msg))
745 } else {
746 serializer.serialize_unit()
747 }
748 }
749 }
750 }
751}
752
753#[cfg(test)]
754mod assertions {
755 use super::*;
756
757 #[cfg(not(feature = "send"))]
758 static_assertions::assert_not_impl_any!(Value: Send);
759 #[cfg(feature = "send")]
760 static_assertions::assert_impl_all!(Value: Send, Sync);
761}