rhai/src/dynamic.rs

1830 lines
65 KiB
Rust
Raw Normal View History

2020-11-20 09:52:28 +01:00
//! Helper module which defines the [`Any`] trait to to allow dynamic value handling.
2020-03-08 12:54:02 +01:00
2020-11-16 16:10:14 +01:00
use crate::fn_native::SendSync;
use crate::r#unsafe::{unsafe_cast_box, unsafe_try_cast};
use crate::{FnPtr, ImmutableString, SmartString, INT};
2021-04-17 09:15:54 +02:00
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{
2020-04-12 17:00:06 +02:00
any::{type_name, Any, TypeId},
2020-05-15 15:40:54 +02:00
fmt,
2020-11-12 14:53:26 +01:00
hash::{Hash, Hasher},
ops::{Deref, DerefMut},
2020-03-10 03:07:44 +01:00
};
2020-11-16 16:10:14 +01:00
#[cfg(not(feature = "no_float"))]
use crate::{ast::FloatWrapper, FLOAT};
2020-11-16 16:10:14 +01:00
2021-02-13 13:57:56 +01:00
#[cfg(feature = "decimal")]
use rust_decimal::Decimal;
2020-11-16 16:10:14 +01:00
#[cfg(not(feature = "no_index"))]
use crate::Array;
#[cfg(not(feature = "no_object"))]
use crate::Map;
2017-12-20 12:16:14 +01:00
#[cfg(not(feature = "no_std"))]
2021-02-19 08:50:48 +01:00
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
2021-04-17 09:15:54 +02:00
use std::time::Instant;
2021-02-13 13:57:56 +01:00
use fmt::Debug;
2020-06-17 10:50:57 +02:00
#[cfg(not(feature = "no_std"))]
2021-02-19 08:50:48 +01:00
#[cfg(any(target_arch = "wasm32", target_arch = "wasm64"))]
2020-06-17 10:50:57 +02:00
use instant::Instant;
mod private {
use crate::fn_native::SendSync;
2021-04-17 09:15:54 +02:00
use std::any::Any;
2020-07-25 10:09:13 +02:00
/// A sealed trait that prevents other crates from implementing [`Variant`].
pub trait Sealed {}
impl<T: Any + Clone + SendSync> Sealed for T {}
}
2021-03-05 07:18:36 +01:00
/// _(INTERNALS)_ Trait to represent any type.
/// Exported under the `internals` feature only.
///
/// This trait is sealed and cannot be implemented.
2020-04-03 13:42:01 +02:00
///
2020-11-20 09:52:28 +01:00
/// Currently, [`Variant`] is not [`Send`] nor [`Sync`], so it can practically be any type.
2020-11-25 02:36:06 +01:00
/// Turn on the `sync` feature to restrict it to only types that implement [`Send`] `+` [`Sync`].
2020-04-12 17:00:06 +02:00
#[cfg(not(feature = "sync"))]
pub trait Variant: Any + private::Sealed {
2020-11-20 09:52:28 +01:00
/// Convert this [`Variant`] trait object to [`&dyn Any`][Any].
2020-04-12 17:00:06 +02:00
fn as_any(&self) -> &dyn Any;
2020-11-20 09:52:28 +01:00
/// Convert this [`Variant`] trait object to [`&mut dyn Any`][Any].
2020-04-12 17:00:06 +02:00
fn as_mut_any(&mut self) -> &mut dyn Any;
2017-12-20 12:16:14 +01:00
2020-11-20 09:52:28 +01:00
/// Convert this [`Variant`] trait object to an [`Any`] trait object.
fn as_box_any(self: Box<Self>) -> Box<dyn Any>;
2020-03-04 15:00:01 +01:00
/// Get the name of this type.
2020-03-03 09:24:03 +01:00
fn type_name(&self) -> &'static str;
2019-09-30 19:57:21 +02:00
2020-11-20 09:52:28 +01:00
/// Convert into [`Dynamic`].
2020-04-12 17:00:06 +02:00
fn into_dynamic(self) -> Dynamic;
2020-11-20 09:52:28 +01:00
/// Clone into [`Dynamic`].
2020-04-12 17:00:06 +02:00
fn clone_into_dynamic(&self) -> Dynamic;
2017-12-20 12:16:14 +01:00
}
2021-03-05 07:18:36 +01:00
/// _(INTERNALS)_ Trait to represent any type.
/// Exported under the `internals` feature only.
///
/// This trait is sealed and cannot be implemented.
2020-04-12 17:00:06 +02:00
#[cfg(feature = "sync")]
pub trait Variant: Any + Send + Sync + private::Sealed {
2020-11-20 09:52:28 +01:00
/// Convert this [`Variant`] trait object to [`&dyn Any`][Any].
2020-04-12 17:00:06 +02:00
fn as_any(&self) -> &dyn Any;
2020-11-20 09:52:28 +01:00
/// Convert this [`Variant`] trait object to [`&mut dyn Any`][Any].
2020-04-12 17:00:06 +02:00
fn as_mut_any(&mut self) -> &mut dyn Any;
2020-11-20 09:52:28 +01:00
/// Convert this [`Variant`] trait object to an [`Any`] trait object.
2020-05-12 10:32:22 +02:00
fn as_box_any(self: Box<Self>) -> Box<dyn Any>;
/// Get the name of this type.
fn type_name(&self) -> &'static str;
2020-11-20 09:52:28 +01:00
/// Convert into [`Dynamic`].
2020-04-12 17:00:06 +02:00
fn into_dynamic(self) -> Dynamic;
2020-11-20 09:52:28 +01:00
/// Clone into [`Dynamic`].
2020-04-12 17:00:06 +02:00
fn clone_into_dynamic(&self) -> Dynamic;
}
impl<T: Any + Clone + SendSync> Variant for T {
2020-12-29 03:41:20 +01:00
#[inline(always)]
2020-04-12 17:00:06 +02:00
fn as_any(&self) -> &dyn Any {
2020-06-23 13:24:26 +02:00
self
2020-04-12 17:00:06 +02:00
}
2020-12-29 03:41:20 +01:00
#[inline(always)]
2020-04-12 17:00:06 +02:00
fn as_mut_any(&mut self) -> &mut dyn Any {
2020-06-23 13:24:26 +02:00
self
2017-12-20 12:16:14 +01:00
}
2020-12-29 03:41:20 +01:00
#[inline(always)]
fn as_box_any(self: Box<Self>) -> Box<dyn Any> {
2020-06-23 13:24:26 +02:00
self
}
2020-12-29 03:41:20 +01:00
#[inline(always)]
2020-03-03 09:24:03 +01:00
fn type_name(&self) -> &'static str {
type_name::<T>()
2019-09-30 19:57:21 +02:00
}
2020-12-29 03:41:20 +01:00
#[inline(always)]
2020-04-12 17:00:06 +02:00
fn into_dynamic(self) -> Dynamic {
Dynamic::from(self)
}
2020-12-29 03:41:20 +01:00
#[inline(always)]
2020-04-12 17:00:06 +02:00
fn clone_into_dynamic(&self) -> Dynamic {
Dynamic::from(self.clone())
2017-12-20 12:16:14 +01:00
}
2019-09-18 12:21:07 +02:00
}
2017-12-20 12:16:14 +01:00
2020-04-12 17:00:06 +02:00
impl dyn Variant {
2020-11-20 09:52:28 +01:00
/// Is this [`Variant`] a specific type?
2020-08-08 05:46:30 +02:00
#[inline(always)]
pub fn is<T: Any>(&self) -> bool {
2020-04-12 17:00:06 +02:00
TypeId::of::<T>() == self.type_id()
2017-12-20 12:16:14 +01:00
}
2020-04-12 17:00:06 +02:00
}
/// Modes of access.
2020-12-08 15:47:38 +01:00
#[derive(Debug, Eq, PartialEq, Hash, Copy, Clone)]
pub enum AccessMode {
/// Mutable.
ReadWrite,
/// Immutable.
ReadOnly,
2020-12-08 15:47:38 +01:00
}
2020-05-15 15:40:54 +02:00
/// Dynamic type containing any value.
2020-04-12 17:00:06 +02:00
pub struct Dynamic(pub(crate) Union);
2020-11-20 09:52:28 +01:00
/// Internal [`Dynamic`] representation.
2020-05-09 18:19:13 +02:00
///
/// Most variants are boxed to reduce the size.
2020-04-12 17:00:06 +02:00
pub enum Union {
2021-02-13 16:01:26 +01:00
/// The Unit value - ().
Unit((), AccessMode),
2021-02-13 16:01:26 +01:00
/// A boolean value.
Bool(bool, AccessMode),
2021-02-13 16:01:26 +01:00
/// An [`ImmutableString`] value.
Str(ImmutableString, AccessMode),
2021-02-13 16:01:26 +01:00
/// A character value.
Char(char, AccessMode),
2021-02-13 16:01:26 +01:00
/// An integer value.
Int(INT, AccessMode),
2021-02-13 16:01:26 +01:00
/// A floating-point value.
2020-04-12 17:00:06 +02:00
#[cfg(not(feature = "no_float"))]
2021-04-06 17:18:41 +02:00
Float(FloatWrapper<FLOAT>, AccessMode),
2021-02-13 16:01:26 +01:00
/// A fixed-precision decimal value.
2021-02-13 13:57:56 +01:00
#[cfg(feature = "decimal")]
Decimal(Box<Decimal>, AccessMode),
2021-02-13 16:01:26 +01:00
/// An array value.
#[cfg(not(feature = "no_index"))]
Array(Box<Array>, AccessMode),
2021-02-13 16:01:26 +01:00
/// An object map value.
#[cfg(not(feature = "no_object"))]
Map(Box<Map>, AccessMode),
2021-02-13 16:01:26 +01:00
/// A function pointer.
FnPtr(Box<FnPtr>, AccessMode),
2021-02-13 16:01:26 +01:00
/// A timestamp value.
2020-09-27 16:15:35 +02:00
#[cfg(not(feature = "no_std"))]
TimeStamp(Box<Instant>, AccessMode),
2020-08-08 10:24:10 +02:00
2021-02-13 16:01:26 +01:00
/// Any type as a trait object.
Variant(Box<Box<dyn Variant>>, AccessMode),
2020-08-08 10:24:10 +02:00
2021-02-13 16:01:26 +01:00
/// A _shared_ value of any type.
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
Shared(crate::Shared<crate::Locked<Dynamic>>, AccessMode),
}
2020-11-20 09:52:28 +01:00
/// Underlying [`Variant`] read guard for [`Dynamic`].
///
/// This data structure provides transparent interoperability between
2020-11-20 09:52:28 +01:00
/// normal [`Dynamic`] and shared [`Dynamic`] values.
#[derive(Debug)]
2021-04-19 12:08:29 +02:00
pub struct DynamicReadLock<'d, T: Clone>(DynamicReadLockInner<'d, T>);
2020-11-20 09:52:28 +01:00
/// Different types of read guards for [`DynamicReadLock`].
#[derive(Debug)]
2021-04-19 12:08:29 +02:00
enum DynamicReadLockInner<'d, T: Clone> {
/// A simple reference to a non-shared value.
Reference(&'d T),
2020-08-08 10:24:10 +02:00
2021-01-02 16:30:10 +01:00
/// A read guard to a shared [`RefCell`][std::cell::RefCell].
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "sync"))]
2021-04-17 09:15:54 +02:00
Guard(std::cell::Ref<'d, Dynamic>),
2020-11-20 09:52:28 +01:00
/// A read guard to a shared [`RwLock`][std::sync::RwLock].
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
#[cfg(feature = "sync")]
2021-04-17 09:15:54 +02:00
Guard(std::sync::RwLockReadGuard<'d, Dynamic>),
}
2021-04-19 12:08:29 +02:00
impl<'d, T: Any + Clone> Deref for DynamicReadLock<'d, T> {
type Target = T;
#[inline(always)]
fn deref(&self) -> &Self::Target {
match &self.0 {
DynamicReadLockInner::Reference(reference) => *reference,
// Unwrapping is safe because all checking is already done in its constructor
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
DynamicReadLockInner::Guard(guard) => guard.downcast_ref().unwrap(),
}
}
}
2020-11-20 09:52:28 +01:00
/// Underlying [`Variant`] write guard for [`Dynamic`].
///
/// This data structure provides transparent interoperability between
2020-11-20 09:52:28 +01:00
/// normal [`Dynamic`] and shared [`Dynamic`] values.
#[derive(Debug)]
2021-04-19 12:08:29 +02:00
pub struct DynamicWriteLock<'d, T: Clone>(DynamicWriteLockInner<'d, T>);
2020-11-20 09:52:28 +01:00
/// Different types of write guards for [`DynamicReadLock`].
#[derive(Debug)]
2021-04-19 12:08:29 +02:00
enum DynamicWriteLockInner<'d, T: Clone> {
/// A simple mutable reference to a non-shared value.
Reference(&'d mut T),
2020-08-08 10:24:10 +02:00
2021-01-02 16:30:10 +01:00
/// A write guard to a shared [`RefCell`][std::cell::RefCell].
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "sync"))]
2021-04-17 09:15:54 +02:00
Guard(std::cell::RefMut<'d, Dynamic>),
2020-11-20 09:52:28 +01:00
/// A write guard to a shared [`RwLock`][std::sync::RwLock].
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
#[cfg(feature = "sync")]
2021-04-17 09:15:54 +02:00
Guard(std::sync::RwLockWriteGuard<'d, Dynamic>),
}
2021-04-19 12:08:29 +02:00
impl<'d, T: Any + Clone> Deref for DynamicWriteLock<'d, T> {
type Target = T;
#[inline(always)]
fn deref(&self) -> &Self::Target {
match &self.0 {
DynamicWriteLockInner::Reference(reference) => *reference,
// Unwrapping is safe because all checking is already done in its constructor
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
DynamicWriteLockInner::Guard(guard) => guard.downcast_ref().unwrap(),
}
}
}
2021-04-19 12:08:29 +02:00
impl<'d, T: Any + Clone> DerefMut for DynamicWriteLock<'d, T> {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
match &mut self.0 {
DynamicWriteLockInner::Reference(reference) => *reference,
// Unwrapping is safe because all checking is already done in its constructor
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
DynamicWriteLockInner::Guard(guard) => guard.downcast_mut().unwrap(),
}
}
2020-04-12 17:00:06 +02:00
}
impl Dynamic {
2020-11-20 09:52:28 +01:00
/// Does this [`Dynamic`] hold a variant data type
2021-01-02 16:30:10 +01:00
/// instead of one of the supported system primitive types?
2020-08-08 05:46:30 +02:00
#[inline(always)]
2020-04-13 04:27:08 +02:00
pub fn is_variant(&self) -> bool {
match self.0 {
2020-12-08 15:47:38 +01:00
Union::Variant(_, _) => true,
2020-04-13 04:27:08 +02:00
_ => false,
}
}
2021-01-02 16:30:10 +01:00
/// Is the value held by this [`Dynamic`] shared?
2021-01-11 16:09:33 +01:00
///
/// Not available under `no_closure`.
#[cfg(not(feature = "no_closure"))]
2020-08-08 05:46:30 +02:00
#[inline(always)]
pub fn is_shared(&self) -> bool {
#[cfg(not(feature = "no_closure"))]
match self.0 {
Union::Shared(_, _) => return true,
_ => (),
}
false
}
2020-11-20 09:52:28 +01:00
/// Is the value held by this [`Dynamic`] a particular type?
///
2020-11-20 09:52:28 +01:00
/// If the [`Dynamic`] is a shared variant checking is performed on
2021-01-02 16:30:10 +01:00
/// top of its internal value.
2020-08-08 05:46:30 +02:00
#[inline(always)]
2021-04-19 12:08:29 +02:00
pub fn is<T: Any + Clone>(&self) -> bool {
let mut target_type_id = TypeId::of::<T>();
if target_type_id == TypeId::of::<String>() {
target_type_id = TypeId::of::<ImmutableString>();
}
self.type_id() == target_type_id
2020-04-12 17:00:06 +02:00
}
2020-11-20 09:52:28 +01:00
/// Get the [`TypeId`] of the value held by this [`Dynamic`].
2020-08-02 07:33:51 +02:00
///
2020-08-04 10:27:55 +02:00
/// # Panics or Deadlocks When Value is Shared
2020-08-02 07:33:51 +02:00
///
2020-11-25 02:36:06 +01:00
/// Under the `sync` feature, this call may deadlock, or [panic](https://doc.rust-lang.org/std/sync/struct.RwLock.html#panics-1).
2020-08-02 07:33:51 +02:00
/// Otherwise, this call panics if the data is currently borrowed for write.
2020-04-12 17:00:06 +02:00
pub fn type_id(&self) -> TypeId {
match &self.0 {
2020-12-08 15:47:38 +01:00
Union::Unit(_, _) => TypeId::of::<()>(),
Union::Bool(_, _) => TypeId::of::<bool>(),
Union::Str(_, _) => TypeId::of::<ImmutableString>(),
Union::Char(_, _) => TypeId::of::<char>(),
Union::Int(_, _) => TypeId::of::<INT>(),
2020-04-12 17:00:06 +02:00
#[cfg(not(feature = "no_float"))]
2020-12-08 15:47:38 +01:00
Union::Float(_, _) => TypeId::of::<FLOAT>(),
2021-02-13 13:57:56 +01:00
#[cfg(feature = "decimal")]
Union::Decimal(_, _) => TypeId::of::<Decimal>(),
#[cfg(not(feature = "no_index"))]
2020-12-08 15:47:38 +01:00
Union::Array(_, _) => TypeId::of::<Array>(),
#[cfg(not(feature = "no_object"))]
2020-12-08 15:47:38 +01:00
Union::Map(_, _) => TypeId::of::<Map>(),
Union::FnPtr(_, _) => TypeId::of::<FnPtr>(),
2020-09-27 16:15:35 +02:00
#[cfg(not(feature = "no_std"))]
2020-12-08 15:47:38 +01:00
Union::TimeStamp(_, _) => TypeId::of::<Instant>(),
2020-08-08 05:46:30 +02:00
2020-12-08 15:47:38 +01:00
Union::Variant(value, _) => (***value).type_id(),
2020-08-08 05:46:30 +02:00
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2021-03-05 07:18:36 +01:00
Union::Shared(cell, _) => {
#[cfg(not(feature = "sync"))]
let value = cell.borrow();
#[cfg(feature = "sync")]
let value = cell.read().unwrap();
(*value).type_id()
}
2020-04-12 17:00:06 +02:00
}
}
2020-11-20 09:52:28 +01:00
/// Get the name of the type of the value held by this [`Dynamic`].
2020-08-02 07:33:51 +02:00
///
2020-08-04 10:27:55 +02:00
/// # Panics or Deadlocks When Value is Shared
2020-08-02 07:33:51 +02:00
///
2020-11-25 02:36:06 +01:00
/// Under the `sync` feature, this call may deadlock, or [panic](https://doc.rust-lang.org/std/sync/struct.RwLock.html#panics-1).
2020-08-02 07:33:51 +02:00
/// Otherwise, this call panics if the data is currently borrowed for write.
2020-04-12 17:00:06 +02:00
pub fn type_name(&self) -> &'static str {
match &self.0 {
2020-12-08 15:47:38 +01:00
Union::Unit(_, _) => "()",
Union::Bool(_, _) => "bool",
Union::Str(_, _) => "string",
Union::Char(_, _) => "char",
Union::Int(_, _) => type_name::<INT>(),
2020-04-12 17:00:06 +02:00
#[cfg(not(feature = "no_float"))]
2020-12-08 15:47:38 +01:00
Union::Float(_, _) => type_name::<FLOAT>(),
2021-02-13 13:57:56 +01:00
#[cfg(feature = "decimal")]
Union::Decimal(_, _) => "decimal",
#[cfg(not(feature = "no_index"))]
2020-12-08 15:47:38 +01:00
Union::Array(_, _) => "array",
#[cfg(not(feature = "no_object"))]
2020-12-08 15:47:38 +01:00
Union::Map(_, _) => "map",
Union::FnPtr(_, _) => "Fn",
#[cfg(not(feature = "no_std"))]
2020-12-08 15:47:38 +01:00
Union::TimeStamp(_, _) => "timestamp",
2020-09-27 16:15:35 +02:00
2020-12-08 15:47:38 +01:00
Union::Variant(value, _) => (***value).type_name(),
2020-08-08 05:46:30 +02:00
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
#[cfg(not(feature = "sync"))]
2020-12-08 15:47:38 +01:00
Union::Shared(cell, _) => cell
2020-08-04 03:47:48 +02:00
.try_borrow()
.map(|v| (*v).type_name())
.unwrap_or("<shared>"),
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
#[cfg(feature = "sync")]
2020-12-08 15:47:38 +01:00
Union::Shared(cell, _) => (*cell.read().unwrap()).type_name(),
2017-12-20 12:16:14 +01:00
}
}
}
2020-11-12 14:53:26 +01:00
impl Hash for Dynamic {
fn hash<H: Hasher>(&self, state: &mut H) {
match &self.0 {
2020-12-08 15:47:38 +01:00
Union::Unit(_, _) => ().hash(state),
Union::Bool(value, _) => value.hash(state),
Union::Str(s, _) => s.hash(state),
Union::Char(ch, _) => ch.hash(state),
Union::Int(i, _) => i.hash(state),
2020-11-12 14:53:26 +01:00
#[cfg(not(feature = "no_float"))]
Union::Float(f, _) => f.hash(state),
2020-11-12 14:53:26 +01:00
#[cfg(not(feature = "no_index"))]
2020-12-08 15:47:38 +01:00
Union::Array(a, _) => (**a).hash(state),
2020-11-12 14:53:26 +01:00
#[cfg(not(feature = "no_object"))]
2020-12-08 15:47:38 +01:00
Union::Map(m, _) => {
2020-11-16 09:28:04 +01:00
let mut buf: crate::StaticVec<_> = m.iter().collect();
2020-11-15 11:39:23 +01:00
buf.sort_by(|(a, _), (b, _)| a.cmp(b));
2020-11-13 11:32:18 +01:00
2020-11-15 11:39:23 +01:00
buf.into_iter().for_each(|(key, value)| {
2020-11-13 11:32:18 +01:00
key.hash(state);
2020-11-15 11:39:23 +01:00
value.hash(state);
2020-11-13 11:32:18 +01:00
})
}
2021-04-20 17:40:52 +02:00
Union::FnPtr(f, _) if f.is_curried() => {
unimplemented!(
"{} with curried arguments cannot be hashed",
self.type_name()
)
}
Union::FnPtr(f, _) => f.fn_name().hash(state),
2020-11-12 14:53:26 +01:00
#[cfg(not(feature = "no_closure"))]
2021-03-05 07:18:36 +01:00
Union::Shared(cell, _) => {
#[cfg(not(feature = "sync"))]
let value = cell.borrow();
#[cfg(feature = "sync")]
let value = cell.read().unwrap();
(*value).hash(state)
}
2020-11-12 14:53:26 +01:00
2021-03-05 03:33:48 +01:00
_ => unimplemented!("{} cannot be hashed", self.type_name()),
2020-11-12 14:53:26 +01:00
}
}
}
2020-07-03 04:45:01 +02:00
/// Map the name of a standard type into a friendly form.
2021-03-04 11:13:47 +01:00
#[inline(always)]
2020-07-03 04:45:01 +02:00
pub(crate) fn map_std_type_name(name: &str) -> &str {
if name == type_name::<String>() {
2021-03-26 09:57:28 +01:00
return "string";
}
if name == type_name::<ImmutableString>() {
return "string";
2020-07-03 04:45:01 +02:00
}
2021-03-26 09:57:28 +01:00
if name == type_name::<&str>() {
return "string";
}
if name == type_name::<FnPtr>() {
return "Fn";
}
#[cfg(feature = "decimal")]
if name == type_name::<Decimal>() {
return "decimal";
}
#[cfg(not(feature = "no_index"))]
if name == type_name::<Array>() {
return "array";
}
#[cfg(not(feature = "no_object"))]
if name == type_name::<Map>() {
return "map";
}
#[cfg(not(feature = "no_std"))]
if name == type_name::<Instant>() {
return "timestamp";
}
name
2020-07-03 04:45:01 +02:00
}
2020-04-12 17:00:06 +02:00
impl fmt::Display for Dynamic {
2019-09-18 12:21:07 +02:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2020-04-12 17:00:06 +02:00
match &self.0 {
2020-12-08 15:47:38 +01:00
Union::Unit(_, _) => write!(f, ""),
Union::Bool(value, _) => fmt::Display::fmt(value, f),
Union::Str(value, _) => fmt::Display::fmt(value, f),
Union::Char(value, _) => fmt::Display::fmt(value, f),
Union::Int(value, _) => fmt::Display::fmt(value, f),
2020-04-12 17:00:06 +02:00
#[cfg(not(feature = "no_float"))]
2020-12-08 15:47:38 +01:00
Union::Float(value, _) => fmt::Display::fmt(value, f),
2021-02-13 13:57:56 +01:00
#[cfg(feature = "decimal")]
Union::Decimal(value, _) => fmt::Display::fmt(value, f),
#[cfg(not(feature = "no_index"))]
2020-12-08 15:47:38 +01:00
Union::Array(value, _) => fmt::Debug::fmt(value, f),
#[cfg(not(feature = "no_object"))]
2020-12-08 15:47:38 +01:00
Union::Map(value, _) => {
f.write_str("#")?;
fmt::Debug::fmt(value, f)
}
2020-12-08 15:47:38 +01:00
Union::FnPtr(value, _) => fmt::Display::fmt(value, f),
2020-05-05 14:54:56 +02:00
#[cfg(not(feature = "no_std"))]
2020-12-08 15:47:38 +01:00
Union::TimeStamp(_, _) => f.write_str("<timestamp>"),
2020-09-27 16:15:35 +02:00
Union::Variant(value, _) => {
let _type_id = (***value).type_id();
#[cfg(not(feature = "only_i32"))]
#[cfg(not(feature = "only_i64"))]
if _type_id == TypeId::of::<u8>() {
return write!(f, "{}", (**value).as_any().downcast_ref::<u8>().unwrap());
} else if _type_id == TypeId::of::<u16>() {
return write!(f, "{}", (**value).as_any().downcast_ref::<u16>().unwrap());
} else if _type_id == TypeId::of::<u32>() {
return write!(f, "{}", (**value).as_any().downcast_ref::<u32>().unwrap());
} else if _type_id == TypeId::of::<u64>() {
return write!(f, "{}", (**value).as_any().downcast_ref::<u64>().unwrap());
} else if _type_id == TypeId::of::<i8>() {
return write!(f, "{}", (**value).as_any().downcast_ref::<i8>().unwrap());
} else if _type_id == TypeId::of::<i16>() {
return write!(f, "{}", (**value).as_any().downcast_ref::<i16>().unwrap());
} else if _type_id == TypeId::of::<i32>() {
return write!(f, "{}", (**value).as_any().downcast_ref::<i32>().unwrap());
} else if _type_id == TypeId::of::<i64>() {
return write!(f, "{}", (**value).as_any().downcast_ref::<i64>().unwrap());
}
#[cfg(not(feature = "no_float"))]
if _type_id == TypeId::of::<f32>() {
return write!(f, "{}", (**value).as_any().downcast_ref::<f32>().unwrap());
} else if _type_id == TypeId::of::<f64>() {
return write!(f, "{}", (**value).as_any().downcast_ref::<f64>().unwrap());
}
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
if _type_id == TypeId::of::<u128>() {
return write!(f, "{}", (**value).as_any().downcast_ref::<u128>().unwrap());
} else if _type_id == TypeId::of::<i128>() {
return write!(f, "{}", (**value).as_any().downcast_ref::<i128>().unwrap());
}
f.write_str((***value).type_name())
}
2020-08-08 10:24:10 +02:00
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-08-04 03:47:48 +02:00
#[cfg(not(feature = "sync"))]
2020-12-08 15:47:38 +01:00
Union::Shared(cell, _) => {
2020-08-04 03:47:48 +02:00
if let Ok(v) = cell.try_borrow() {
fmt::Display::fmt(&*v, f)
} else {
f.write_str("<shared>")
}
}
#[cfg(not(feature = "no_closure"))]
#[cfg(feature = "sync")]
2020-12-08 15:47:38 +01:00
Union::Shared(cell, _) => fmt::Display::fmt(&*cell.read().unwrap(), f),
2020-04-12 17:00:06 +02:00
}
}
}
impl fmt::Debug for Dynamic {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.0 {
2020-12-08 15:47:38 +01:00
Union::Unit(value, _) => fmt::Debug::fmt(value, f),
Union::Bool(value, _) => fmt::Debug::fmt(value, f),
Union::Str(value, _) => fmt::Debug::fmt(value, f),
Union::Char(value, _) => fmt::Debug::fmt(value, f),
Union::Int(value, _) => fmt::Debug::fmt(value, f),
2020-04-12 17:00:06 +02:00
#[cfg(not(feature = "no_float"))]
2020-12-08 15:47:38 +01:00
Union::Float(value, _) => fmt::Debug::fmt(value, f),
2021-02-13 13:57:56 +01:00
#[cfg(feature = "decimal")]
Union::Decimal(value, _) => fmt::Debug::fmt(value, f),
#[cfg(not(feature = "no_index"))]
2020-12-08 15:47:38 +01:00
Union::Array(value, _) => fmt::Debug::fmt(value, f),
#[cfg(not(feature = "no_object"))]
2020-12-08 15:47:38 +01:00
Union::Map(value, _) => {
f.write_str("#")?;
fmt::Debug::fmt(value, f)
}
2020-12-08 15:47:38 +01:00
Union::FnPtr(value, _) => fmt::Debug::fmt(value, f),
2020-05-05 14:54:56 +02:00
#[cfg(not(feature = "no_std"))]
2020-12-08 15:47:38 +01:00
Union::TimeStamp(_, _) => write!(f, "<timestamp>"),
2020-09-27 16:15:35 +02:00
Union::Variant(value, _) => {
let _type_id = (***value).type_id();
#[cfg(not(feature = "only_i32"))]
#[cfg(not(feature = "only_i64"))]
if _type_id == TypeId::of::<u8>() {
return write!(f, "{:?}", (**value).as_any().downcast_ref::<u8>().unwrap());
} else if _type_id == TypeId::of::<u16>() {
return write!(f, "{:?}", (**value).as_any().downcast_ref::<u16>().unwrap());
} else if _type_id == TypeId::of::<u32>() {
return write!(f, "{:?}", (**value).as_any().downcast_ref::<u32>().unwrap());
} else if _type_id == TypeId::of::<u64>() {
return write!(f, "{:?}", (**value).as_any().downcast_ref::<u64>().unwrap());
} else if _type_id == TypeId::of::<i8>() {
return write!(f, "{:?}", (**value).as_any().downcast_ref::<i8>().unwrap());
} else if _type_id == TypeId::of::<i16>() {
return write!(f, "{:?}", (**value).as_any().downcast_ref::<i16>().unwrap());
} else if _type_id == TypeId::of::<i32>() {
return write!(f, "{:?}", (**value).as_any().downcast_ref::<i32>().unwrap());
} else if _type_id == TypeId::of::<i64>() {
return write!(f, "{:?}", (**value).as_any().downcast_ref::<i64>().unwrap());
}
#[cfg(not(feature = "no_float"))]
if _type_id == TypeId::of::<f32>() {
return write!(f, "{}", (**value).as_any().downcast_ref::<f32>().unwrap());
} else if _type_id == TypeId::of::<f64>() {
return write!(f, "{}", (**value).as_any().downcast_ref::<f64>().unwrap());
}
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
if _type_id == TypeId::of::<u128>() {
return write!(
f,
"{:?}",
(**value).as_any().downcast_ref::<u128>().unwrap()
);
} else if _type_id == TypeId::of::<i128>() {
return write!(
f,
"{:?}",
(**value).as_any().downcast_ref::<i128>().unwrap()
);
}
write!(f, "{}", (*value).type_name())
}
2020-08-08 10:24:10 +02:00
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-08-04 03:47:48 +02:00
#[cfg(not(feature = "sync"))]
2020-12-08 15:47:38 +01:00
Union::Shared(cell, _) => {
2020-08-04 03:47:48 +02:00
if let Ok(v) = cell.try_borrow() {
write!(f, "{:?} (shared)", *v)
} else {
f.write_str("<shared>")
}
}
#[cfg(not(feature = "no_closure"))]
#[cfg(feature = "sync")]
2020-12-08 15:47:38 +01:00
Union::Shared(cell, _) => fmt::Debug::fmt(&*cell.read().unwrap(), f),
2020-04-12 17:00:06 +02:00
}
2017-12-20 12:16:14 +01:00
}
}
2020-03-04 15:00:01 +01:00
impl Clone for Dynamic {
2020-12-08 15:47:38 +01:00
/// Clone the [`Dynamic`] value.
///
2021-01-02 16:30:10 +01:00
/// # WARNING
2020-12-08 15:47:38 +01:00
///
/// The cloned copy is marked read-write even if the original is read-only.
2020-03-04 15:00:01 +01:00
fn clone(&self) -> Self {
2020-05-03 16:17:28 +02:00
match self.0 {
Union::Unit(value, _) => Self(Union::Unit(value, AccessMode::ReadWrite)),
Union::Bool(value, _) => Self(Union::Bool(value, AccessMode::ReadWrite)),
Union::Str(ref value, _) => Self(Union::Str(value.clone(), AccessMode::ReadWrite)),
Union::Char(value, _) => Self(Union::Char(value, AccessMode::ReadWrite)),
Union::Int(value, _) => Self(Union::Int(value, AccessMode::ReadWrite)),
2020-04-12 17:00:06 +02:00
#[cfg(not(feature = "no_float"))]
Union::Float(value, _) => Self(Union::Float(value, AccessMode::ReadWrite)),
2021-02-13 13:57:56 +01:00
#[cfg(feature = "decimal")]
Union::Decimal(ref value, _) => {
Self(Union::Decimal(value.clone(), AccessMode::ReadWrite))
}
#[cfg(not(feature = "no_index"))]
Union::Array(ref value, _) => Self(Union::Array(value.clone(), AccessMode::ReadWrite)),
#[cfg(not(feature = "no_object"))]
Union::Map(ref value, _) => Self(Union::Map(value.clone(), AccessMode::ReadWrite)),
Union::FnPtr(ref value, _) => Self(Union::FnPtr(value.clone(), AccessMode::ReadWrite)),
2020-09-27 16:15:35 +02:00
#[cfg(not(feature = "no_std"))]
2020-12-08 15:47:38 +01:00
Union::TimeStamp(ref value, _) => {
Self(Union::TimeStamp(value.clone(), AccessMode::ReadWrite))
2020-12-08 15:47:38 +01:00
}
2020-08-08 05:46:30 +02:00
2020-12-08 15:47:38 +01:00
Union::Variant(ref value, _) => (***value).clone_into_dynamic(),
2020-08-08 05:46:30 +02:00
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
Union::Shared(ref cell, _) => Self(Union::Shared(cell.clone(), AccessMode::ReadWrite)),
2020-04-12 17:00:06 +02:00
}
2020-03-04 15:00:01 +01:00
}
}
2020-04-30 16:52:36 +02:00
impl Default for Dynamic {
2020-08-08 05:46:30 +02:00
#[inline(always)]
2020-04-30 16:52:36 +02:00
fn default() -> Self {
2020-11-15 16:14:29 +01:00
Self::UNIT
2020-04-30 16:52:36 +02:00
}
}
2020-04-12 17:00:06 +02:00
impl Dynamic {
2020-11-20 09:52:28 +01:00
/// A [`Dynamic`] containing a `()`.
pub const UNIT: Dynamic = Self(Union::Unit((), AccessMode::ReadWrite));
2020-11-20 09:52:28 +01:00
/// A [`Dynamic`] containing a `true`.
pub const TRUE: Dynamic = Self(Union::Bool(true, AccessMode::ReadWrite));
2020-11-20 09:52:28 +01:00
/// A [`Dynamic`] containing a [`false`].
pub const FALSE: Dynamic = Self(Union::Bool(false, AccessMode::ReadWrite));
2020-11-20 09:52:28 +01:00
/// A [`Dynamic`] containing the integer zero.
pub const ZERO: Dynamic = Self(Union::Int(0, AccessMode::ReadWrite));
2020-11-20 09:52:28 +01:00
/// A [`Dynamic`] containing the integer one.
pub const ONE: Dynamic = Self(Union::Int(1, AccessMode::ReadWrite));
2020-11-20 09:52:28 +01:00
/// A [`Dynamic`] containing the integer negative one.
pub const NEGATIVE_ONE: Dynamic = Self(Union::Int(-1, AccessMode::ReadWrite));
2020-11-20 09:52:28 +01:00
/// A [`Dynamic`] containing the floating-point zero.
2020-11-16 06:56:07 +01:00
#[cfg(not(feature = "no_float"))]
2021-04-06 17:18:41 +02:00
pub const FLOAT_ZERO: Dynamic = Self(Union::Float(
FloatWrapper::const_new(0.0),
AccessMode::ReadWrite,
));
2020-11-20 09:52:28 +01:00
/// A [`Dynamic`] containing the floating-point one.
2020-11-16 06:56:07 +01:00
#[cfg(not(feature = "no_float"))]
2021-04-06 17:18:41 +02:00
pub const FLOAT_ONE: Dynamic = Self(Union::Float(
FloatWrapper::const_new(1.0),
AccessMode::ReadWrite,
));
2020-11-20 09:52:28 +01:00
/// A [`Dynamic`] containing the floating-point negative one.
2020-11-16 06:56:07 +01:00
#[cfg(not(feature = "no_float"))]
2021-04-06 17:18:41 +02:00
pub const FLOAT_NEGATIVE_ONE: Dynamic = Self(Union::Float(
FloatWrapper::const_new(-1.0),
AccessMode::ReadWrite,
));
2020-11-15 16:14:29 +01:00
/// Get the [`AccessMode`] for this [`Dynamic`].
pub(crate) fn access_mode(&self) -> AccessMode {
2020-12-08 15:47:38 +01:00
match self.0 {
Union::Unit(_, access)
| Union::Bool(_, access)
| Union::Str(_, access)
| Union::Char(_, access)
| Union::Int(_, access)
| Union::FnPtr(_, access)
2020-12-08 16:09:12 +01:00
| Union::Variant(_, access) => access,
#[cfg(not(feature = "no_float"))]
Union::Float(_, access) => access,
2021-02-13 13:57:56 +01:00
#[cfg(feature = "decimal")]
Union::Decimal(_, access) => access,
2020-12-08 16:09:12 +01:00
#[cfg(not(feature = "no_index"))]
Union::Array(_, access) => access,
#[cfg(not(feature = "no_object"))]
Union::Map(_, access) => access,
#[cfg(not(feature = "no_std"))]
Union::TimeStamp(_, access) => access,
#[cfg(not(feature = "no_closure"))]
Union::Shared(_, access) => access,
2020-12-08 15:47:38 +01:00
}
}
/// Set the [`AccessMode`] for this [`Dynamic`].
pub(crate) fn set_access_mode(&mut self, typ: AccessMode) {
2020-12-08 15:47:38 +01:00
match &mut self.0 {
Union::Unit(_, access)
| Union::Bool(_, access)
| Union::Str(_, access)
| Union::Char(_, access)
| Union::Int(_, access)
| Union::FnPtr(_, access)
2020-12-08 16:09:12 +01:00
| Union::Variant(_, access) => *access = typ,
#[cfg(not(feature = "no_float"))]
Union::Float(_, access) => *access = typ,
2021-02-13 13:57:56 +01:00
#[cfg(feature = "decimal")]
Union::Decimal(_, access) => *access = typ,
2020-12-08 16:09:12 +01:00
#[cfg(not(feature = "no_index"))]
Union::Array(_, access) => *access = typ,
#[cfg(not(feature = "no_object"))]
Union::Map(_, access) => *access = typ,
#[cfg(not(feature = "no_std"))]
Union::TimeStamp(_, access) => *access = typ,
#[cfg(not(feature = "no_closure"))]
Union::Shared(_, access) => *access = typ,
2020-12-08 15:47:38 +01:00
}
}
2020-12-08 16:09:12 +01:00
/// Is this [`Dynamic`] read-only?
///
/// Constant [`Dynamic`] values are read-only. If a [`&mut Dynamic`][Dynamic] to such a constant
/// is passed to a Rust function, the function can use this information to return an error of
2021-01-02 16:30:10 +01:00
/// [`ErrorAssignmentToConstant`][crate::EvalAltResult::ErrorAssignmentToConstant]
2020-12-08 16:09:12 +01:00
/// if its value is going to be modified. This safe-guards constant values from being modified
/// from within Rust functions.
pub fn is_read_only(&self) -> bool {
#[cfg(not(feature = "no_closure"))]
2020-12-09 14:06:36 +01:00
match self.0 {
Union::Shared(_, AccessMode::ReadOnly) => return true,
2021-03-05 06:34:58 +01:00
Union::Shared(ref cell, _) => {
#[cfg(not(feature = "sync"))]
2021-03-05 07:18:36 +01:00
let value = cell.borrow();
2021-03-05 06:34:58 +01:00
#[cfg(feature = "sync")]
2021-03-05 07:18:36 +01:00
let value = cell.read().unwrap();
2020-12-09 14:06:36 +01:00
return match value.access_mode() {
2021-03-05 06:34:58 +01:00
AccessMode::ReadWrite => false,
AccessMode::ReadOnly => true,
};
2021-03-05 06:34:58 +01:00
}
_ => (),
}
2020-12-09 14:06:36 +01:00
match self.access_mode() {
AccessMode::ReadWrite => false,
AccessMode::ReadOnly => true,
2020-12-09 14:06:36 +01:00
}
2020-12-08 15:47:38 +01:00
}
2021-03-05 03:33:48 +01:00
/// Can this [`Dynamic`] be hashed?
pub(crate) fn is_hashable(&self) -> bool {
match &self.0 {
Union::Unit(_, _)
| Union::Bool(_, _)
| Union::Str(_, _)
| Union::Char(_, _)
| Union::Int(_, _) => true,
#[cfg(not(feature = "no_float"))]
Union::Float(_, _) => true,
#[cfg(not(feature = "no_index"))]
Union::Array(_, _) => true,
#[cfg(not(feature = "no_object"))]
Union::Map(_, _) => true,
#[cfg(not(feature = "no_closure"))]
2021-03-05 07:18:36 +01:00
Union::Shared(cell, _) => {
#[cfg(not(feature = "sync"))]
let value = cell.borrow();
#[cfg(feature = "sync")]
let value = cell.read().unwrap();
value.is_hashable()
}
2021-03-05 03:33:48 +01:00
_ => false,
}
}
2020-11-20 09:52:28 +01:00
/// Create a [`Dynamic`] from any type. A [`Dynamic`] value is simply returned as is.
///
/// # Safety
///
/// This type uses some unsafe code, mainly for type casting.
///
/// # Notes
///
2020-11-20 09:52:28 +01:00
/// Beware that you need to pass in an [`Array`] type for it to be recognized as an [`Array`].
/// A [`Vec<T>`][Vec] does not get automatically converted to an [`Array`], but will be a generic
/// restricted trait object instead, because [`Vec<T>`][Vec] is not a supported standard type.
///
2021-03-23 05:13:53 +01:00
/// Similarly, passing in a [`HashMap<String, T>`][std::collections::HashMap] or
/// [`BTreeMap<String, T>`][std::collections::BTreeMap] will not get a [`Map`] but a trait object.
///
2020-04-12 17:00:06 +02:00
/// # Examples
///
2020-04-12 17:00:06 +02:00
/// ```
/// use rhai::Dynamic;
///
/// let result = Dynamic::from(42_i64);
/// assert_eq!(result.type_name(), "i64");
/// assert_eq!(result.to_string(), "42");
///
2020-10-07 05:44:06 +02:00
/// let result = Dynamic::from("hello");
2020-04-12 17:00:06 +02:00
/// assert_eq!(result.type_name(), "string");
/// assert_eq!(result.to_string(), "hello");
2020-04-13 04:27:08 +02:00
///
/// let new_result = Dynamic::from(result);
/// assert_eq!(new_result.type_name(), "string");
/// assert_eq!(new_result.to_string(), "hello");
2020-04-12 17:00:06 +02:00
/// ```
2020-07-22 07:05:24 +02:00
#[inline(always)]
2021-03-22 04:18:09 +01:00
pub fn from<T: Variant + Clone>(mut value: T) -> Self {
2020-10-08 16:25:50 +02:00
// Coded this way in order to maximally leverage potentials for dead-code removal.
2021-03-22 04:18:09 +01:00
if TypeId::of::<T>() == TypeId::of::<Dynamic>() {
return unsafe_try_cast::<_, Dynamic>(value).ok().unwrap();
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<INT>() {
2020-07-22 07:05:24 +02:00
return <dyn Any>::downcast_ref::<INT>(&value)
.unwrap()
.clone()
.into();
}
2020-04-12 17:00:06 +02:00
#[cfg(not(feature = "no_float"))]
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<FLOAT>() {
2020-07-22 07:05:24 +02:00
return <dyn Any>::downcast_ref::<FLOAT>(&value)
.unwrap()
.clone()
.into();
}
2021-02-13 13:57:56 +01:00
#[cfg(feature = "decimal")]
if TypeId::of::<T>() == TypeId::of::<Decimal>() {
return <dyn Any>::downcast_ref::<Decimal>(&value)
.unwrap()
.clone()
.into();
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<bool>() {
2020-07-22 07:05:24 +02:00
return <dyn Any>::downcast_ref::<bool>(&value)
.unwrap()
.clone()
.into();
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<char>() {
2020-07-22 07:05:24 +02:00
return <dyn Any>::downcast_ref::<char>(&value)
.unwrap()
.clone()
.into();
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<ImmutableString>() {
2020-07-22 07:05:24 +02:00
return <dyn Any>::downcast_ref::<ImmutableString>(&value)
.unwrap()
.clone()
.into();
}
2020-10-06 15:25:05 +02:00
if TypeId::of::<T>() == TypeId::of::<&str>() {
return <dyn Any>::downcast_ref::<&str>(&value)
.unwrap()
2021-01-02 16:30:10 +01:00
.deref()
2020-10-06 15:25:05 +02:00
.into();
}
if TypeId::of::<T>() == TypeId::of::<SmartString>() {
return <dyn Any>::downcast_ref::<SmartString>(&value)
.unwrap()
.clone()
.into();
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<()>() {
2020-07-22 07:05:24 +02:00
return ().into();
2020-04-12 17:00:06 +02:00
}
2021-03-22 04:18:09 +01:00
value = match unsafe_try_cast::<_, String>(value) {
Ok(s) => return (s).into(),
2020-06-23 13:24:26 +02:00
Err(val) => val,
};
#[cfg(not(feature = "no_index"))]
{
2021-03-22 04:18:09 +01:00
value = match unsafe_try_cast::<_, Array>(value) {
Ok(array) => return (array).into(),
2020-06-23 13:24:26 +02:00
Err(val) => val,
};
}
#[cfg(not(feature = "no_object"))]
{
2021-03-22 04:18:09 +01:00
value = match unsafe_try_cast::<_, Map>(value) {
Ok(map) => return (map).into(),
2020-06-23 13:24:26 +02:00
Err(val) => val,
2021-03-26 09:57:28 +01:00
};
}
2021-03-22 04:18:09 +01:00
value = match unsafe_try_cast::<_, FnPtr>(value) {
Ok(fn_ptr) => return (fn_ptr).into(),
2020-08-03 17:11:24 +02:00
Err(val) => val,
};
2020-09-27 16:15:35 +02:00
#[cfg(not(feature = "no_std"))]
{
2021-03-22 04:18:09 +01:00
value = match unsafe_try_cast::<_, Instant>(value) {
Ok(timestamp) => return (timestamp).into(),
2020-09-27 16:15:35 +02:00
Err(val) => val,
2021-03-26 09:57:28 +01:00
};
2020-09-27 16:15:35 +02:00
}
2021-03-22 04:18:09 +01:00
Self(Union::Variant(
Box::new(Box::new(value)),
AccessMode::ReadWrite,
))
2020-04-12 17:00:06 +02:00
}
2020-12-26 06:05:57 +01:00
/// Turn the [`Dynamic`] value into a shared [`Dynamic`] value backed by an
/// [`Rc`][std::rc::Rc]`<`[`RefCell`][std::cell::RefCell]`<`[`Dynamic`]`>>` or
/// [`Arc`][std::sync::Arc]`<`[`RwLock`][std::sync::RwLock]`<`[`Dynamic`]`>>`
/// depending on the `sync` feature.
2020-03-04 15:00:01 +01:00
///
2021-02-19 08:50:48 +01:00
/// Not available under `no_closure`.
///
2020-11-20 09:52:28 +01:00
/// Shared [`Dynamic`] values are relatively cheap to clone as they simply increment the
/// reference counts.
///
2020-12-26 06:05:57 +01:00
/// Shared [`Dynamic`] values can be converted seamlessly to and from ordinary [`Dynamic`]
/// values.
///
2020-11-20 09:52:28 +01:00
/// If the [`Dynamic`] value is already shared, this method returns itself.
#[cfg(not(feature = "no_closure"))]
2020-08-04 12:39:24 +02:00
#[inline(always)]
pub fn into_shared(self) -> Self {
let _access = self.access_mode();
2020-12-08 15:47:38 +01:00
match self.0 {
2020-12-08 15:47:38 +01:00
Union::Shared(_, _) => self,
_ => Self(Union::Shared(crate::Locked::new(self).into(), _access)),
}
}
2020-11-20 09:52:28 +01:00
/// Convert the [`Dynamic`] value into specific type.
2020-07-31 10:39:38 +02:00
///
2020-11-20 09:52:28 +01:00
/// Casting to a [`Dynamic`] just returns as is, but if it contains a shared value,
/// it is cloned into a [`Dynamic`] with a normal value.
2020-03-04 15:00:01 +01:00
///
2020-11-20 09:52:28 +01:00
/// Returns [`None`] if types mismatched.
///
2020-08-04 10:27:55 +02:00
/// # Panics or Deadlocks
///
2020-11-25 02:36:06 +01:00
/// Under the `sync` feature, this call may deadlock, or [panic](https://doc.rust-lang.org/std/sync/struct.RwLock.html#panics-1).
/// Otherwise, this call panics if the data is currently borrowed for write.
///
/// These normally shouldn't occur since most operations in Rhai is single-threaded.
2020-04-12 17:00:06 +02:00
///
2020-03-04 15:00:01 +01:00
/// # Example
///
2020-03-19 06:52:10 +01:00
/// ```
2020-04-12 17:00:06 +02:00
/// use rhai::Dynamic;
2020-03-04 15:00:01 +01:00
///
2020-04-12 17:00:06 +02:00
/// let x = Dynamic::from(42_u32);
2020-03-04 15:00:01 +01:00
///
/// assert_eq!(x.try_cast::<u32>().unwrap(), 42);
2020-03-04 15:00:01 +01:00
/// ```
2020-07-22 07:05:24 +02:00
#[inline(always)]
2021-04-19 12:08:29 +02:00
pub fn try_cast<T: Any>(self) -> Option<T> {
2020-10-08 16:25:50 +02:00
// Coded this way in order to maximally leverage potentials for dead-code removal.
2021-03-04 03:50:45 +01:00
#[cfg(not(feature = "no_closure"))]
2021-03-04 03:24:14 +01:00
if let Union::Shared(_, _) = self.0 {
return self.flatten().try_cast::<T>();
2020-07-31 10:39:38 +02:00
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<Dynamic>() {
2021-03-22 04:18:09 +01:00
return unsafe_try_cast::<_, T>(self).ok();
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<INT>() {
2020-07-22 07:05:24 +02:00
return match self.0 {
2021-03-22 04:18:09 +01:00
Union::Int(value, _) => unsafe_try_cast(value).ok(),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2020-07-22 07:05:24 +02:00
#[cfg(not(feature = "no_float"))]
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<FLOAT>() {
2020-07-22 07:05:24 +02:00
return match self.0 {
2021-03-22 04:18:09 +01:00
Union::Float(value, _) => unsafe_try_cast(*value).ok(),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2021-02-13 13:57:56 +01:00
#[cfg(feature = "decimal")]
if TypeId::of::<T>() == TypeId::of::<Decimal>() {
return match self.0 {
2021-03-22 04:18:09 +01:00
Union::Decimal(value, _) => unsafe_try_cast(*value).ok(),
2021-02-13 13:57:56 +01:00
_ => None,
};
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<bool>() {
2020-07-22 07:05:24 +02:00
return match self.0 {
2021-03-22 04:18:09 +01:00
Union::Bool(value, _) => unsafe_try_cast(value).ok(),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<ImmutableString>() {
2020-07-22 07:05:24 +02:00
return match self.0 {
2021-03-22 04:18:09 +01:00
Union::Str(value, _) => unsafe_try_cast(value).ok(),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<String>() {
2020-07-22 07:05:24 +02:00
return match self.0 {
2021-03-22 04:18:09 +01:00
Union::Str(value, _) => unsafe_try_cast(value.into_owned()).ok(),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<char>() {
2020-07-22 07:05:24 +02:00
return match self.0 {
2021-03-22 04:18:09 +01:00
Union::Char(value, _) => unsafe_try_cast(value).ok(),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2020-07-22 07:05:24 +02:00
#[cfg(not(feature = "no_index"))]
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<Array>() {
2020-07-22 07:05:24 +02:00
return match self.0 {
2020-12-08 15:47:38 +01:00
Union::Array(value, _) => unsafe_cast_box::<_, T>(value).ok().map(|v| *v),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2020-07-22 07:05:24 +02:00
#[cfg(not(feature = "no_object"))]
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<Map>() {
2020-07-22 07:05:24 +02:00
return match self.0 {
2020-12-08 15:47:38 +01:00
Union::Map(value, _) => unsafe_cast_box::<_, T>(value).ok().map(|v| *v),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<FnPtr>() {
2020-07-22 07:05:24 +02:00
return match self.0 {
2020-12-08 15:47:38 +01:00
Union::FnPtr(value, _) => unsafe_cast_box::<_, T>(value).ok().map(|v| *v),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2020-09-27 16:15:35 +02:00
#[cfg(not(feature = "no_std"))]
if TypeId::of::<T>() == TypeId::of::<Instant>() {
return match self.0 {
2020-12-08 15:47:38 +01:00
Union::TimeStamp(value, _) => unsafe_cast_box::<_, T>(value).ok().map(|v| *v),
2020-09-27 16:15:35 +02:00
_ => None,
};
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<()>() {
2020-07-22 07:05:24 +02:00
return match self.0 {
2021-03-22 04:18:09 +01:00
Union::Unit(value, _) => unsafe_try_cast(value).ok(),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2020-04-13 04:27:08 +02:00
2020-04-30 16:52:36 +02:00
match self.0 {
2020-12-08 15:47:38 +01:00
Union::Variant(value, _) => (*value).as_box_any().downcast().map(|x| *x).ok(),
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
Union::Shared(_, _) => unreachable!("Union::Shared case should be already handled"),
2020-07-22 07:05:24 +02:00
_ => None,
2017-12-20 12:16:14 +01:00
}
}
2020-11-20 09:52:28 +01:00
/// Convert the [`Dynamic`] value into a specific type.
///
2020-11-20 09:52:28 +01:00
/// Casting to a [`Dynamic`] just returns as is, but if it contains a shared value,
/// it is cloned into a [`Dynamic`] with a normal value.
///
2020-11-20 09:52:28 +01:00
/// Returns [`None`] if types mismatched.
///
2020-08-04 10:27:55 +02:00
/// # Panics or Deadlocks
///
/// Panics if the cast fails (e.g. the type of the actual value is not the
/// same as the specified type).
///
2020-11-25 02:36:06 +01:00
/// Under the `sync` feature, this call may deadlock, or [panic](https://doc.rust-lang.org/std/sync/struct.RwLock.html#panics-1).
/// Otherwise, this call panics if the data is currently borrowed for write.
///
/// These normally shouldn't occur since most operations in Rhai is single-threaded.
///
/// # Example
///
/// ```
2020-04-12 17:00:06 +02:00
/// use rhai::Dynamic;
///
2020-04-12 17:00:06 +02:00
/// let x = Dynamic::from(42_u32);
///
/// assert_eq!(x.cast::<u32>(), 42);
/// ```
2020-07-22 07:05:24 +02:00
#[inline(always)]
2021-04-19 12:08:29 +02:00
pub fn cast<T: Any + Clone>(self) -> T {
#[cfg(not(feature = "no_closure"))]
2020-09-27 05:14:50 +02:00
let self_type_name = if self.is_shared() {
// Avoid panics/deadlocks with shared values
"<shared>"
} else {
self.type_name()
};
#[cfg(feature = "no_closure")]
let self_type_name = self.type_name();
2020-09-27 05:14:50 +02:00
self.try_cast::<T>().unwrap_or_else(|| {
panic!(
2020-09-28 05:19:49 +02:00
"cannot cast {} value and to {}",
2020-09-27 05:14:50 +02:00
self_type_name,
type_name::<T>()
)
})
}
2021-03-30 12:57:16 +02:00
/// Clone the [`Dynamic`] value and convert it into a specific type.
///
/// Casting to a [`Dynamic`] just returns as is, but if it contains a shared value,
/// it is cloned into a [`Dynamic`] with a normal value.
///
/// Returns [`None`] if types mismatched.
///
/// # Panics or Deadlocks
///
/// Panics if the cast fails (e.g. the type of the actual value is not the
/// same as the specified type).
///
/// Under the `sync` feature, this call may deadlock, or [panic](https://doc.rust-lang.org/std/sync/struct.RwLock.html#panics-1).
/// Otherwise, this call panics if the data is currently borrowed for write.
///
/// These normally shouldn't occur since most operations in Rhai is single-threaded.
///
/// # Example
///
/// ```
/// use rhai::Dynamic;
///
/// let x = Dynamic::from(42_u32);
/// let y = &x;
///
/// assert_eq!(y.clone_cast::<u32>(), 42);
/// ```
#[inline(always)]
2021-04-19 12:08:29 +02:00
pub fn clone_cast<T: Any + Clone>(&self) -> T {
self.flatten_clone().cast::<T>()
2021-03-30 12:57:16 +02:00
}
2020-11-20 09:52:28 +01:00
/// Flatten the [`Dynamic`] and clone it.
///
2020-11-20 09:52:28 +01:00
/// If the [`Dynamic`] is not a shared value, it returns a cloned copy.
///
/// If the [`Dynamic`] is a shared value, it returns a cloned copy of the shared value.
2020-08-08 10:24:10 +02:00
#[inline(always)]
2020-08-08 11:04:21 +02:00
pub fn flatten_clone(&self) -> Self {
#[cfg(not(feature = "no_closure"))]
2020-08-08 10:24:10 +02:00
match &self.0 {
2020-12-08 15:47:38 +01:00
Union::Shared(cell, _) => {
2020-08-08 10:24:10 +02:00
#[cfg(not(feature = "sync"))]
2021-03-05 07:18:36 +01:00
let value = cell.borrow();
2020-08-08 10:24:10 +02:00
#[cfg(feature = "sync")]
2021-03-05 07:18:36 +01:00
let value = cell.read().unwrap();
return value.clone();
2020-08-08 10:24:10 +02:00
}
_ => (),
2020-08-08 10:24:10 +02:00
}
self.clone()
2020-08-08 10:24:10 +02:00
}
2020-11-20 09:52:28 +01:00
/// Flatten the [`Dynamic`].
///
2020-11-20 09:52:28 +01:00
/// If the [`Dynamic`] is not a shared value, it returns itself.
///
2020-12-26 06:05:57 +01:00
/// If the [`Dynamic`] is a shared value, it returns the shared value if there are no
/// outstanding references, or a cloned copy.
2020-07-22 07:05:24 +02:00
#[inline(always)]
2020-08-08 10:24:10 +02:00
pub fn flatten(self) -> Self {
#[cfg(not(feature = "no_closure"))]
match self.0 {
Union::Shared(cell, _) => {
return crate::fn_native::shared_try_take(cell).map_or_else(
|cell| {
#[cfg(not(feature = "sync"))]
let value = cell.borrow();
#[cfg(feature = "sync")]
let value = cell.read().unwrap();
value.clone()
},
|value| {
#[cfg(not(feature = "sync"))]
return value.into_inner();
#[cfg(feature = "sync")]
return value.into_inner().unwrap();
},
)
}
_ => (),
}
self
}
/// Flatten the [`Dynamic`] in place.
///
/// If the [`Dynamic`] is not a shared value, it does nothing.
///
/// If the [`Dynamic`] is a shared value, it is set to the shared value if there are no
/// outstanding references, or a cloned copy otherwise.
#[inline(always)]
pub(crate) fn flatten_in_place(&mut self) {
#[cfg(not(feature = "no_closure"))]
match self.0 {
2021-04-17 09:15:54 +02:00
Union::Shared(_, _) => match std::mem::take(self).0 {
Union::Shared(cell, _) => {
2021-03-06 15:07:20 +01:00
*self = crate::fn_native::shared_try_take(cell).map_or_else(
|cell| {
#[cfg(not(feature = "sync"))]
let value = cell.borrow();
#[cfg(feature = "sync")]
let value = cell.read().unwrap();
value.clone()
},
|value| {
#[cfg(not(feature = "sync"))]
return value.into_inner();
#[cfg(feature = "sync")]
return value.into_inner().unwrap();
},
)
}
2021-03-07 15:10:54 +01:00
_ => unreachable!(),
},
_ => (),
}
}
2020-11-20 09:52:28 +01:00
/// Is the [`Dynamic`] a shared value that is locked?
2020-08-02 07:33:51 +02:00
///
/// Not available under `no_closure`.
///
2020-08-02 07:33:51 +02:00
/// ## Note
///
2020-11-25 02:36:06 +01:00
/// Under the `sync` feature, shared values use [`RwLock`][std::sync::RwLock] and they are never locked.
2020-11-20 09:52:28 +01:00
/// Access just waits until the [`RwLock`][std::sync::RwLock] is released.
/// So this method always returns [`false`] under [`Sync`].
#[cfg(not(feature = "no_closure"))]
2020-08-02 07:33:51 +02:00
#[inline(always)]
pub fn is_locked(&self) -> bool {
#[cfg(not(feature = "no_closure"))]
2020-08-02 07:33:51 +02:00
match self.0 {
2020-12-08 15:47:38 +01:00
Union::Shared(ref _cell, _) => {
2020-08-02 07:33:51 +02:00
#[cfg(not(feature = "sync"))]
return _cell.try_borrow().is_err();
#[cfg(feature = "sync")]
return false;
}
_ => (),
2020-08-02 07:33:51 +02:00
}
false
2020-08-02 07:33:51 +02:00
}
2020-11-20 09:52:28 +01:00
/// Get a reference of a specific type to the [`Dynamic`].
/// Casting to [`Dynamic`] just returns a reference to it.
///
2020-11-20 09:52:28 +01:00
/// Returns [`None`] if the cast fails.
2020-08-03 06:10:20 +02:00
///
2020-08-04 10:27:55 +02:00
/// # Panics or Deadlocks When Value is Shared
2020-08-03 06:10:20 +02:00
///
2020-11-25 02:36:06 +01:00
/// Under the `sync` feature, this call may deadlock, or [panic](https://doc.rust-lang.org/std/sync/struct.RwLock.html#panics-1).
2020-08-03 06:10:20 +02:00
/// Otherwise, this call panics if the data is currently borrowed for write.
#[inline(always)]
2021-04-19 12:08:29 +02:00
pub fn read_lock<T: Any + Clone>(&self) -> Option<DynamicReadLock<T>> {
match self.0 {
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-12-08 15:47:38 +01:00
Union::Shared(ref cell, _) => {
#[cfg(not(feature = "sync"))]
2021-03-05 07:18:36 +01:00
let value = cell.borrow();
#[cfg(feature = "sync")]
2021-03-05 07:18:36 +01:00
let value = cell.read().unwrap();
2020-08-03 06:10:20 +02:00
2021-03-05 07:18:36 +01:00
let type_id = (*value).type_id();
2020-08-03 06:10:20 +02:00
if type_id != TypeId::of::<T>() && TypeId::of::<Dynamic>() != TypeId::of::<T>() {
return None;
2020-08-03 06:10:20 +02:00
} else {
return Some(DynamicReadLock(DynamicReadLockInner::Guard(value)));
2020-08-03 06:10:20 +02:00
}
}
_ => (),
}
self.downcast_ref()
.map(|r| DynamicReadLock(DynamicReadLockInner::Reference(r)))
}
2020-11-20 09:52:28 +01:00
/// Get a mutable reference of a specific type to the [`Dynamic`].
/// Casting to [`Dynamic`] just returns a mutable reference to it.
///
2020-11-20 09:52:28 +01:00
/// Returns [`None`] if the cast fails.
2020-08-03 06:10:20 +02:00
///
2020-08-04 10:27:55 +02:00
/// # Panics or Deadlocks When Value is Shared
2020-08-03 06:10:20 +02:00
///
2020-11-25 02:36:06 +01:00
/// Under the `sync` feature, this call may deadlock, or [panic](https://doc.rust-lang.org/std/sync/struct.RwLock.html#panics-1).
2020-08-03 06:10:20 +02:00
/// Otherwise, this call panics if the data is currently borrowed for write.
#[inline(always)]
2021-04-19 12:08:29 +02:00
pub fn write_lock<T: Any + Clone>(&mut self) -> Option<DynamicWriteLock<T>> {
match self.0 {
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-12-08 15:47:38 +01:00
Union::Shared(ref cell, _) => {
#[cfg(not(feature = "sync"))]
2021-03-05 07:18:36 +01:00
let value = cell.borrow_mut();
#[cfg(feature = "sync")]
2021-03-05 07:18:36 +01:00
let value = cell.write().unwrap();
2020-08-03 06:10:20 +02:00
2021-03-05 07:18:36 +01:00
let type_id = (*value).type_id();
2020-08-03 06:10:20 +02:00
if type_id != TypeId::of::<T>() && TypeId::of::<Dynamic>() != TypeId::of::<T>() {
return None;
2020-08-03 06:10:20 +02:00
} else {
return Some(DynamicWriteLock(DynamicWriteLockInner::Guard(value)));
2020-08-03 06:10:20 +02:00
}
}
_ => (),
}
self.downcast_mut()
.map(|r| DynamicWriteLock(DynamicWriteLockInner::Reference(r)))
}
2020-11-20 09:52:28 +01:00
/// Get a reference of a specific type to the [`Dynamic`].
/// Casting to [`Dynamic`] just returns a reference to it.
///
2020-11-20 09:52:28 +01:00
/// Returns [`None`] if the cast fails, or if the value is shared.
2020-07-22 07:05:24 +02:00
#[inline(always)]
pub(crate) fn downcast_ref<T: Any + Clone + ?Sized>(&self) -> Option<&T> {
2020-10-08 16:25:50 +02:00
// Coded this way in order to maximally leverage potentials for dead-code removal.
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<INT>() {
2020-07-22 07:05:24 +02:00
return match &self.0 {
2020-12-08 15:47:38 +01:00
Union::Int(value, _) => <dyn Any>::downcast_ref::<T>(value),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
#[cfg(not(feature = "no_float"))]
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<FLOAT>() {
2020-07-22 07:05:24 +02:00
return match &self.0 {
Union::Float(value, _) => <dyn Any>::downcast_ref::<T>(value.as_ref()),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2021-02-13 13:57:56 +01:00
#[cfg(feature = "decimal")]
if TypeId::of::<T>() == TypeId::of::<Decimal>() {
return match &self.0 {
Union::Decimal(value, _) => <dyn Any>::downcast_ref::<T>(value.as_ref()),
_ => None,
};
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<bool>() {
2020-07-22 07:05:24 +02:00
return match &self.0 {
2020-12-08 15:47:38 +01:00
Union::Bool(value, _) => <dyn Any>::downcast_ref::<T>(value),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<ImmutableString>() {
2020-07-22 07:05:24 +02:00
return match &self.0 {
2020-12-08 15:47:38 +01:00
Union::Str(value, _) => <dyn Any>::downcast_ref::<T>(value),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<char>() {
2020-07-22 07:05:24 +02:00
return match &self.0 {
2020-12-08 15:47:38 +01:00
Union::Char(value, _) => <dyn Any>::downcast_ref::<T>(value),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
#[cfg(not(feature = "no_index"))]
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<Array>() {
2020-07-22 07:05:24 +02:00
return match &self.0 {
2020-12-08 15:47:38 +01:00
Union::Array(value, _) => <dyn Any>::downcast_ref::<T>(value.as_ref()),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
#[cfg(not(feature = "no_object"))]
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<Map>() {
2020-07-22 07:05:24 +02:00
return match &self.0 {
2020-12-08 15:47:38 +01:00
Union::Map(value, _) => <dyn Any>::downcast_ref::<T>(value.as_ref()),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<FnPtr>() {
2020-07-22 07:05:24 +02:00
return match &self.0 {
2020-12-08 15:47:38 +01:00
Union::FnPtr(value, _) => <dyn Any>::downcast_ref::<T>(value.as_ref()),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2020-09-27 16:15:35 +02:00
#[cfg(not(feature = "no_std"))]
if TypeId::of::<T>() == TypeId::of::<Instant>() {
return match &self.0 {
2020-12-08 15:47:38 +01:00
Union::TimeStamp(value, _) => <dyn Any>::downcast_ref::<T>(value.as_ref()),
2020-09-27 16:15:35 +02:00
_ => None,
};
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<()>() {
2020-07-22 07:05:24 +02:00
return match &self.0 {
2020-12-08 15:47:38 +01:00
Union::Unit(value, _) => <dyn Any>::downcast_ref::<T>(value),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<Dynamic>() {
2020-06-23 13:24:26 +02:00
return <dyn Any>::downcast_ref::<T>(self);
2020-04-13 17:31:05 +02:00
}
2020-04-12 17:00:06 +02:00
match &self.0 {
2020-12-08 15:47:38 +01:00
Union::Variant(value, _) => value.as_ref().as_ref().as_any().downcast_ref::<T>(),
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-12-08 15:47:38 +01:00
Union::Shared(_, _) => None,
2020-07-22 07:05:24 +02:00
_ => None,
2020-04-12 17:00:06 +02:00
}
}
2020-11-20 09:52:28 +01:00
/// Get a mutable reference of a specific type to the [`Dynamic`].
/// Casting to [`Dynamic`] just returns a mutable reference to it.
///
2020-11-20 09:52:28 +01:00
/// Returns [`None`] if the cast fails, or if the value is shared.
2020-07-22 07:05:24 +02:00
#[inline(always)]
2021-04-19 12:08:29 +02:00
pub(crate) fn downcast_mut<T: Any + Clone>(&mut self) -> Option<&mut T> {
2020-10-08 16:25:50 +02:00
// Coded this way in order to maximally leverage potentials for dead-code removal.
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<INT>() {
2020-07-22 07:05:24 +02:00
return match &mut self.0 {
2020-12-08 15:47:38 +01:00
Union::Int(value, _) => <dyn Any>::downcast_mut::<T>(value),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
#[cfg(not(feature = "no_float"))]
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<FLOAT>() {
2020-07-22 07:05:24 +02:00
return match &mut self.0 {
Union::Float(value, _) => <dyn Any>::downcast_mut::<T>(value.as_mut()),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2021-02-13 13:57:56 +01:00
#[cfg(feature = "decimal")]
if TypeId::of::<T>() == TypeId::of::<Decimal>() {
return match &mut self.0 {
Union::Decimal(value, _) => <dyn Any>::downcast_mut::<T>(value.as_mut()),
_ => None,
};
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<bool>() {
2020-07-22 07:05:24 +02:00
return match &mut self.0 {
2020-12-08 15:47:38 +01:00
Union::Bool(value, _) => <dyn Any>::downcast_mut::<T>(value),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<ImmutableString>() {
2020-07-22 07:05:24 +02:00
return match &mut self.0 {
2020-12-08 15:47:38 +01:00
Union::Str(value, _) => <dyn Any>::downcast_mut::<T>(value),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<char>() {
2020-07-22 07:05:24 +02:00
return match &mut self.0 {
2020-12-08 15:47:38 +01:00
Union::Char(value, _) => <dyn Any>::downcast_mut::<T>(value),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
#[cfg(not(feature = "no_index"))]
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<Array>() {
2020-07-22 07:05:24 +02:00
return match &mut self.0 {
2020-12-08 15:47:38 +01:00
Union::Array(value, _) => <dyn Any>::downcast_mut::<T>(value.as_mut()),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
#[cfg(not(feature = "no_object"))]
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<Map>() {
2020-07-22 07:05:24 +02:00
return match &mut self.0 {
2020-12-08 15:47:38 +01:00
Union::Map(value, _) => <dyn Any>::downcast_mut::<T>(value.as_mut()),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<FnPtr>() {
2020-07-22 07:05:24 +02:00
return match &mut self.0 {
2020-12-08 15:47:38 +01:00
Union::FnPtr(value, _) => <dyn Any>::downcast_mut::<T>(value.as_mut()),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2020-09-27 16:15:35 +02:00
#[cfg(not(feature = "no_std"))]
if TypeId::of::<T>() == TypeId::of::<Instant>() {
return match &mut self.0 {
2020-12-08 15:47:38 +01:00
Union::TimeStamp(value, _) => <dyn Any>::downcast_mut::<T>(value.as_mut()),
2020-09-27 16:15:35 +02:00
_ => None,
};
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<()>() {
2020-07-22 07:05:24 +02:00
return match &mut self.0 {
2020-12-08 15:47:38 +01:00
Union::Unit(value, _) => <dyn Any>::downcast_mut::<T>(value),
2020-07-22 07:05:24 +02:00
_ => None,
};
}
2020-08-14 07:43:26 +02:00
if TypeId::of::<T>() == TypeId::of::<Dynamic>() {
2020-06-23 13:24:26 +02:00
return <dyn Any>::downcast_mut::<T>(self);
2020-04-13 17:31:05 +02:00
}
2020-04-12 17:00:06 +02:00
match &mut self.0 {
2020-12-08 15:47:38 +01:00
Union::Variant(value, _) => value.as_mut().as_mut_any().downcast_mut::<T>(),
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-12-08 15:47:38 +01:00
Union::Shared(_, _) => None,
2020-07-22 07:05:24 +02:00
_ => None,
2020-04-12 17:00:06 +02:00
}
}
2021-03-05 06:34:58 +01:00
/// Cast the [`Dynamic`] as a unit `()` and return it.
/// Returns the name of the actual type if the cast fails.
#[inline(always)]
pub fn as_unit(&self) -> Result<(), &'static str> {
match self.0 {
Union::Unit(value, _) => Ok(value),
#[cfg(not(feature = "no_closure"))]
Union::Shared(_, _) => self.read_lock().map(|v| *v).ok_or_else(|| self.type_name()),
_ => Err(self.type_name()),
}
}
2020-11-20 09:52:28 +01:00
/// Cast the [`Dynamic`] as the system integer type [`INT`] and return it.
2020-04-12 17:00:06 +02:00
/// Returns the name of the actual type if the cast fails.
2020-08-08 05:46:30 +02:00
#[inline(always)]
pub fn as_int(&self) -> Result<INT, &'static str> {
2020-04-12 17:00:06 +02:00
match self.0 {
2020-12-08 15:47:38 +01:00
Union::Int(n, _) => Ok(n),
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-12-08 15:47:38 +01:00
Union::Shared(_, _) => self.read_lock().map(|v| *v).ok_or_else(|| self.type_name()),
2020-04-12 17:00:06 +02:00
_ => Err(self.type_name()),
}
}
2020-11-20 09:52:28 +01:00
/// Cast the [`Dynamic`] as the system floating-point type [`FLOAT`] and return it.
2020-05-22 15:49:53 +02:00
/// Returns the name of the actual type if the cast fails.
2021-02-13 13:57:56 +01:00
///
/// Not available under `no_float`.
2020-05-22 15:49:53 +02:00
#[cfg(not(feature = "no_float"))]
2020-08-08 05:46:30 +02:00
#[inline(always)]
2020-05-22 15:49:53 +02:00
pub fn as_float(&self) -> Result<FLOAT, &'static str> {
match self.0 {
Union::Float(n, _) => Ok(*n),
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-12-08 15:47:38 +01:00
Union::Shared(_, _) => self.read_lock().map(|v| *v).ok_or_else(|| self.type_name()),
2020-05-22 15:49:53 +02:00
_ => Err(self.type_name()),
}
}
2021-02-21 07:26:31 +01:00
/// _(DECIMAL)_ Cast the [`Dynamic`] as a [`Decimal`] and return it.
2021-02-13 13:57:56 +01:00
/// Returns the name of the actual type if the cast fails.
///
2021-02-21 07:26:31 +01:00
/// Exported under the `decimal` feature only.
2021-02-13 13:57:56 +01:00
#[cfg(feature = "decimal")]
#[inline(always)]
2021-03-03 06:34:29 +01:00
pub fn as_decimal(&self) -> Result<Decimal, &'static str> {
match &self.0 {
Union::Decimal(n, _) => Ok(**n),
2021-02-13 13:57:56 +01:00
#[cfg(not(feature = "no_closure"))]
Union::Shared(_, _) => self.read_lock().map(|v| *v).ok_or_else(|| self.type_name()),
_ => Err(self.type_name()),
}
}
2020-11-20 09:52:28 +01:00
/// Cast the [`Dynamic`] as a [`bool`] and return it.
2020-04-12 17:00:06 +02:00
/// Returns the name of the actual type if the cast fails.
2020-08-08 05:46:30 +02:00
#[inline(always)]
pub fn as_bool(&self) -> Result<bool, &'static str> {
2020-04-12 17:00:06 +02:00
match self.0 {
2020-12-08 15:47:38 +01:00
Union::Bool(b, _) => Ok(b),
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-12-08 15:47:38 +01:00
Union::Shared(_, _) => self.read_lock().map(|v| *v).ok_or_else(|| self.type_name()),
2020-04-12 17:00:06 +02:00
_ => Err(self.type_name()),
}
}
2020-11-20 09:52:28 +01:00
/// Cast the [`Dynamic`] as a [`char`] and return it.
2020-04-12 17:00:06 +02:00
/// Returns the name of the actual type if the cast fails.
2020-08-08 05:46:30 +02:00
#[inline(always)]
pub fn as_char(&self) -> Result<char, &'static str> {
2020-04-12 17:00:06 +02:00
match self.0 {
2020-12-08 15:47:38 +01:00
Union::Char(n, _) => Ok(n),
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-12-08 15:47:38 +01:00
Union::Shared(_, _) => self.read_lock().map(|v| *v).ok_or_else(|| self.type_name()),
2020-04-12 17:00:06 +02:00
_ => Err(self.type_name()),
}
}
2021-03-05 16:00:27 +01:00
/// Cast the [`Dynamic`] as an [`ImmutableString`] and return it.
2020-04-12 17:00:06 +02:00
/// Returns the name of the actual type if the cast fails.
///
2021-03-05 16:00:27 +01:00
/// # Panics
///
/// Panics if the value is shared.
2020-08-08 05:46:30 +02:00
#[inline(always)]
pub(crate) fn as_str_ref(&self) -> Result<&str, &'static str> {
2020-04-12 17:00:06 +02:00
match &self.0 {
2020-12-08 15:47:38 +01:00
Union::Str(s, _) => Ok(s),
2021-03-05 16:00:27 +01:00
#[cfg(not(feature = "no_closure"))]
Union::Shared(_, _) => panic!("as_str() cannot be called on shared values"),
2020-04-12 17:00:06 +02:00
_ => Err(self.type_name()),
}
}
2020-11-20 09:52:28 +01:00
/// Convert the [`Dynamic`] into a [`String`] and return it.
/// If there are other references to the same string, a cloned copy is returned.
2020-04-12 17:00:06 +02:00
/// Returns the name of the actual type if the cast fails.
2020-08-08 05:46:30 +02:00
#[inline(always)]
pub fn take_string(self) -> Result<String, &'static str> {
self.take_immutable_string()
.map(ImmutableString::into_owned)
}
2020-11-20 09:52:28 +01:00
/// Convert the [`Dynamic`] into an [`ImmutableString`] and return it.
/// Returns the name of the actual type if the cast fails.
2021-03-04 11:13:47 +01:00
#[inline(always)]
pub fn take_immutable_string(self) -> Result<ImmutableString, &'static str> {
2020-04-12 17:00:06 +02:00
match self.0 {
2020-12-08 15:47:38 +01:00
Union::Str(s, _) => Ok(s),
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-12-08 15:47:38 +01:00
Union::Shared(cell, _) => {
#[cfg(not(feature = "sync"))]
2021-03-05 07:18:36 +01:00
let value = cell.borrow();
#[cfg(feature = "sync")]
2021-03-05 07:18:36 +01:00
let value = cell.read().unwrap();
2021-03-05 07:18:36 +01:00
match &value.0 {
Union::Str(s, _) => Ok(s.clone()),
2021-03-05 07:18:36 +01:00
_ => Err((*value).type_name()),
}
}
2020-06-25 12:07:57 +02:00
_ => Err(self.type_name()),
}
}
}
2020-04-12 17:00:06 +02:00
impl From<()> for Dynamic {
2020-08-08 05:46:30 +02:00
#[inline(always)]
fn from(value: ()) -> Self {
Self(Union::Unit(value, AccessMode::ReadWrite))
2020-04-12 17:00:06 +02:00
}
}
impl From<bool> for Dynamic {
2020-08-08 05:46:30 +02:00
#[inline(always)]
fn from(value: bool) -> Self {
Self(Union::Bool(value, AccessMode::ReadWrite))
2020-04-12 17:00:06 +02:00
}
}
impl From<INT> for Dynamic {
2020-08-08 05:46:30 +02:00
#[inline(always)]
fn from(value: INT) -> Self {
Self(Union::Int(value, AccessMode::ReadWrite))
2020-04-12 17:00:06 +02:00
}
}
#[cfg(not(feature = "no_float"))]
impl From<FLOAT> for Dynamic {
2020-08-08 05:46:30 +02:00
#[inline(always)]
fn from(value: FLOAT) -> Self {
Self(Union::Float(value.into(), AccessMode::ReadWrite))
}
}
#[cfg(not(feature = "no_float"))]
2021-04-06 17:18:41 +02:00
impl From<FloatWrapper<FLOAT>> for Dynamic {
#[inline(always)]
2021-04-06 17:18:41 +02:00
fn from(value: FloatWrapper<FLOAT>) -> Self {
Self(Union::Float(value, AccessMode::ReadWrite))
2020-04-12 17:00:06 +02:00
}
}
2021-02-13 13:57:56 +01:00
#[cfg(feature = "decimal")]
impl From<Decimal> for Dynamic {
#[inline(always)]
fn from(value: Decimal) -> Self {
Self(Union::Decimal(
Box::new(value.into()),
AccessMode::ReadWrite,
))
}
}
impl From<char> for Dynamic {
2020-08-08 05:46:30 +02:00
#[inline(always)]
fn from(value: char) -> Self {
Self(Union::Char(value, AccessMode::ReadWrite))
2020-04-12 17:00:06 +02:00
}
}
2020-06-23 13:24:26 +02:00
impl<S: Into<ImmutableString>> From<S> for Dynamic {
2020-08-08 05:46:30 +02:00
#[inline(always)]
2020-06-23 13:24:26 +02:00
fn from(value: S) -> Self {
Self(Union::Str(value.into(), AccessMode::ReadWrite))
2020-05-25 07:44:28 +02:00
}
}
2021-03-29 05:36:02 +02:00
impl From<&ImmutableString> for Dynamic {
#[inline(always)]
fn from(value: &ImmutableString) -> Self {
value.clone().into()
}
}
#[cfg(not(feature = "no_smartstring_for_identifier"))]
2021-03-29 07:40:33 +02:00
impl From<&crate::Identifier> for Dynamic {
2021-03-29 05:36:02 +02:00
#[inline(always)]
2021-03-29 07:40:33 +02:00
fn from(value: &crate::Identifier) -> Self {
2021-04-20 13:19:35 +02:00
value.to_string().into()
2021-03-29 05:36:02 +02:00
}
}
#[cfg(not(feature = "no_index"))]
impl Dynamic {
/// Create a [`Dynamc`] from an [`Array`].
#[inline(always)]
pub(crate) fn from_array(array: Array) -> Self {
Self(Union::Array(Box::new(array), AccessMode::ReadWrite))
}
}
#[cfg(not(feature = "no_index"))]
2021-04-20 13:19:35 +02:00
impl<T: Variant + Clone> From<Vec<T>> for Dynamic {
2020-08-08 05:46:30 +02:00
#[inline(always)]
2021-04-20 13:19:35 +02:00
fn from(value: Vec<T>) -> Self {
2020-12-08 15:47:38 +01:00
Self(Union::Array(
Box::new(value.into_iter().map(Dynamic::from).collect()),
AccessMode::ReadWrite,
2020-12-08 15:47:38 +01:00
))
}
}
#[cfg(not(feature = "no_index"))]
impl<T: Variant + Clone> From<&[T]> for Dynamic {
2020-08-08 05:46:30 +02:00
#[inline(always)]
fn from(value: &[T]) -> Self {
2020-12-08 15:47:38 +01:00
Self(Union::Array(
Box::new(value.iter().cloned().map(Dynamic::from).collect()),
AccessMode::ReadWrite,
2020-12-08 15:47:38 +01:00
))
}
}
2021-03-07 15:10:54 +01:00
#[cfg(not(feature = "no_index"))]
2021-04-17 09:15:54 +02:00
impl<T: Variant + Clone> std::iter::FromIterator<T> for Dynamic {
2021-03-07 15:10:54 +01:00
#[inline(always)]
fn from_iter<X: IntoIterator<Item = T>>(iter: X) -> Self {
Self(Union::Array(
Box::new(iter.into_iter().map(Dynamic::from).collect()),
AccessMode::ReadWrite,
))
}
}
#[cfg(not(feature = "no_object"))]
impl Dynamic {
/// Create a [`Dynamc`] from a [`Map`].
#[inline(always)]
pub(crate) fn from_map(map: Map) -> Self {
Self(Union::Map(Box::new(map), AccessMode::ReadWrite))
}
}
#[cfg(not(feature = "no_object"))]
2021-03-23 05:13:53 +01:00
#[cfg(not(feature = "no_std"))]
2021-04-17 09:15:54 +02:00
impl<K: Into<crate::Identifier>, T: Variant + Clone> From<std::collections::HashMap<K, T>>
2020-11-16 09:28:04 +01:00
for Dynamic
{
2020-08-08 05:46:30 +02:00
#[inline(always)]
2021-04-17 09:15:54 +02:00
fn from(value: std::collections::HashMap<K, T>) -> Self {
2020-12-08 15:47:38 +01:00
Self(Union::Map(
Box::new(
value
.into_iter()
.map(|(k, v)| (k.into(), Dynamic::from(v)))
.collect(),
),
AccessMode::ReadWrite,
2020-12-08 15:47:38 +01:00
))
}
}
2021-03-23 05:13:53 +01:00
#[cfg(not(feature = "no_object"))]
2021-04-17 09:15:54 +02:00
impl<K: Into<crate::Identifier>, T: Variant + Clone> From<std::collections::BTreeMap<K, T>>
for Dynamic
2021-03-23 05:13:53 +01:00
{
#[inline(always)]
2021-04-17 09:15:54 +02:00
fn from(value: std::collections::BTreeMap<K, T>) -> Self {
2021-03-23 05:13:53 +01:00
Self(Union::Map(
Box::new(
value
.into_iter()
.map(|(k, v)| (k.into(), Dynamic::from(v)))
.collect(),
),
AccessMode::ReadWrite,
))
}
}
2020-06-25 12:07:57 +02:00
impl From<FnPtr> for Dynamic {
2020-08-08 05:46:30 +02:00
#[inline(always)]
2020-06-25 12:07:57 +02:00
fn from(value: FnPtr) -> Self {
Self(Union::FnPtr(Box::new(value), AccessMode::ReadWrite))
2020-07-22 17:12:09 +02:00
}
}
impl From<Box<FnPtr>> for Dynamic {
2020-08-08 05:46:30 +02:00
#[inline(always)]
2020-07-22 17:12:09 +02:00
fn from(value: Box<FnPtr>) -> Self {
Self(Union::FnPtr(value, AccessMode::ReadWrite))
2020-06-25 12:07:57 +02:00
}
}
2020-09-27 12:47:20 +02:00
#[cfg(not(feature = "no_std"))]
2020-09-26 13:41:04 +02:00
impl From<Instant> for Dynamic {
#[inline(always)]
fn from(value: Instant) -> Self {
Self(Union::TimeStamp(Box::new(value), AccessMode::ReadWrite))
2020-09-26 13:41:04 +02:00
}
}