Skip to main content

dynamic/
lib.rs

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