Skip to main content

dynamic/
lib.rs

1use bytemuck::{AnyBitPattern, NoUninit, cast_slice, cast_slice_mut};
2use smol_str::SmolStr;
3use std::collections::BTreeMap;
4use std::mem;
5use tinyvec::TinyVec;
6const TINY_SIZE: usize = 28;
7pub mod json;
8#[derive(Debug, Default, Clone, PartialEq)]
9pub struct MyVec<T> {
10    pub(crate) data: TinyVec<[u8; TINY_SIZE]>,
11    phantom: std::marker::PhantomData<T>,
12}
13
14impl<T> MyVec<T> {
15    pub fn len(&self) -> usize {
16        self.data.len() / mem::size_of::<T>()
17    }
18
19    pub fn is_empty(&self) -> bool {
20        self.data.is_empty()
21    }
22
23    pub fn as_slice(&self) -> &[u8] {
24        self.data.as_slice()
25    }
26}
27
28impl<T: NoUninit + AnyBitPattern> MyVec<T> {
29    pub fn push(&mut self, value: T) {
30        let binding = [value];
31        let bytes = cast_slice(&binding);
32        self.data.extend_from_slice(bytes);
33    }
34
35    pub fn pop(&mut self) -> Option<T>
36    where
37        T: AnyBitPattern,
38    {
39        if self.data.len() < mem::size_of::<T>() {
40            return None;
41        }
42        let start = self.data.len() - mem::size_of::<T>();
43        let slice = &self.data[start..];
44        let value = cast_slice::<u8, T>(slice)[0];
45        self.data.truncate(start);
46        Some(value)
47    }
48
49    pub fn get(&self, idx: usize) -> Option<T> {
50        if idx >= self.len() {
51            return None;
52        }
53        let start = idx * mem::size_of::<T>();
54        let slice = &self.data[start..start + mem::size_of::<T>()];
55        Some(cast_slice::<u8, T>(slice)[0])
56    }
57
58    pub fn set(&mut self, idx: usize, value: T) {
59        if idx < self.len() {
60            let start = idx * mem::size_of::<T>();
61            let slice = &mut self.data[start..start + mem::size_of::<T>()];
62            cast_slice_mut::<u8, T>(slice)[0] = value;
63        }
64    }
65
66    pub fn iter(&self) -> Iter<'_, T> {
67        Iter { data: self.data.as_slice(), index: 0, phantom: std::marker::PhantomData }
68    }
69    pub fn extend_from_slice(&mut self, slice: &[T]) {
70        self.data.extend_from_slice(cast_slice(slice));
71    }
72}
73
74impl<T: NoUninit> From<&[T]> for MyVec<T> {
75    fn from(vec: &[T]) -> Self {
76        let mut data: TinyVec<[u8; TINY_SIZE]> = TinyVec::new();
77        data.extend_from_slice(cast_slice(vec));
78        Self { data, phantom: std::marker::PhantomData }
79    }
80}
81
82impl<T: NoUninit, const N: usize> From<[T; N]> for MyVec<T> {
83    fn from(arr: [T; N]) -> Self {
84        Self::from(&arr[..])
85    }
86}
87
88impl<T: AnyBitPattern> From<MyVec<T>> for Vec<T> {
89    fn from(my_vec: MyVec<T>) -> Self {
90        cast_slice(my_vec.data.as_slice()).to_vec()
91    }
92}
93
94pub struct Iter<'a, T> {
95    data: &'a [u8],
96    index: usize,
97    phantom: std::marker::PhantomData<T>,
98}
99
100impl<'a, T: AnyBitPattern> Iterator for Iter<'a, T> {
101    type Item = &'a T;
102    fn next(&mut self) -> Option<Self::Item> {
103        let size = std::mem::size_of::<T>();
104        let start = self.index * size;
105
106        if start + size > self.data.len() {
107            return None;
108        }
109
110        let slice = &self.data[start..start + size];
111        let value = &cast_slice::<u8, T>(slice)[0];
112        self.index += 1;
113        Some(value)
114    }
115
116    fn size_hint(&self) -> (usize, Option<usize>) {
117        let remaining = self.data.len() / std::mem::size_of::<T>() - self.index;
118        (remaining, Some(remaining))
119    }
120}
121
122impl<'a, T: AnyBitPattern> ExactSizeIterator for Iter<'a, T> {
123    fn len(&self) -> usize {
124        self.data.len() / std::mem::size_of::<T>() - self.index
125    }
126}
127
128#[derive(Debug, thiserror::Error)]
129pub enum DynamicErr {
130    #[error("type mismatch")]
131    TypeMismatch,
132    #[error("range error: {0}")]
133    Range(i64),
134    #[error("没有成员: {0}")]
135    NoField(SmolStr),
136    #[error("out of range")]
137    OutOfRange,
138}
139
140use std::sync::{Arc, RwLock};
141#[derive(Debug, Default, Clone)]
142pub enum Dynamic {
143    #[default]
144    Null,
145    Bool(bool),
146    U8(u8),
147    I8(i8),
148    U16(u16),
149    I16(i16),
150    U32(u32),
151    I32(i32), //默认整数类型
152    U64(u64),
153    I64(i64),
154    F32(f32), //默认浮点类型
155    F64(f64),
156    String(SmolStr),
157    Bytes(Vec<u8>),
158    VecI8(MyVec<i8>),
159    VecU16(MyVec<u16>),
160    VecI16(MyVec<i16>),
161    VecU32(MyVec<u32>),
162    VecI32(MyVec<i32>),
163    VecF32(MyVec<f32>),
164    VecU64(Vec<u64>),
165    VecI64(Vec<i64>),
166    VecF64(Vec<f64>),
167    List(Arc<RwLock<Vec<Dynamic>>>),
168    Map(Arc<RwLock<BTreeMap<SmolStr, Dynamic>>>),
169    Struct {
170        addr: usize,
171        ty: Type,
172    },
173    Iter {
174        idx: usize,
175        keys: Vec<SmolStr>,
176        value: Box<Dynamic>,
177    },
178}
179
180unsafe impl Send for Dynamic {}
181unsafe impl Sync for Dynamic {}
182
183impl PartialEq for Dynamic {
184    fn eq(&self, other: &Self) -> bool {
185        match (self, other) {
186            (Self::Null, Self::Null) => true,
187            (Self::Bool(a), Self::Bool(b)) => a == b,
188            (Self::String(a), Self::String(b)) => a == b,
189            (Self::Bytes(a), Self::Bytes(b)) => a == b,
190            // Integer types - compare as i64
191            (Self::U8(a), Self::U8(b)) => a == b,
192            (Self::I8(a), Self::I8(b)) => a == b,
193            (Self::U16(a), Self::U16(b)) => a == b,
194            (Self::I16(a), Self::I16(b)) => a == b,
195            (Self::U32(a), Self::U32(b)) => a == b,
196            (Self::I32(a), Self::I32(b)) => a == b,
197            (Self::U64(a), Self::U64(b)) => a == b,
198            (Self::I64(a), Self::I64(b)) => a == b,
199            // Mixed integer types - compare as i64
200            (a, b) if a.is_int() && b.is_int() => a.as_int() == b.as_int(),
201            // Float types
202            (Self::F32(a), Self::F32(b)) => a.to_bits() == b.to_bits(),
203            (Self::F64(a), Self::F64(b)) => a.to_bits() == b.to_bits(),
204            (a, b) if (a.is_f32() || a.is_f64()) && (b.is_f32() || b.is_f64()) => a.as_float() == b.as_float(),
205            // Typed vectors
206            (Self::VecI8(a), Self::VecI8(b)) => a.data == b.data,
207            (Self::VecU16(a), Self::VecU16(b)) => a.data == b.data,
208            (Self::VecI16(a), Self::VecI16(b)) => a.data == b.data,
209            (Self::VecU32(a), Self::VecU32(b)) => a.data == b.data,
210            (Self::VecI32(a), Self::VecI32(b)) => a.data == b.data,
211            (Self::VecF32(a), Self::VecF32(b)) => a.data == b.data,
212            (Self::VecU64(a), Self::VecU64(b)) => a == b,
213            (Self::VecI64(a), Self::VecI64(b)) => a == b,
214            (Self::VecF64(a), Self::VecF64(b)) => a == b,
215            // List - compare inner values
216            (Self::List(a), Self::List(b)) => {
217                let a_guard = a.read().unwrap();
218                let b_guard = b.read().unwrap();
219                if a_guard.len() != b_guard.len() {
220                    return false;
221                }
222                a_guard.iter().zip(b_guard.iter()).all(|(x, y)| x == y)
223            }
224            // Map - compare key-value pairs
225            (Self::Map(a), Self::Map(b)) => {
226                let a_guard = a.read().unwrap();
227                let b_guard = b.read().unwrap();
228                if a_guard.len() != b_guard.len() {
229                    return false;
230                }
231                for (k, v) in a_guard.iter() {
232                    if let Some(other_v) = b_guard.get(k) {
233                        if v != other_v {
234                            return false;
235                        }
236                    } else {
237                        return false;
238                    }
239                }
240                true
241            }
242            // Struct - compare addresses and types
243            (Self::Struct { addr: a_addr, ty: a_ty }, Self::Struct { addr: b_addr, ty: b_ty }) => a_addr == b_addr && a_ty == b_ty,
244            _ => false,
245        }
246    }
247}
248
249impl Eq for Dynamic {}
250
251use std::cmp::Ordering;
252
253impl PartialOrd for Dynamic {
254    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
255        Some(self.cmp(other))
256    }
257}
258
259impl Ord for Dynamic {
260    fn cmp(&self, other: &Self) -> Ordering {
261        if self.is_f32() || self.is_f64() || other.is_f32() || other.is_f64() {
262            self.as_float().unwrap_or(0.0).total_cmp(&other.as_float().unwrap_or(0.0))
263        } else if self.is_int() || other.is_int() {
264            self.as_int().unwrap_or(0).cmp(&other.as_int().unwrap_or(0))
265        } else if self.is_uint() || other.is_uint() {
266            self.as_uint().unwrap_or(0).cmp(&other.as_uint().unwrap_or(0))
267        } else if (self.is_true() && other.is_false()) || (self.is_false() && other.is_true()) {
268            Ordering::Less
269        } else if self.is_null() && other.is_null() {
270            Ordering::Equal
271        } else if let Self::String(s1) = self
272            && let Self::String(s2) = other
273        {
274            s1.cmp(s2)
275        } else {
276            Ordering::Equal
277        }
278    }
279}
280
281macro_rules! impl_dynamic_scalar {
282    ($variant:ident, $ty:ty) => {
283        impl From<$ty> for Dynamic {
284            fn from(value: $ty) -> Self {
285                Dynamic::$variant(value)
286            }
287        }
288    };
289}
290
291impl_dynamic_scalar!(Bool, bool);
292
293impl_dynamic_scalar!(I8, i8);
294impl_dynamic_scalar!(U16, u16);
295impl_dynamic_scalar!(I16, i16);
296impl_dynamic_scalar!(U32, u32);
297impl_dynamic_scalar!(I32, i32);
298impl_dynamic_scalar!(F32, f32);
299impl_dynamic_scalar!(I64, i64);
300impl_dynamic_scalar!(U64, u64);
301impl_dynamic_scalar!(F64, f64);
302impl_dynamic_scalar!(String, SmolStr);
303impl From<&str> for Dynamic {
304    fn from(s: &str) -> Self {
305        Dynamic::String(s.into())
306    }
307}
308
309macro_rules! impl_try_from_dynamic_int {
310    ($($target:ty),+ $(,)?) => {
311        $(
312            impl TryFrom<Dynamic> for $target {
313                type Error = DynamicErr;
314                fn try_from(value: Dynamic) -> Result<Self, Self::Error> {
315                    match value {
316                        Dynamic::U8(v)  => v.try_into().map_err(|_| DynamicErr::OutOfRange),
317                        Dynamic::U16(v) => v.try_into().map_err(|_| DynamicErr::OutOfRange),
318                        Dynamic::U32(v) => v.try_into().map_err(|_| DynamicErr::OutOfRange),
319                        Dynamic::U64(v) => v.try_into().map_err(|_| DynamicErr::OutOfRange),
320                        Dynamic::I8(v)  => v.try_into().map_err(|_| DynamicErr::OutOfRange),
321                        Dynamic::I16(v) => v.try_into().map_err(|_| DynamicErr::OutOfRange),
322                        Dynamic::I32(v) => v.try_into().map_err(|_| DynamicErr::OutOfRange),
323                        Dynamic::I64(v) => v.try_into().map_err(|_| DynamicErr::OutOfRange),
324                        _ => Err(DynamicErr::TypeMismatch),
325                    }
326                }
327            }
328        )+
329    };
330}
331impl_try_from_dynamic_int!(u8, u16, u32, u64, i8, i16, i32, i64);
332
333impl TryFrom<Dynamic> for f64 {
334    type Error = DynamicErr;
335    fn try_from(value: Dynamic) -> Result<Self, Self::Error> {
336        match value {
337            Dynamic::F32(v) => Ok(v as f64),
338            Dynamic::F64(v) => Ok(v),
339            Dynamic::U8(v) => Ok(v as f64),
340            Dynamic::U16(v) => Ok(v as f64),
341            Dynamic::U32(v) => Ok(v as f64),
342            Dynamic::U64(v) => Ok(v as f64),
343            Dynamic::I8(v) => Ok(v as f64),
344            Dynamic::I16(v) => Ok(v as f64),
345            Dynamic::I32(v) => Ok(v as f64),
346            Dynamic::I64(v) => Ok(v as f64),
347            _ => Err(DynamicErr::TypeMismatch),
348        }
349    }
350}
351
352impl TryFrom<Dynamic> for f32 {
353    type Error = DynamicErr;
354    fn try_from(value: Dynamic) -> Result<Self, Self::Error> {
355        match value {
356            Dynamic::F32(v) => Ok(v),
357            Dynamic::F64(v) => Ok(v as f32),
358            Dynamic::U8(v) => Ok(v as f32),
359            Dynamic::U16(v) => Ok(v as f32),
360            Dynamic::U32(v) => Ok(v as f32),
361            Dynamic::U64(v) => Ok(v as f32),
362            Dynamic::I8(v) => Ok(v as f32),
363            Dynamic::I16(v) => Ok(v as f32),
364            Dynamic::I32(v) => Ok(v as f32),
365            Dynamic::I64(v) => Ok(v as f32),
366            _ => Err(DynamicErr::TypeMismatch),
367        }
368    }
369}
370
371impl TryFrom<Dynamic> for bool {
372    type Error = DynamicErr;
373    fn try_from(value: Dynamic) -> Result<Self, Self::Error> {
374        match value {
375            Dynamic::Bool(v) => Ok(v),
376            Dynamic::U8(v) => Ok(v != 0),
377            Dynamic::U16(v) => Ok(v != 0),
378            Dynamic::U32(v) => Ok(v != 0),
379            Dynamic::U64(v) => Ok(v != 0),
380            Dynamic::I8(v) => Ok(v != 0),
381            Dynamic::I16(v) => Ok(v != 0),
382            Dynamic::I32(v) => Ok(v != 0),
383            Dynamic::I64(v) => Ok(v != 0),
384            _ => Err(DynamicErr::TypeMismatch),
385        }
386    }
387}
388
389impl TryFrom<Dynamic> for SmolStr {
390    type Error = DynamicErr;
391    fn try_from(value: Dynamic) -> Result<Self, Self::Error> {
392        match value {
393            Dynamic::String(s) => Ok(s),
394            _ => Err(DynamicErr::TypeMismatch),
395        }
396    }
397}
398
399macro_rules! impl_dynamic_vec_from_slice {
400    ($variant:ident, $ty:ty) => {
401        impl From<&[$ty]> for Dynamic {
402            fn from(vec: &[$ty]) -> Self {
403                Dynamic::$variant(MyVec::from(vec))
404            }
405        }
406
407        impl<const N: usize> From<[$ty; N]> for Dynamic {
408            fn from(vec: [$ty; N]) -> Self {
409                Dynamic::$variant(MyVec::from(vec))
410            }
411        }
412    };
413}
414
415impl_dynamic_vec_from_slice!(VecI8, i8);
416impl_dynamic_vec_from_slice!(VecU16, u16);
417impl_dynamic_vec_from_slice!(VecI16, i16);
418impl_dynamic_vec_from_slice!(VecU32, u32);
419impl_dynamic_vec_from_slice!(VecI32, i32);
420impl_dynamic_vec_from_slice!(VecF32, f32);
421
422impl From<&[u8]> for Dynamic {
423    fn from(vec: &[u8]) -> Self {
424        Dynamic::Bytes(vec.to_vec())
425    }
426}
427
428impl From<Vec<u8>> for Dynamic {
429    fn from(vec: Vec<u8>) -> Self {
430        Dynamic::Bytes(vec)
431    }
432}
433
434impl From<&[u64]> for Dynamic {
435    fn from(vec: &[u64]) -> Self {
436        Dynamic::VecU64(vec.to_vec())
437    }
438}
439
440impl<const N: usize> From<[u64; N]> for Dynamic {
441    fn from(vec: [u64; N]) -> Self {
442        Dynamic::VecU64(vec.to_vec())
443    }
444}
445
446impl From<&[i64]> for Dynamic {
447    fn from(vec: &[i64]) -> Self {
448        Dynamic::VecI64(vec.to_vec())
449    }
450}
451impl<const N: usize> From<[i64; N]> for Dynamic {
452    fn from(vec: [i64; N]) -> Self {
453        Dynamic::VecI64(vec.to_vec())
454    }
455}
456
457impl From<&[f64]> for Dynamic {
458    fn from(vec: &[f64]) -> Self {
459        Dynamic::VecF64(vec.to_vec())
460    }
461}
462impl<const N: usize> From<[f64; N]> for Dynamic {
463    fn from(vec: [f64; N]) -> Self {
464        Dynamic::VecF64(vec.to_vec())
465    }
466}
467
468impl<T: Into<Dynamic>> From<Vec<T>> for Dynamic {
469    fn from(vec: Vec<T>) -> Self {
470        let vec = vec.into_iter().map(|v| v.into()).collect();
471        Dynamic::List(Arc::new(RwLock::new(vec)))
472    }
473}
474
475impl From<String> for Dynamic {
476    fn from(s: String) -> Self {
477        Dynamic::String(s.into())
478    }
479}
480
481impl ToString for Dynamic {
482    fn to_string(&self) -> String {
483        match self {
484            Self::Null => "()".into(),
485            Self::Bool(b) => {
486                if *b {
487                    "true".into()
488                } else {
489                    "false".into()
490                }
491            }
492            Self::U8(u) => u.to_string(),
493            Self::U16(u) => u.to_string(),
494            Self::U32(u) => u.to_string(),
495            Self::U64(u) => u.to_string(),
496            Self::I8(u) => u.to_string(),
497            Self::I16(u) => u.to_string(),
498            Self::I32(u) => u.to_string(),
499            Self::I64(u) => u.to_string(),
500            Self::F32(u) => u.to_string(),
501            Self::F64(u) => u.to_string(),
502            Self::String(s) => s.to_string(),
503            _ => {
504                let mut buf = String::new();
505                self.to_json(&mut buf);
506                if buf.is_empty() { format!("{:?}", self) } else { buf }
507            }
508        }
509    }
510}
511
512use anyhow::Result;
513impl Dynamic {
514    pub fn deep_clone(&self) -> Self {
515        match self {
516            Self::Map(m) => {
517                let m = m.read().unwrap().iter().map(|(k, v)| (k.clone(), v.clone())).collect();
518                Self::map(m)
519            }
520            Self::List(l) => {
521                let l = l.read().unwrap().iter().map(|item| item.clone()).collect();
522                Self::list(l)
523            }
524            Self::Struct { addr, ty } => Self::Struct { addr: *addr, ty: ty.clone() },
525            _ => self.clone(),
526        }
527    }
528
529    pub fn add(&mut self, val: i64) -> Option<i64> {
530        //如果是 整数类型 增加指定值 并返回新的值 不考虑溢出
531        match self {
532            Self::U8(u) => {
533                let v = (*u as i64) + val;
534                *u = v as u8;
535                Some(v)
536            }
537            Self::U16(u) => {
538                let v = (*u as i64) + val;
539                *u = v as u16;
540                Some(v)
541            }
542            Self::U32(u) => {
543                let v = (*u as i64) + val;
544                *u = v as u32;
545                Some(v)
546            }
547            Self::U64(u) => {
548                let v = (*u as i64) + val;
549                *u = v as u64;
550                Some(v)
551            }
552            Self::I8(i) => {
553                let v = (*i as i64) + val;
554                *i = v as i8;
555                Some(v)
556            }
557            Self::I16(i) => {
558                let v = (*i as i64) + val;
559                *i = v as i16;
560                Some(v)
561            }
562            Self::I32(i) => {
563                let v = (*i as i64) + val;
564                *i = v as i32;
565                Some(v)
566            }
567            Self::I64(i) => {
568                let v = (*i as i64) + val;
569                *i = v;
570                Some(v)
571            }
572            _ => None,
573        }
574    }
575
576    pub fn is_vec(&self) -> bool {
577        use Dynamic::*;
578        match self {
579            VecI8(_) | VecU16(_) | Self::VecI16(_) | VecU32(_) | VecI32(_) | VecF32(_) | VecU64(_) | VecI64(_) | VecF64(_) => true,
580            _ => false,
581        }
582    }
583
584    pub fn as_bytes(&self) -> Option<&[u8]> {
585        match self {
586            Self::Bytes(b) => Some(b.as_slice()),
587            _ => None,
588        }
589    }
590
591    pub fn as_str(&self) -> &str {
592        match self {
593            Dynamic::String(s) => s.as_str(),
594            _ => "",
595        }
596    }
597
598    pub fn is_native(&self) -> bool {
599        if self.is_f64() || self.is_f32() || self.is_int() || self.is_true() || self.is_false() { true } else { false }
600    }
601
602    pub fn from_utf8(buf: &[u8]) -> Result<Self> {
603        Ok(Dynamic::from(SmolStr::new(std::str::from_utf8(buf)?)))
604    }
605
606    pub fn append(&self, other: Self) {
607        match (self, other) {
608            (Self::List(left), rhs) => {
609                if let Self::List(right) = rhs {
610                    left.write().unwrap().append(&mut right.write().unwrap());
611                } else {
612                    left.write().unwrap().push(rhs);
613                }
614            }
615            (Self::Map(left), Self::Map(right)) => {
616                left.write().unwrap().append(&mut right.write().unwrap());
617            }
618            (_, _) => {}
619        }
620    }
621
622    pub fn into_vec<T: TryFrom<Self> + 'static>(self) -> Option<Vec<T>> {
623        if std::any::TypeId::of::<T>() == std::any::TypeId::of::<Dynamic>() {
624            match self {
625                Dynamic::List(list) => {
626                    match Arc::try_unwrap(list) {
627                        Ok(vec) => vec.into_inner().map(|v| unsafe { mem::transmute::<Vec<Dynamic>, Vec<T>>(v) }).ok(), // 成功:直接返回 Vec
628                        Err(_) => None,                                                                                 // 失败:有其他引用,无法移动所有权
629                    }
630                }
631                _ => {
632                    let mut vec = Vec::with_capacity(self.len());
633                    for idx in 0..self.len() {
634                        if let Some(item) = self.get_idx(idx) {
635                            vec.push(item);
636                        }
637                    }
638                    Some(unsafe { mem::transmute(vec) })
639                }
640            }
641        } else {
642            match self {
643                Dynamic::List(list) => Arc::try_unwrap(list).ok().and_then(|l| l.into_inner().map(|l| l.into_iter().filter_map(|l| T::try_from(l).ok()).collect()).ok()),
644                Dynamic::Bytes(vec) => {
645                    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u8>() {
646                        let bytes_vec: Vec<u8> = Vec::from(vec);
647                        Some(unsafe { mem::transmute(bytes_vec) })
648                    } else {
649                        None
650                    }
651                }
652                Dynamic::VecI8(vec) => {
653                    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i8>() {
654                        let vec_i8: Vec<i8> = Vec::from(vec);
655                        Some(unsafe { mem::transmute(vec_i8) })
656                    } else {
657                        None
658                    }
659                }
660                Dynamic::VecU16(vec) => {
661                    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u16>() {
662                        let vec_u16: Vec<u16> = Vec::from(vec);
663                        Some(unsafe { mem::transmute(vec_u16) })
664                    } else {
665                        None
666                    }
667                }
668                Dynamic::VecI16(vec) => {
669                    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i16>() {
670                        let vec_i16: Vec<i16> = Vec::from(vec);
671                        Some(unsafe { mem::transmute(vec_i16) })
672                    } else {
673                        None
674                    }
675                }
676                Dynamic::VecU32(vec) => {
677                    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u32>() {
678                        let vec_u32: Vec<u32> = Vec::from(vec);
679                        Some(unsafe { mem::transmute(vec_u32) })
680                    } else {
681                        None
682                    }
683                }
684                Dynamic::VecI32(vec) => {
685                    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i32>() {
686                        let vec_i32: Vec<i32> = Vec::from(vec);
687                        Some(unsafe { mem::transmute(vec_i32) })
688                    } else {
689                        None
690                    }
691                }
692                Dynamic::VecF32(vec) => {
693                    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<f32>() {
694                        let vec_f32: Vec<f32> = Vec::from(vec);
695                        Some(unsafe { mem::transmute(vec_f32) })
696                    } else {
697                        None
698                    }
699                }
700                Dynamic::VecU64(vec) => {
701                    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u64>() {
702                        Some(unsafe { mem::transmute(vec) })
703                    } else {
704                        None
705                    }
706                }
707                Dynamic::VecI64(vec) => {
708                    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i64>() {
709                        Some(unsafe { mem::transmute(vec) })
710                    } else {
711                        None
712                    }
713                }
714                Dynamic::VecF64(vec) => {
715                    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<f64>() {
716                        Some(unsafe { mem::transmute(vec) })
717                    } else {
718                        None
719                    }
720                }
721                _ => None,
722            }
723        }
724    }
725
726    pub fn push<T: Into<Dynamic> + 'static>(&mut self, value: T) -> bool {
727        match self {
728            Self::List(list) => {
729                list.write().unwrap().push(value.into());
730                true
731            }
732            Self::Bytes(vec) => {
733                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u8>() {
734                    vec.push(unsafe { mem::transmute_copy(&value) });
735                    true
736                } else {
737                    false
738                }
739            }
740            Self::VecI8(vec) => {
741                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i8>() {
742                    vec.push(unsafe { mem::transmute_copy(&value) });
743                    true
744                } else {
745                    false
746                }
747            }
748            Self::VecU16(vec) => {
749                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u16>() {
750                    vec.push(unsafe { mem::transmute_copy(&value) });
751                    true
752                } else {
753                    false
754                }
755            }
756            Self::VecI16(vec) => {
757                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i16>() {
758                    vec.push(unsafe { mem::transmute_copy(&value) });
759                    true
760                } else {
761                    false
762                }
763            }
764            Self::VecU32(vec) => {
765                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u32>() {
766                    vec.push(unsafe { mem::transmute_copy(&value) });
767                    true
768                } else {
769                    false
770                }
771            }
772            Self::VecI32(vec) => {
773                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i32>() {
774                    vec.push(unsafe { mem::transmute_copy(&value) });
775                    true
776                } else {
777                    false
778                }
779            }
780            Self::VecF32(vec) => {
781                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<f32>() {
782                    vec.push(unsafe { mem::transmute_copy(&value) });
783                    true
784                } else {
785                    false
786                }
787            }
788            Self::VecU64(vec) => {
789                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u64>() {
790                    vec.push(unsafe { mem::transmute_copy(&value) });
791                    true
792                } else {
793                    false
794                }
795            }
796            Self::VecI64(vec) => {
797                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i64>() {
798                    vec.push(unsafe { mem::transmute_copy(&value) });
799                    true
800                } else {
801                    false
802                }
803            }
804            Self::VecF64(vec) => {
805                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<f64>() {
806                    vec.push(unsafe { mem::transmute_copy(&value) });
807                    true
808                } else {
809                    false
810                }
811            }
812            _ => false,
813        }
814    }
815
816    pub fn pop(&mut self) -> Option<Dynamic> {
817        match self {
818            Self::List(list) => list.write().unwrap().pop(),
819            Self::Bytes(vec) => vec.pop().map(Dynamic::U8),
820            Self::VecI8(vec) => vec.pop().map(Dynamic::I8),
821            Self::VecU16(vec) => vec.pop().map(Dynamic::U16),
822            Self::VecI16(vec) => vec.pop().map(Dynamic::I16),
823            Self::VecU32(vec) => vec.pop().map(Dynamic::U32),
824            Self::VecI32(vec) => vec.pop().map(Dynamic::I32),
825            Self::VecF32(vec) => vec.pop().map(Dynamic::F32),
826            Self::VecU64(vec) => vec.pop().map(Dynamic::U64),
827            Self::VecI64(vec) => vec.pop().map(Dynamic::I64),
828            Self::VecF64(vec) => vec.pop().map(Dynamic::F64),
829            _ => None,
830        }
831    }
832
833    pub fn is_null(&self) -> bool {
834        match self {
835            Self::Null => true,
836            _ => false,
837        }
838    }
839
840    pub fn as_bool(&self) -> Option<bool> {
841        if let Self::Bool(b) = self { Some(*b) } else { None }
842    }
843
844    pub fn is_true(&self) -> bool {
845        match self {
846            Self::Bool(b) => *b,
847            _ => false,
848        }
849    }
850
851    pub fn is_false(&self) -> bool {
852        match self {
853            Self::Bool(b) => !*b,
854            _ => false,
855        }
856    }
857
858    pub fn is_int(&self) -> bool {
859        match self {
860            Self::I8(_) | Self::I16(_) | Self::I32(_) | Self::I64(_) => true,
861            Self::U8(_) | Self::U16(_) | Self::U32(_) | Self::U64(_) => true,
862            _ => false,
863        }
864    }
865
866    pub fn as_int(&self) -> Option<i64> {
867        match self {
868            Self::U8(u) => Some(*u as i64),
869            Self::U16(u) => Some(*u as i64),
870            Self::U32(u) => Some(*u as i64),
871            Self::U64(u) => Some(*u as i64),
872            Self::I8(i) => Some(*i as i64),
873            Self::I16(i) => Some(*i as i64),
874            Self::I32(i) => Some(*i as i64),
875            Self::I64(i) => Some(*i as i64),
876            _ => None,
877        }
878    }
879
880    pub fn is_uint(&self) -> bool {
881        match self {
882            Self::U8(_) | Self::U16(_) | Self::U32(_) | Self::U64(_) => true,
883            _ => false,
884        }
885    }
886
887    pub fn as_uint(&self) -> Option<u64> {
888        match self {
889            Self::U8(i) => Some(*i as u64),
890            Self::U16(i) => Some(*i as u64),
891            Self::U32(i) => Some(*i as u64),
892            Self::U64(i) => Some(*i as u64),
893            _ => None,
894        }
895    }
896
897    pub fn is_f32(&self) -> bool {
898        if let Self::F32(_) = self { true } else { false }
899    }
900
901    pub fn is_str(&self) -> bool {
902        if let Self::String(_) = self { true } else { false }
903    }
904
905    pub fn is_f64(&self) -> bool {
906        if let Self::F64(_) = self { true } else { false }
907    }
908
909    pub fn as_float(&self) -> Option<f64> {
910        match self {
911            Self::U8(u) => Some(*u as f64),
912            Self::U16(u) => Some(*u as f64),
913            Self::U32(u) => Some(*u as f64),
914            Self::U64(u) => Some(*u as f64),
915            Self::I8(i) => Some(*i as f64),
916            Self::I16(i) => Some(*i as f64),
917            Self::I32(i) => Some(*i as f64),
918            Self::I64(i) => Some(*i as f64),
919            Self::F32(f) => Some(*f as f64),
920            Self::F64(f) => Some(*f),
921            _ => None,
922        }
923    }
924
925    pub fn is_signed(&self) -> bool {
926        match self {
927            Self::I8(_) | Self::I16(_) | Self::I32(_) | Self::I64(_) | Self::F32(_) | Self::F64(_) => true,
928            _ => false,
929        }
930    }
931
932    pub fn size_of(&self) -> usize {
933        match self {
934            Self::I8(_) | Self::U8(_) => 1,
935            Self::I16(_) | Self::U16(_) => 2,
936            Self::I32(_) | Self::U32(_) | Self::F32(_) => 4,
937            Self::I64(_) | Self::U64(_) | Self::F64(_) => 8,
938            Self::String(s) => s.len(),
939            Self::Bytes(bytes) => bytes.len(),
940            Self::VecI8(vec) => vec.len(),
941            Self::VecU16(vec) => vec.len(),
942            Self::VecI16(vec) => vec.len(),
943            Self::VecU32(vec) => vec.len(),
944            Self::VecI32(vec) => vec.len(),
945            Self::VecF32(vec) => vec.len(),
946            Self::VecI64(vec) => vec.len(),
947            Self::VecU64(vec) => vec.len(),
948            Self::VecF64(vec) => vec.len(),
949            Self::List(list) => list.read().unwrap().len(),
950            Self::Map(obj) => obj.read().unwrap().len(),
951            Self::Struct { ty, .. } => ty.len(),
952            _ => 1,
953        }
954    }
955
956    pub fn list(v: Vec<Dynamic>) -> Self {
957        Dynamic::List(Arc::new(RwLock::new(v)))
958    }
959
960    pub fn is_list(&self) -> bool {
961        match self {
962            Self::List(_) | Self::VecF32(_) | Self::VecF64(_) | Self::VecI16(_) | Self::VecI32(_) | Self::VecI64(_) | Self::VecU16(_) | Self::VecU32(_) | Self::VecU64(_) => true,
963            _ => false,
964        }
965    }
966
967    pub fn split(self, tag: &str) -> Self {
968        match self {
969            Self::String(s) => Self::list(s.split(tag).map(|p| Dynamic::from(p)).collect()),
970            _ => self,
971        }
972    }
973
974    pub fn map(m: BTreeMap<SmolStr, Dynamic>) -> Self {
975        Dynamic::Map(Arc::new(RwLock::new(m)))
976    }
977
978    pub fn into_map(self) -> Option<BTreeMap<SmolStr, Dynamic>> {
979        if let Self::Map(map) = self { Arc::try_unwrap(map).ok().and_then(|m| m.into_inner().ok()) } else { None }
980    }
981
982    pub fn is_map(&self) -> bool {
983        if let Self::Map(_) | Self::Struct { .. } = self { true } else { false }
984    }
985
986    pub fn insert<K: Into<SmolStr>, T: Into<Self>>(&self, key: K, value: T) {
987        match self {
988            Self::Map(obj) => {
989                obj.write().unwrap().insert(key.into(), value.into());
990            }
991            _ => {}
992        }
993    }
994
995    pub fn len(&self) -> usize {
996        match self {
997            Self::String(value) => value.len(),
998            Self::List(list) => list.read().unwrap().len(),
999            Self::Bytes(bytes) => bytes.len(),
1000            Self::VecI8(vec) => vec.len(),
1001            Self::VecU16(vec) => vec.len(),
1002            Self::VecI16(vec) => vec.len(),
1003            Self::VecU32(vec) => vec.len(),
1004            Self::VecI32(vec) => vec.len(),
1005            Self::VecF32(vec) => vec.len(),
1006            Self::VecI64(vec) => vec.len(),
1007            Self::VecU64(vec) => vec.len(),
1008            Self::VecF64(vec) => vec.len(),
1009            Self::Map(obj) => obj.read().unwrap().len(),
1010            _ => 0,
1011        }
1012    }
1013
1014    pub fn keys(&self) -> Vec<SmolStr> {
1015        if let Self::Map(map) = self {
1016            map.read().unwrap().keys().cloned().collect()
1017        } else if let Self::Struct { ty: Type::Struct { params: _, fields }, .. } = self {
1018            fields.iter().map(|(name, _)| name.clone()).collect()
1019        } else {
1020            Vec::new()
1021        }
1022    }
1023
1024    pub fn contains(&self, key: &str) -> bool {
1025        if let Self::Map(map) = self {
1026            map.read().unwrap().get(key).is_some_and(|value| !value.is_null())
1027        } else if let Self::Struct { ty, .. } = self {
1028            ty.get_field(key).is_ok()
1029        } else if let Self::List(list) = self {
1030            list.read().unwrap().iter().find(|l| l.as_str() == key).is_some()
1031        } else if let Self::String(s) = self {
1032            s.contains(key)
1033        } else {
1034            false
1035        }
1036    }
1037
1038    pub fn starts_with(&self, prefix: &str) -> bool {
1039        if let Self::String(s) = self { s.starts_with(prefix) } else { false }
1040    }
1041
1042    pub fn get_dynamic(&self, key: &str) -> Option<Dynamic> {
1043        if let Self::Map(map) = self {
1044            map.read().unwrap().get(key).cloned()
1045        } else if let Self::Struct { addr, ty } = self {
1046            let (idx, field_ty) = ty.get_field(key).ok()?;
1047            Self::read_struct_field(*addr, idx, field_ty, ty)
1048        } else {
1049            None
1050        }
1051    }
1052
1053    pub fn set_dynamic(&self, key: SmolStr, value: impl Into<Dynamic>) {
1054        if let Self::Map(map) = self {
1055            map.write().unwrap().insert(key, value.into());
1056        } else if let Self::Struct { addr, ty } = self
1057            && let Ok((idx, field_ty)) = ty.get_field(key.as_str())
1058        {
1059            Self::write_struct_field(*addr, idx, field_ty, ty, value.into());
1060        }
1061    }
1062
1063    fn field_addr(addr: usize, idx: usize, struct_ty: &Type) -> Option<usize> {
1064        struct_ty.field_offset(idx).map(|offset| addr + offset as usize)
1065    }
1066
1067    fn read_dynamic_ptr(addr: usize) -> Option<Dynamic> {
1068        let ptr = unsafe { std::ptr::read_unaligned(addr as *const usize) };
1069        if ptr == 0 { None } else { Some(unsafe { (&*(ptr as *const Dynamic)).clone() }) }
1070    }
1071
1072    fn write_dynamic_ptr(addr: usize, value: Dynamic) {
1073        let ptr = Box::into_raw(Box::new(value)) as usize;
1074        unsafe {
1075            std::ptr::write_unaligned(addr as *mut usize, ptr);
1076        }
1077    }
1078
1079    fn read_struct_field(addr: usize, idx: usize, field_ty: &Type, struct_ty: &Type) -> Option<Dynamic> {
1080        let field_addr = Self::field_addr(addr, idx, struct_ty)?;
1081        match field_ty {
1082            Type::Bool => Some(Dynamic::Bool(unsafe { std::ptr::read_unaligned(field_addr as *const u8) } != 0)),
1083            Type::I8 => Some(Dynamic::I8(unsafe { std::ptr::read_unaligned(field_addr as *const i8) })),
1084            Type::U8 => Some(Dynamic::U8(unsafe { std::ptr::read_unaligned(field_addr as *const u8) })),
1085            Type::I16 => Some(Dynamic::I16(unsafe { std::ptr::read_unaligned(field_addr as *const i16) })),
1086            Type::U16 => Some(Dynamic::U16(unsafe { std::ptr::read_unaligned(field_addr as *const u16) })),
1087            Type::I32 => Some(Dynamic::I32(unsafe { std::ptr::read_unaligned(field_addr as *const i32) })),
1088            Type::U32 => Some(Dynamic::U32(unsafe { std::ptr::read_unaligned(field_addr as *const u32) })),
1089            Type::I64 => Some(Dynamic::I64(unsafe { std::ptr::read_unaligned(field_addr as *const i64) })),
1090            Type::U64 => Some(Dynamic::U64(unsafe { std::ptr::read_unaligned(field_addr as *const u64) })),
1091            Type::F32 => Some(Dynamic::F32(unsafe { std::ptr::read_unaligned(field_addr as *const f32) })),
1092            Type::F64 => Some(Dynamic::F64(unsafe { std::ptr::read_unaligned(field_addr as *const f64) })),
1093            Type::Struct { .. } => {
1094                let ptr = unsafe { std::ptr::read_unaligned(field_addr as *const usize) };
1095                Some(Dynamic::Struct { addr: ptr, ty: field_ty.clone() })
1096            }
1097            _ => Self::read_dynamic_ptr(field_addr),
1098        }
1099    }
1100
1101    fn write_struct_field(addr: usize, idx: usize, field_ty: &Type, struct_ty: &Type, value: Dynamic) {
1102        let Some(field_addr) = Self::field_addr(addr, idx, struct_ty) else {
1103            return;
1104        };
1105        match field_ty {
1106            Type::Bool => unsafe {
1107                std::ptr::write_unaligned(field_addr as *mut u8, if value.is_true() { 1 } else { 0 });
1108            },
1109            Type::I8 => unsafe {
1110                std::ptr::write_unaligned(field_addr as *mut i8, value.try_into().unwrap_or_default());
1111            },
1112            Type::U8 => unsafe {
1113                std::ptr::write_unaligned(field_addr as *mut u8, value.try_into().unwrap_or_default());
1114            },
1115            Type::I16 => unsafe {
1116                std::ptr::write_unaligned(field_addr as *mut i16, value.try_into().unwrap_or_default());
1117            },
1118            Type::U16 => unsafe {
1119                std::ptr::write_unaligned(field_addr as *mut u16, value.try_into().unwrap_or_default());
1120            },
1121            Type::I32 => unsafe {
1122                std::ptr::write_unaligned(field_addr as *mut i32, value.try_into().unwrap_or_default());
1123            },
1124            Type::U32 => unsafe {
1125                std::ptr::write_unaligned(field_addr as *mut u32, value.try_into().unwrap_or_default());
1126            },
1127            Type::I64 => unsafe {
1128                std::ptr::write_unaligned(field_addr as *mut i64, value.try_into().unwrap_or_default());
1129            },
1130            Type::U64 => unsafe {
1131                std::ptr::write_unaligned(field_addr as *mut u64, value.try_into().unwrap_or_default());
1132            },
1133            Type::F32 => unsafe {
1134                std::ptr::write_unaligned(field_addr as *mut f32, f32::try_from(value).unwrap_or_default());
1135            },
1136            Type::F64 => unsafe {
1137                std::ptr::write_unaligned(field_addr as *mut f64, f64::try_from(value).unwrap_or_default());
1138            },
1139            Type::Struct { .. } => {
1140                if let Dynamic::Struct { addr, ty: _ } = value {
1141                    unsafe {
1142                        std::ptr::write_unaligned(field_addr as *mut usize, addr);
1143                    }
1144                }
1145            }
1146            _ => Self::write_dynamic_ptr(field_addr, value),
1147        }
1148    }
1149
1150    pub fn remove_dynamic(&self, key: &str) -> Option<Dynamic> {
1151        if let Self::Map(map) = self { map.write().unwrap().remove(key) } else { None }
1152    }
1153
1154    pub fn get_idx(&self, idx: usize) -> Option<Self> {
1155        match self {
1156            Self::List(list) => list.read().unwrap().get(idx).cloned(),
1157            Self::VecI8(vec) => vec.get(idx).map(Self::I8),
1158            Self::VecU16(vec) => vec.get(idx).map(Self::U16),
1159            Self::VecI16(vec) => vec.get(idx).map(Self::I16),
1160            Self::VecU32(vec) => vec.get(idx).map(Self::U32),
1161            Self::VecI32(vec) => vec.get(idx).map(Self::I32),
1162            Self::VecF32(vec) => vec.get(idx).map(Self::F32),
1163            Self::VecI64(vec) => vec.get(idx).cloned().map(Self::I64),
1164            Self::VecU64(vec) => vec.get(idx).cloned().map(Self::U64),
1165            Self::VecF64(vec) => vec.get(idx).cloned().map(Self::F64),
1166            Self::Struct { addr, ty } => {
1167                if let Type::Struct { params: _, fields } = ty {
1168                    fields.get(idx).and_then(|(_, field_ty)| Self::read_struct_field(*addr, idx, field_ty, ty))
1169                } else {
1170                    None
1171                }
1172            }
1173            _ => None,
1174        }
1175    }
1176
1177    pub fn into_iter(self) -> Self {
1178        if self.is_map() {
1179            let keys = self.keys();
1180            Self::Iter { idx: 0, keys, value: Box::new(self) }
1181        } else {
1182            Self::Iter { idx: 0, keys: Vec::new(), value: Box::new(self) }
1183        }
1184    }
1185
1186    pub fn next(&mut self) -> Option<Self> {
1187        if let Self::Iter { idx, keys, value } = self {
1188            if !keys.is_empty() {
1189                if *idx < keys.len() {
1190                    let k = keys[*idx].clone();
1191                    let v = value.get_dynamic(k.as_str()).unwrap();
1192                    *idx += 1;
1193                    return Some(list!(k, v));
1194                }
1195            } else {
1196                if let Some(v) = value.get_idx(*idx) {
1197                    *idx += 1;
1198                    return Some(v);
1199                }
1200            }
1201        }
1202        None
1203    }
1204
1205    pub fn set_idx(&mut self, idx: usize, val: Dynamic) {
1206        match self {
1207            Self::List(list) => {
1208                list.write().unwrap().get_mut(idx).map(|l| *l = val);
1209            }
1210            Self::VecI8(vec) => vec.set(idx, val.try_into().unwrap()),
1211            Self::VecU16(vec) => vec.set(idx, val.try_into().unwrap()),
1212            Self::VecI16(vec) => vec.set(idx, val.try_into().unwrap()),
1213            Self::VecU32(vec) => vec.set(idx, val.try_into().unwrap()),
1214            Self::VecI32(vec) => vec.set(idx, val.try_into().unwrap()),
1215            Self::VecF32(vec) => vec.set(idx, val.try_into().unwrap()),
1216            Self::VecI64(vec) => vec[idx] = val.try_into().unwrap(),
1217            Self::VecU64(vec) => vec[idx] = val.try_into().unwrap(),
1218            Self::VecF64(vec) => vec[idx] = val.try_into().unwrap(),
1219            Self::Struct { addr, ty } => {
1220                if let Type::Struct { params: _, fields } = ty.clone()
1221                    && let Some((_, field_ty)) = fields.get(idx)
1222                {
1223                    Self::write_struct_field(*addr, idx, field_ty, &ty, val);
1224                }
1225            }
1226            _ => {}
1227        }
1228    }
1229
1230    pub fn to_markdown(&self) -> String {
1231        let mut s = String::new();
1232        if let Self::Map(m) = self {
1233            for (key, v) in m.read().unwrap().iter() {
1234                s.push_str(&format!("#### ```{}```\n", key));
1235                s.push_str(&v.to_markdown());
1236                s.push('\n');
1237            }
1238        } else if let Self::Bytes(bytes) = self {
1239            s = format!("[{}...]", hex::encode(&bytes[..8]));
1240        } else {
1241            let len = self.len();
1242            if len > 0 {
1243                for idx in 0..len {
1244                    s.push_str(&format!("- {}\n", self.get_idx(idx).unwrap().to_markdown()));
1245                }
1246            } else {
1247                s = self.to_string();
1248            }
1249        }
1250        s
1251    }
1252}
1253
1254#[macro_export]
1255macro_rules! assert_ok {
1256    ( $x: expr, $ok: expr) => {
1257        if $x {
1258            return Ok($ok);
1259        }
1260    };
1261}
1262
1263#[macro_export]
1264macro_rules! assert_err {
1265    ( $x: expr, $err: expr) => {
1266        if $x {
1267            return Err($err);
1268        }
1269    };
1270}
1271
1272pub struct ZOnce {
1273    first: Option<&'static str>,
1274    other: &'static str,
1275}
1276
1277impl ZOnce {
1278    pub fn new(first: &'static str, other: &'static str) -> Self {
1279        Self { first: Some(first), other }
1280    }
1281    pub fn take(&mut self) -> &'static str {
1282        self.first.take().unwrap_or(self.other)
1283    }
1284}
1285
1286mod fixvec;
1287pub use fixvec::FixVec;
1288mod msgpack;
1289pub use msgpack::{MsgPack, MsgUnpack};
1290
1291pub use json::{FromJson, ToJson};
1292
1293mod ops;
1294mod types;
1295pub use types::{ConstIntOp, Type, call_fn};
1296
1297#[macro_export]
1298macro_rules! list {
1299    ($($v:expr),+ $(,)?) => {{
1300        let mut list = Vec::new();
1301        $( let _ = list.push(Dynamic::from($v)); )*
1302        Dynamic::List(std::sync::Arc::new(std::sync::RwLock::new(list)))
1303    }};
1304}
1305
1306#[macro_export]
1307macro_rules! map {
1308    ($($k:expr => $v:expr), *) => {{
1309        let mut obj = std::collections::BTreeMap::new();
1310        $( let _ = obj.insert(smol_str::SmolStr::from($k), Dynamic::from($v)); )*
1311        Dynamic::Map(std::sync::Arc::new(std::sync::RwLock::new(obj)))
1312    }};
1313}