Skip to main content

dynamic/
lib.rs

1use bytemuck::{AnyBitPattern, NoUninit, cast_slice, cast_slice_mut};
2use half::f16;
3use indexmap::IndexMap;
4use smol_str::SmolStr;
5use std::any::Any;
6use std::collections::BTreeMap;
7use std::mem;
8use tinyvec::TinyVec;
9const TINY_SIZE: usize = 28;
10pub mod json;
11
12/// IEEE 754 half-precision bits -> f64. Delegates to `half::f16` for proper
13/// signaling NaN, subnormal, and rounding semantics.
14#[inline]
15pub fn f16_to_f64(bits: u16) -> f64 {
16    f16::from_bits(bits).to_f64()
17}
18
19/// f64 -> IEEE 754 half-precision bits, via `half::f16`.
20#[inline]
21pub fn f64_to_f16(value: f64) -> u16 {
22    f16::from_f64(value).to_bits()
23}
24#[derive(Debug, Default, Clone, PartialEq)]
25pub struct MyVec<T> {
26    pub(crate) data: TinyVec<[u8; TINY_SIZE]>,
27    phantom: std::marker::PhantomData<T>,
28}
29
30impl<T> MyVec<T> {
31    pub fn len(&self) -> usize {
32        self.data.len() / mem::size_of::<T>()
33    }
34
35    pub fn is_empty(&self) -> bool {
36        self.data.is_empty()
37    }
38
39    pub fn as_slice(&self) -> &[u8] {
40        self.data.as_slice()
41    }
42}
43
44impl<T: NoUninit + AnyBitPattern> MyVec<T> {
45    pub fn push(&mut self, value: T) {
46        let binding = [value];
47        let bytes = cast_slice(&binding);
48        self.data.extend_from_slice(bytes);
49    }
50
51    pub fn pop(&mut self) -> Option<T>
52    where
53        T: AnyBitPattern,
54    {
55        if self.data.len() < mem::size_of::<T>() {
56            return None;
57        }
58        let start = self.data.len() - mem::size_of::<T>();
59        let slice = &self.data[start..];
60        let value = cast_slice::<u8, T>(slice)[0];
61        self.data.truncate(start);
62        Some(value)
63    }
64
65    pub fn get(&self, idx: usize) -> Option<T> {
66        if idx >= self.len() {
67            return None;
68        }
69        let start = idx * mem::size_of::<T>();
70        let slice = &self.data[start..start + mem::size_of::<T>()];
71        Some(cast_slice::<u8, T>(slice)[0])
72    }
73
74    pub fn set(&mut self, idx: usize, value: T) {
75        if idx < self.len() {
76            let start = idx * mem::size_of::<T>();
77            let slice = &mut self.data[start..start + mem::size_of::<T>()];
78            cast_slice_mut::<u8, T>(slice)[0] = value;
79        }
80    }
81
82    pub fn iter(&self) -> Iter<'_, T> {
83        Iter { data: self.data.as_slice(), index: 0, phantom: std::marker::PhantomData }
84    }
85    pub fn extend_from_slice(&mut self, slice: &[T]) {
86        self.data.extend_from_slice(cast_slice(slice));
87    }
88}
89
90impl<T: NoUninit> From<&[T]> for MyVec<T> {
91    fn from(vec: &[T]) -> Self {
92        let mut data: TinyVec<[u8; TINY_SIZE]> = TinyVec::new();
93        data.extend_from_slice(cast_slice(vec));
94        Self { data, phantom: std::marker::PhantomData }
95    }
96}
97
98impl<T: NoUninit, const N: usize> From<[T; N]> for MyVec<T> {
99    fn from(arr: [T; N]) -> Self {
100        Self::from(&arr[..])
101    }
102}
103
104impl<T: AnyBitPattern> From<MyVec<T>> for Vec<T> {
105    fn from(my_vec: MyVec<T>) -> Self {
106        cast_slice(my_vec.data.as_slice()).to_vec()
107    }
108}
109
110pub struct Iter<'a, T> {
111    data: &'a [u8],
112    index: usize,
113    phantom: std::marker::PhantomData<T>,
114}
115
116impl<'a, T: AnyBitPattern> Iterator for Iter<'a, T> {
117    type Item = &'a T;
118    fn next(&mut self) -> Option<Self::Item> {
119        let size = std::mem::size_of::<T>();
120        let start = self.index * size;
121
122        if start + size > self.data.len() {
123            return None;
124        }
125
126        let slice = &self.data[start..start + size];
127        let value = &cast_slice::<u8, T>(slice)[0];
128        self.index += 1;
129        Some(value)
130    }
131
132    fn size_hint(&self) -> (usize, Option<usize>) {
133        let remaining = self.data.len() / std::mem::size_of::<T>() - self.index;
134        (remaining, Some(remaining))
135    }
136}
137
138impl<'a, T: AnyBitPattern> ExactSizeIterator for Iter<'a, T> {
139    fn len(&self) -> usize {
140        self.data.len() / std::mem::size_of::<T>() - self.index
141    }
142}
143
144#[derive(Debug, thiserror::Error)]
145pub enum DynamicErr {
146    #[error("type mismatch")]
147    TypeMismatch,
148    #[error("range error: {0}")]
149    Range(i64),
150    #[error("没有成员: {0}")]
151    NoField(SmolStr),
152    #[error("out of range")]
153    OutOfRange,
154}
155
156pub use parking_lot::RwLock;
157use std::sync::Arc;
158
159pub trait CustomProperty: Any + Send + Sync {
160    fn get_key(&self, key: &str) -> Option<Dynamic>;
161
162    fn set_key(&self, key: &str, value: Dynamic) -> bool;
163
164    fn contains_key(&self, key: &str) -> bool {
165        self.get_key(key).is_some()
166    }
167}
168
169#[derive(Clone)]
170pub struct CustomValue {
171    type_name: &'static str,
172    value: Arc<dyn Any + Send + Sync>,
173    get_key: Option<fn(&(dyn Any + Send + Sync), &str) -> Option<Dynamic>>,
174    set_key: Option<fn(&(dyn Any + Send + Sync), &str, Dynamic) -> bool>,
175    contains_key: Option<fn(&(dyn Any + Send + Sync), &str) -> bool>,
176}
177
178impl CustomValue {
179    pub fn new<T>(value: T) -> Self
180    where
181        T: Any + Send + Sync + 'static,
182    {
183        Self { type_name: std::any::type_name::<T>(), value: Arc::new(value), get_key: None, set_key: None, contains_key: None }
184    }
185
186    pub fn from_arc<T>(value: Arc<T>) -> Self
187    where
188        T: Any + Send + Sync + 'static,
189    {
190        Self { type_name: std::any::type_name::<T>(), value, get_key: None, set_key: None, contains_key: None }
191    }
192
193    pub fn new_with_properties<T>(value: T) -> Self
194    where
195        T: CustomProperty + 'static,
196    {
197        Self::from_property_arc(Arc::new(value))
198    }
199
200    pub fn from_property_arc<T>(value: Arc<T>) -> Self
201    where
202        T: CustomProperty + 'static,
203    {
204        fn get_key<T: CustomProperty + 'static>(value: &(dyn Any + Send + Sync), key: &str) -> Option<Dynamic> {
205            value.downcast_ref::<T>()?.get_key(key)
206        }
207
208        fn set_key<T: CustomProperty + 'static>(value: &(dyn Any + Send + Sync), key: &str, next: Dynamic) -> bool {
209            value.downcast_ref::<T>().is_some_and(|value| value.set_key(key, next))
210        }
211
212        fn contains_key<T: CustomProperty + 'static>(value: &(dyn Any + Send + Sync), key: &str) -> bool {
213            value.downcast_ref::<T>().is_some_and(|value| value.contains_key(key))
214        }
215
216        Self { type_name: std::any::type_name::<T>(), value, get_key: Some(get_key::<T>), set_key: Some(set_key::<T>), contains_key: Some(contains_key::<T>) }
217    }
218
219    pub fn as_any(&self) -> &(dyn Any + Send + Sync) {
220        self.value.as_ref()
221    }
222
223    pub fn custom_type_name(&self) -> &'static str {
224        self.type_name
225    }
226
227    fn ptr_eq(&self, other: &Self) -> bool {
228        Arc::ptr_eq(&self.value, &other.value)
229    }
230
231    fn get_key(&self, key: &str) -> Option<Dynamic> {
232        self.get_key.and_then(|get_key| get_key(self.as_any(), key))
233    }
234
235    fn set_key(&self, key: &str, value: Dynamic) -> bool {
236        self.set_key.is_some_and(|set_key| set_key(self.as_any(), key, value))
237    }
238
239    fn contains_key(&self, key: &str) -> bool {
240        self.contains_key.is_some_and(|contains_key| contains_key(self.as_any(), key))
241    }
242}
243
244impl std::fmt::Debug for CustomValue {
245    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
246        f.debug_struct("CustomValue").field("type_name", &self.type_name).finish()
247    }
248}
249
250#[derive(Debug)]
251pub struct StructBytes {
252    bytes: RwLock<Vec<u8>>,
253    dynamic_fields: RwLock<BTreeMap<usize, Box<Dynamic>>>,
254}
255
256impl StructBytes {
257    fn new(size: usize) -> Arc<Self> {
258        Arc::new(Self { bytes: RwLock::new(vec![0; size]), dynamic_fields: RwLock::new(BTreeMap::new()) })
259    }
260
261    fn addr(&self) -> usize {
262        self.bytes.read().as_ptr() as usize
263    }
264
265    fn copy_from_ptr(addr: usize, ty: &Type) -> Arc<Self> {
266        let size = ty.storage_width() as usize;
267        let storage = Self::new(size);
268        if addr != 0 && size > 0 {
269            unsafe {
270                std::ptr::copy_nonoverlapping(addr as *const u8, storage.addr() as *mut u8, size);
271            }
272            storage.clone_dynamic_fields_from(addr, ty, 0);
273        }
274        storage
275    }
276
277    fn clone_dynamic_fields_from(&self, src_addr: usize, ty: &Type, dst_offset: usize) {
278        match ty {
279            Type::Bool | Type::I8 | Type::U8 | Type::I16 | Type::U16 | Type::I32 | Type::U32 | Type::I64 | Type::U64 | Type::F16 | Type::F32 | Type::F64 | Type::Void => {}
280            Type::Struct { fields, .. } => {
281                let (_, offsets) = Type::struct_layout(fields);
282                for ((_, field_ty), offset) in fields.iter().zip(offsets) {
283                    self.clone_dynamic_fields_from(src_addr + offset as usize, field_ty, dst_offset + offset as usize);
284                }
285            }
286            Type::Array(elem_ty, len) | Type::Vec(elem_ty, len) => {
287                let width = elem_ty.storage_width() as usize;
288                for idx in 0..*len as usize {
289                    self.clone_dynamic_fields_from(src_addr + idx * width, elem_ty, dst_offset + idx * width);
290                }
291            }
292            _ => {
293                let ptr = unsafe { std::ptr::read_unaligned(src_addr as *const usize) };
294                if ptr != 0 {
295                    let value = unsafe { (&*(ptr as *const Dynamic)).deep_clone() };
296                    self.write_dynamic_ptr_at(dst_offset, value);
297                }
298            }
299        }
300    }
301
302    fn clear_dynamic_fields_in(&self, start: usize, width: usize) {
303        let end = start.saturating_add(width);
304        self.dynamic_fields.write().retain(|offset, _| *offset < start || *offset >= end);
305    }
306
307    fn read_dynamic_ptr_at(&self, offset: usize) -> Option<Dynamic> {
308        if let Some(value) = self.dynamic_fields.read().get(&offset) {
309            return Some(value.as_ref().clone());
310        }
311        let ptr = unsafe { std::ptr::read_unaligned((self.addr() + offset) as *const usize) };
312        if ptr == 0 { None } else { Some(unsafe { (&*(ptr as *const Dynamic)).clone() }) }
313    }
314
315    fn write_dynamic_ptr_at(&self, offset: usize, value: Dynamic) {
316        let mut boxed = Box::new(value);
317        let ptr = boxed.as_mut() as *mut Dynamic as usize;
318        self.dynamic_fields.write().insert(offset, boxed);
319        unsafe {
320            std::ptr::write_unaligned((self.addr() + offset) as *mut usize, ptr);
321        }
322    }
323}
324
325#[derive(Debug, Default, Clone)]
326pub enum Dynamic {
327    #[default]
328    Null,
329    Bool(bool),
330    U8(u8),
331    I8(i8),
332    U16(u16),
333    I16(i16),
334    U32(u32),
335    I32(i32), //默认整数类型
336    U64(u64),
337    I64(i64),
338    F16(u16), //IEEE 754 half-precision bits
339    F32(f32), //默认浮点类型
340    F64(f64),
341    String(SmolStr),
342    StringBuf(String),
343    Bytes(Vec<u8>),
344    VecI8(MyVec<i8>),
345    VecU16(MyVec<u16>),
346    VecI16(MyVec<i16>),
347    VecU32(MyVec<u32>),
348    VecI32(MyVec<i32>),
349    VecF32(MyVec<f32>),
350    VecU64(Vec<u64>),
351    VecI64(Vec<i64>),
352    VecF64(Vec<f64>),
353    List(Arc<RwLock<Vec<Dynamic>>>),
354    Map(Arc<RwLock<IndexMap<SmolStr, Dynamic>>>),
355    StructView {
356        addr: usize,
357        ty: Arc<Type>,
358    },
359    StructOwned {
360        storage: Arc<StructBytes>,
361        ty: Arc<Type>,
362    },
363    Custom(Box<CustomValue>),
364    Iter {
365        idx: usize,
366        keys: Vec<SmolStr>,
367        value: Box<Dynamic>,
368    },
369}
370
371unsafe impl Send for Dynamic {}
372unsafe impl Sync for Dynamic {}
373
374impl PartialEq for Dynamic {
375    fn eq(&self, other: &Self) -> bool {
376        match (self, other) {
377            (Self::Null, Self::Null) => true,
378            (Self::Bool(a), Self::Bool(b)) => a == b,
379            (a, b) if a.is_str() && b.is_str() => a.as_str() == b.as_str(),
380            (Self::Bytes(a), Self::Bytes(b)) => a == b,
381            // Integer types - compare as i64
382            (Self::U8(a), Self::U8(b)) => a == b,
383            (Self::I8(a), Self::I8(b)) => a == b,
384            (Self::U16(a), Self::U16(b)) => a == b,
385            (Self::I16(a), Self::I16(b)) => a == b,
386            (Self::U32(a), Self::U32(b)) => a == b,
387            (Self::I32(a), Self::I32(b)) => a == b,
388            (Self::U64(a), Self::U64(b)) => a == b,
389            (Self::I64(a), Self::I64(b)) => a == b,
390            // Mixed integer types - compare as i64
391            (a, b) if a.is_int() && b.is_int() => a.as_int() == b.as_int(),
392            // Float types
393            (Self::F16(a), Self::F16(b)) => a == b,
394            (Self::F32(a), Self::F32(b)) => a.to_bits() == b.to_bits(),
395            (Self::F64(a), Self::F64(b)) => a.to_bits() == b.to_bits(),
396            (a, b) if (a.is_f16() || a.is_f32() || a.is_f64()) && (b.is_f16() || b.is_f32() || b.is_f64()) => a.as_float() == b.as_float(),
397            // Typed vectors
398            (Self::VecI8(a), Self::VecI8(b)) => a.data == b.data,
399            (Self::VecU16(a), Self::VecU16(b)) => a.data == b.data,
400            (Self::VecI16(a), Self::VecI16(b)) => a.data == b.data,
401            (Self::VecU32(a), Self::VecU32(b)) => a.data == b.data,
402            (Self::VecI32(a), Self::VecI32(b)) => a.data == b.data,
403            (Self::VecF32(a), Self::VecF32(b)) => a.data == b.data,
404            (Self::VecU64(a), Self::VecU64(b)) => a == b,
405            (Self::VecI64(a), Self::VecI64(b)) => a == b,
406            (Self::VecF64(a), Self::VecF64(b)) => a == b,
407            // List - compare inner values
408            (Self::List(a), Self::List(b)) => {
409                let a_guard = a.read();
410                let b_guard = b.read();
411                if a_guard.len() != b_guard.len() {
412                    return false;
413                }
414                a_guard.iter().zip(b_guard.iter()).all(|(x, y)| x == y)
415            }
416            // Map - compare key-value pairs
417            (Self::Map(a), Self::Map(b)) => {
418                let a_guard = a.read();
419                let b_guard = b.read();
420                if a_guard.len() != b_guard.len() {
421                    return false;
422                }
423                for (k, v) in a_guard.iter() {
424                    if let Some(other_v) = b_guard.get(k) {
425                        if v != other_v {
426                            return false;
427                        }
428                    } else {
429                        return false;
430                    }
431                }
432                true
433            }
434            // StructView compares by address, StructOwned by bytes.
435            (Self::StructView { addr: a_addr, ty: a_ty }, Self::StructView { addr: b_addr, ty: b_ty }) => a_addr == b_addr && a_ty == b_ty,
436            (Self::StructOwned { storage: a, ty: a_ty }, Self::StructOwned { storage: b, ty: b_ty }) => a_ty == b_ty && *a.bytes.read() == *b.bytes.read(),
437            (Self::Custom(a), Self::Custom(b)) => a.ptr_eq(b),
438            _ => false,
439        }
440    }
441}
442
443impl Eq for Dynamic {}
444
445use std::cmp::Ordering;
446
447impl PartialOrd for Dynamic {
448    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
449        Some(self.cmp(other))
450    }
451}
452
453impl Ord for Dynamic {
454    fn cmp(&self, other: &Self) -> Ordering {
455        if self.is_f32() || self.is_f64() || other.is_f32() || other.is_f64() {
456            self.as_float().unwrap_or(0.0).total_cmp(&other.as_float().unwrap_or(0.0))
457        } else if self.is_int() || other.is_int() {
458            self.as_int().unwrap_or(0).cmp(&other.as_int().unwrap_or(0))
459        } else if self.is_uint() || other.is_uint() {
460            self.as_uint().unwrap_or(0).cmp(&other.as_uint().unwrap_or(0))
461        } else if self.is_false() && other.is_true() {
462            Ordering::Less // false < true
463        } else if self.is_true() && other.is_false() {
464            Ordering::Greater // true > false
465        } else if self.is_null() && other.is_null() {
466            Ordering::Equal
467        } else if self.is_str() && other.is_str() {
468            self.as_str().cmp(other.as_str())
469        } else {
470            Ordering::Equal
471        }
472    }
473}
474
475macro_rules! impl_dynamic_scalar {
476    ($variant:ident, $ty:ty) => {
477        impl From<$ty> for Dynamic {
478            fn from(value: $ty) -> Self {
479                Dynamic::$variant(value)
480            }
481        }
482    };
483}
484
485impl_dynamic_scalar!(Bool, bool);
486
487impl_dynamic_scalar!(I8, i8);
488impl_dynamic_scalar!(U16, u16);
489impl_dynamic_scalar!(I16, i16);
490impl_dynamic_scalar!(U32, u32);
491impl_dynamic_scalar!(I32, i32);
492impl_dynamic_scalar!(F32, f32);
493impl_dynamic_scalar!(I64, i64);
494impl_dynamic_scalar!(U64, u64);
495impl_dynamic_scalar!(F64, f64);
496impl_dynamic_scalar!(String, SmolStr);
497impl From<&str> for Dynamic {
498    fn from(s: &str) -> Self {
499        Dynamic::String(s.into())
500    }
501}
502
503macro_rules! impl_try_from_dynamic_int {
504    ($($target:ty),+ $(,)?) => {
505        $(
506            impl TryFrom<Dynamic> for $target {
507                type Error = DynamicErr;
508                fn try_from(value: Dynamic) -> Result<Self, Self::Error> {
509                    match value {
510                        Dynamic::F32(v) => Ok(v as $target),
511                        Dynamic::F64(v) => Ok(v as $target),
512                        Dynamic::String(v) => v.trim().parse::<$target>().or_else(|_| v.trim().parse::<f64>().map(|value| value as $target)).map_err(|_| DynamicErr::TypeMismatch),
513                        Dynamic::StringBuf(v) => v.trim().parse::<$target>().or_else(|_| v.trim().parse::<f64>().map(|value| value as $target)).map_err(|_| DynamicErr::TypeMismatch),
514                        Dynamic::U8(v)  => v.try_into().map_err(|_| DynamicErr::OutOfRange),
515                        Dynamic::U16(v) => v.try_into().map_err(|_| DynamicErr::OutOfRange),
516                        Dynamic::U32(v) => v.try_into().map_err(|_| DynamicErr::OutOfRange),
517                        Dynamic::U64(v) => v.try_into().map_err(|_| DynamicErr::OutOfRange),
518                        Dynamic::I8(v)  => v.try_into().map_err(|_| DynamicErr::OutOfRange),
519                        Dynamic::I16(v) => v.try_into().map_err(|_| DynamicErr::OutOfRange),
520                        Dynamic::I32(v) => v.try_into().map_err(|_| DynamicErr::OutOfRange),
521                        Dynamic::I64(v) => v.try_into().map_err(|_| DynamicErr::OutOfRange),
522                        _ => Err(DynamicErr::TypeMismatch),
523                    }
524                }
525            }
526        )+
527    };
528}
529impl_try_from_dynamic_int!(u8, u16, u32, u64, i8, i16, i32, i64);
530
531impl TryFrom<Dynamic> for f64 {
532    type Error = DynamicErr;
533    fn try_from(value: Dynamic) -> Result<Self, Self::Error> {
534        match value {
535            Dynamic::F32(v) => Ok(v as f64),
536            Dynamic::F64(v) => Ok(v),
537            Dynamic::U8(v) => Ok(v as f64),
538            Dynamic::U16(v) => Ok(v as f64),
539            Dynamic::U32(v) => Ok(v as f64),
540            Dynamic::U64(v) => Ok(v as f64),
541            Dynamic::I8(v) => Ok(v as f64),
542            Dynamic::I16(v) => Ok(v as f64),
543            Dynamic::I32(v) => Ok(v as f64),
544            Dynamic::I64(v) => Ok(v as f64),
545            Dynamic::String(v) => v.trim().parse::<f64>().map_err(|_| DynamicErr::TypeMismatch),
546            Dynamic::StringBuf(v) => v.trim().parse::<f64>().map_err(|_| DynamicErr::TypeMismatch),
547            _ => Err(DynamicErr::TypeMismatch),
548        }
549    }
550}
551
552impl TryFrom<Dynamic> for f32 {
553    type Error = DynamicErr;
554    fn try_from(value: Dynamic) -> Result<Self, Self::Error> {
555        match value {
556            Dynamic::F32(v) => Ok(v),
557            Dynamic::F64(v) => Ok(v as f32),
558            Dynamic::U8(v) => Ok(v as f32),
559            Dynamic::U16(v) => Ok(v as f32),
560            Dynamic::U32(v) => Ok(v as f32),
561            Dynamic::U64(v) => Ok(v as f32),
562            Dynamic::I8(v) => Ok(v as f32),
563            Dynamic::I16(v) => Ok(v as f32),
564            Dynamic::I32(v) => Ok(v as f32),
565            Dynamic::I64(v) => Ok(v as f32),
566            Dynamic::String(v) => v.trim().parse::<f32>().map_err(|_| DynamicErr::TypeMismatch),
567            Dynamic::StringBuf(v) => v.trim().parse::<f32>().map_err(|_| DynamicErr::TypeMismatch),
568            _ => Err(DynamicErr::TypeMismatch),
569        }
570    }
571}
572
573impl TryFrom<Dynamic> for bool {
574    type Error = DynamicErr;
575    fn try_from(value: Dynamic) -> Result<Self, Self::Error> {
576        match value {
577            Dynamic::Bool(v) => Ok(v),
578            Dynamic::U8(v) => Ok(v != 0),
579            Dynamic::U16(v) => Ok(v != 0),
580            Dynamic::U32(v) => Ok(v != 0),
581            Dynamic::U64(v) => Ok(v != 0),
582            Dynamic::I8(v) => Ok(v != 0),
583            Dynamic::I16(v) => Ok(v != 0),
584            Dynamic::I32(v) => Ok(v != 0),
585            Dynamic::I64(v) => Ok(v != 0),
586            _ => Err(DynamicErr::TypeMismatch),
587        }
588    }
589}
590
591impl TryFrom<Dynamic> for SmolStr {
592    type Error = DynamicErr;
593    fn try_from(value: Dynamic) -> Result<Self, Self::Error> {
594        match value {
595            Dynamic::String(s) => Ok(s),
596            Dynamic::StringBuf(s) => Ok(s.into()),
597            _ => Err(DynamicErr::TypeMismatch),
598        }
599    }
600}
601
602macro_rules! impl_dynamic_vec_from_slice {
603    ($variant:ident, $ty:ty) => {
604        impl From<&[$ty]> for Dynamic {
605            fn from(vec: &[$ty]) -> Self {
606                Dynamic::$variant(MyVec::from(vec))
607            }
608        }
609
610        impl<const N: usize> From<[$ty; N]> for Dynamic {
611            fn from(vec: [$ty; N]) -> Self {
612                Dynamic::$variant(MyVec::from(vec))
613            }
614        }
615    };
616}
617
618impl_dynamic_vec_from_slice!(VecI8, i8);
619impl_dynamic_vec_from_slice!(VecU16, u16);
620impl_dynamic_vec_from_slice!(VecI16, i16);
621impl_dynamic_vec_from_slice!(VecU32, u32);
622impl_dynamic_vec_from_slice!(VecI32, i32);
623impl_dynamic_vec_from_slice!(VecF32, f32);
624
625impl From<&[u8]> for Dynamic {
626    fn from(vec: &[u8]) -> Self {
627        Dynamic::Bytes(vec.to_vec())
628    }
629}
630
631impl From<Vec<u8>> for Dynamic {
632    fn from(vec: Vec<u8>) -> Self {
633        Dynamic::Bytes(vec)
634    }
635}
636
637impl From<&[u64]> for Dynamic {
638    fn from(vec: &[u64]) -> Self {
639        Dynamic::VecU64(vec.to_vec())
640    }
641}
642
643impl<const N: usize> From<[u64; N]> for Dynamic {
644    fn from(vec: [u64; N]) -> Self {
645        Dynamic::VecU64(vec.to_vec())
646    }
647}
648
649impl From<&[i64]> for Dynamic {
650    fn from(vec: &[i64]) -> Self {
651        Dynamic::VecI64(vec.to_vec())
652    }
653}
654impl<const N: usize> From<[i64; N]> for Dynamic {
655    fn from(vec: [i64; N]) -> Self {
656        Dynamic::VecI64(vec.to_vec())
657    }
658}
659
660impl From<&[f64]> for Dynamic {
661    fn from(vec: &[f64]) -> Self {
662        Dynamic::VecF64(vec.to_vec())
663    }
664}
665impl<const N: usize> From<[f64; N]> for Dynamic {
666    fn from(vec: [f64; N]) -> Self {
667        Dynamic::VecF64(vec.to_vec())
668    }
669}
670
671impl<T: Into<Dynamic>> From<Vec<T>> for Dynamic {
672    fn from(vec: Vec<T>) -> Self {
673        let vec = vec.into_iter().map(|v| v.into()).collect();
674        Dynamic::List(Arc::new(RwLock::new(vec)))
675    }
676}
677
678impl From<String> for Dynamic {
679    fn from(s: String) -> Self {
680        Dynamic::String(s.into())
681    }
682}
683
684impl ToString for Dynamic {
685    fn to_string(&self) -> String {
686        match self {
687            Self::Null => "()".into(),
688            Self::Bool(b) => {
689                if *b {
690                    "true".into()
691                } else {
692                    "false".into()
693                }
694            }
695            Self::U8(u) => u.to_string(),
696            Self::U16(u) => u.to_string(),
697            Self::U32(u) => u.to_string(),
698            Self::U64(u) => u.to_string(),
699            Self::I8(u) => u.to_string(),
700            Self::I16(u) => u.to_string(),
701            Self::I32(u) => u.to_string(),
702            Self::I64(u) => u.to_string(),
703            Self::F32(u) => u.to_string(),
704            Self::F64(u) => u.to_string(),
705            Self::String(s) => s.to_string(),
706            Self::StringBuf(s) => s.clone(),
707            _ => {
708                let mut buf = String::new();
709                self.to_json(&mut buf);
710                if buf.is_empty() { format!("{:?}", self) } else { buf }
711            }
712        }
713    }
714}
715
716use anyhow::Result;
717impl Dynamic {
718    pub fn custom<T>(value: T) -> Self
719    where
720        T: Any + Send + Sync + 'static,
721    {
722        Self::Custom(Box::new(CustomValue::new(value)))
723    }
724
725    pub fn custom_arc<T>(value: Arc<T>) -> Self
726    where
727        T: Any + Send + Sync + 'static,
728    {
729        Self::Custom(Box::new(CustomValue::from_arc(value)))
730    }
731
732    pub fn custom_with_properties<T>(value: T) -> Self
733    where
734        T: CustomProperty + 'static,
735    {
736        Self::Custom(Box::new(CustomValue::new_with_properties(value)))
737    }
738
739    pub fn custom_property_arc<T>(value: Arc<T>) -> Self
740    where
741        T: CustomProperty + 'static,
742    {
743        Self::Custom(Box::new(CustomValue::from_property_arc(value)))
744    }
745
746    pub fn is_custom(&self) -> bool {
747        matches!(self, Self::Custom(_))
748    }
749
750    pub fn custom_type_name(&self) -> Option<&'static str> {
751        if let Self::Custom(value) = self { Some(value.custom_type_name()) } else { None }
752    }
753
754    pub fn as_custom<T>(&self) -> Option<&T>
755    where
756        T: Any + Send + Sync,
757    {
758        if let Self::Custom(value) = self { value.as_any().downcast_ref::<T>() } else { None }
759    }
760
761    pub fn deep_clone(&self) -> Self {
762        match self {
763            Self::Map(m) => {
764                let m = m.read().iter().map(|(k, v)| (k.clone(), v.deep_clone())).collect();
765                Self::map(m)
766            }
767            Self::List(l) => {
768                let l = l.read().iter().map(|item| item.deep_clone()).collect();
769                Self::list(l)
770            }
771            Self::StructView { addr, ty } => Self::owned_struct_from_ptr(*addr, ty.as_ref().clone()),
772            Self::StructOwned { storage, ty } => Self::owned_struct_from_ptr(storage.addr(), ty.as_ref().clone()),
773            _ => self.clone(),
774        }
775    }
776
777    pub fn struct_view(addr: usize, ty: Type) -> Self {
778        Self::StructView { addr, ty: Arc::new(ty) }
779    }
780
781    pub fn owned_struct_from_ptr(addr: usize, ty: Type) -> Self {
782        Self::StructOwned { storage: StructBytes::copy_from_ptr(addr, &ty), ty: Arc::new(ty) }
783    }
784
785    fn struct_addr_ty(&self) -> Option<(usize, &Type)> {
786        match self {
787            Self::StructView { addr, ty } => Some((*addr, ty.as_ref())),
788            Self::StructOwned { storage, ty } => Some((storage.addr(), ty.as_ref())),
789            _ => None,
790        }
791    }
792
793    fn struct_storage(&self) -> Option<&StructBytes> {
794        match self {
795            Self::StructOwned { storage, .. } => Some(storage),
796            _ => None,
797        }
798    }
799
800    pub fn add(&mut self, val: i64) -> Option<i64> {
801        // 如果是 整数类型 增加指定值 并返回新的值 不考虑溢出
802        // 关键不变量:返回 Some(n) 时,*self 的实际值 == n(没有"写入截断但返回溢出值"的不一致 bug)。
803        // 原代码 v: i64 = *u as i64 + val 后 *u = v as u8 会静默截断 + 返回不一致;
804        // 这里改用 checked_add_signed:失败时返回 None,不修改 *self。
805        match self {
806            Self::U8(u)  => u.checked_add_signed(val as i8).map(|v| { *u = v; v as i64 }),
807            Self::U16(u) => u.checked_add_signed(val as i16).map(|v| { *u = v; v as i64 }),
808            Self::U32(u) => u.checked_add_signed(val as i32).map(|v| { *u = v; v as i64 }),
809            Self::U64(u) => u.checked_add(val as u64).map(|v| { *u = v; v as i64 }),
810            Self::I8(i)  => i.checked_add(val as i8).map(|v| { *i = v; v as i64 }),
811            Self::I16(i) => i.checked_add(val as i16).map(|v| { *i = v; v as i64 }),
812            Self::I32(i) => i.checked_add(val as i32).map(|v| { *i = v; v as i64 }),
813            Self::I64(i) => i.checked_add(val).map(|v| { *i = v; v }),
814            _ => None,
815        }
816    }
817
818    pub fn is_vec(&self) -> bool {
819        use Dynamic::*;
820        match self {
821            VecI8(_) | VecU16(_) | Self::VecI16(_) | VecU32(_) | VecI32(_) | VecF32(_) | VecU64(_) | VecI64(_) | VecF64(_) => true,
822            _ => false,
823        }
824    }
825
826    pub fn as_bytes(&self) -> Option<&[u8]> {
827        match self {
828            Self::Bytes(b) => Some(b.as_slice()),
829            _ => None,
830        }
831    }
832
833    pub fn as_str(&self) -> &str {
834        match self {
835            Dynamic::String(s) => s.as_str(),
836            Dynamic::StringBuf(s) => s.as_str(),
837            _ => "",
838        }
839    }
840
841    pub fn is_native(&self) -> bool {
842        if self.is_f64() || self.is_f32() || self.is_int() || self.is_true() || self.is_false() { true } else { false }
843    }
844
845    pub fn from_utf8(buf: &[u8]) -> Result<Self> {
846        Ok(Dynamic::from(SmolStr::new(std::str::from_utf8(buf)?)))
847    }
848
849    pub fn append(&self, other: Self) {
850        match (self, other) {
851            (Self::List(left), rhs) => {
852                if let Self::List(right) = rhs {
853                    left.write().append(&mut right.write());
854                } else {
855                    left.write().push(rhs);
856                }
857            }
858            (Self::Map(left), Self::Map(right)) => {
859                left.write().append(&mut right.write());
860            }
861            (_, _) => {}
862        }
863    }
864
865    pub fn into_vec<T: TryFrom<Self> + 'static>(self) -> Option<Vec<T>> {
866        if std::any::TypeId::of::<T>() == std::any::TypeId::of::<Dynamic>() {
867            match self {
868                Dynamic::List(list) => match Arc::try_unwrap(list) {
869                    Ok(vec) => Some(unsafe { mem::transmute::<Vec<Dynamic>, Vec<T>>(vec.into_inner()) }),
870                    Err(_) => None,
871                },
872                _ => {
873                    let mut vec = Vec::with_capacity(self.len());
874                    for idx in 0..self.len() {
875                        if let Some(item) = self.get_idx(idx) {
876                            vec.push(item);
877                        }
878                    }
879                    Some(unsafe { mem::transmute(vec) })
880                }
881            }
882        } else {
883            match self {
884                Dynamic::List(list) => Arc::try_unwrap(list).ok().map(|l| l.into_inner().into_iter().filter_map(|l| T::try_from(l).ok()).collect()),
885                Dynamic::Bytes(vec) => {
886                    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u8>() {
887                        let bytes_vec: Vec<u8> = Vec::from(vec);
888                        Some(unsafe { mem::transmute(bytes_vec) })
889                    } else {
890                        None
891                    }
892                }
893                Dynamic::VecI8(vec) => {
894                    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i8>() {
895                        let vec_i8: Vec<i8> = Vec::from(vec);
896                        Some(unsafe { mem::transmute(vec_i8) })
897                    } else {
898                        None
899                    }
900                }
901                Dynamic::VecU16(vec) => {
902                    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u16>() {
903                        let vec_u16: Vec<u16> = Vec::from(vec);
904                        Some(unsafe { mem::transmute(vec_u16) })
905                    } else {
906                        None
907                    }
908                }
909                Dynamic::VecI16(vec) => {
910                    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i16>() {
911                        let vec_i16: Vec<i16> = Vec::from(vec);
912                        Some(unsafe { mem::transmute(vec_i16) })
913                    } else {
914                        None
915                    }
916                }
917                Dynamic::VecU32(vec) => {
918                    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u32>() {
919                        let vec_u32: Vec<u32> = Vec::from(vec);
920                        Some(unsafe { mem::transmute(vec_u32) })
921                    } else {
922                        None
923                    }
924                }
925                Dynamic::VecI32(vec) => {
926                    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i32>() {
927                        let vec_i32: Vec<i32> = Vec::from(vec);
928                        Some(unsafe { mem::transmute(vec_i32) })
929                    } else {
930                        None
931                    }
932                }
933                Dynamic::VecF32(vec) => {
934                    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<f32>() {
935                        let vec_f32: Vec<f32> = Vec::from(vec);
936                        Some(unsafe { mem::transmute(vec_f32) })
937                    } else {
938                        None
939                    }
940                }
941                Dynamic::VecU64(vec) => {
942                    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u64>() {
943                        Some(unsafe { mem::transmute(vec) })
944                    } else {
945                        None
946                    }
947                }
948                Dynamic::VecI64(vec) => {
949                    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i64>() {
950                        Some(unsafe { mem::transmute(vec) })
951                    } else {
952                        None
953                    }
954                }
955                Dynamic::VecF64(vec) => {
956                    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<f64>() {
957                        Some(unsafe { mem::transmute(vec) })
958                    } else {
959                        None
960                    }
961                }
962                _ => None,
963            }
964        }
965    }
966
967    pub fn push<T: Into<Dynamic> + 'static>(&mut self, value: T) -> bool {
968        match self {
969            Self::List(list) => {
970                list.write().push(value.into());
971                true
972            }
973            Self::Bytes(vec) => {
974                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u8>() {
975                    vec.push(unsafe { mem::transmute_copy(&value) });
976                    true
977                } else {
978                    false
979                }
980            }
981            Self::VecI8(vec) => {
982                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i8>() {
983                    vec.push(unsafe { mem::transmute_copy(&value) });
984                    true
985                } else {
986                    false
987                }
988            }
989            Self::VecU16(vec) => {
990                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u16>() {
991                    vec.push(unsafe { mem::transmute_copy(&value) });
992                    true
993                } else {
994                    false
995                }
996            }
997            Self::VecI16(vec) => {
998                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i16>() {
999                    vec.push(unsafe { mem::transmute_copy(&value) });
1000                    true
1001                } else {
1002                    false
1003                }
1004            }
1005            Self::VecU32(vec) => {
1006                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u32>() {
1007                    vec.push(unsafe { mem::transmute_copy(&value) });
1008                    true
1009                } else {
1010                    false
1011                }
1012            }
1013            Self::VecI32(vec) => {
1014                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i32>() {
1015                    vec.push(unsafe { mem::transmute_copy(&value) });
1016                    true
1017                } else {
1018                    false
1019                }
1020            }
1021            Self::VecF32(vec) => {
1022                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<f32>() {
1023                    vec.push(unsafe { mem::transmute_copy(&value) });
1024                    true
1025                } else {
1026                    false
1027                }
1028            }
1029            Self::VecU64(vec) => {
1030                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u64>() {
1031                    vec.push(unsafe { mem::transmute_copy(&value) });
1032                    true
1033                } else {
1034                    false
1035                }
1036            }
1037            Self::VecI64(vec) => {
1038                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i64>() {
1039                    vec.push(unsafe { mem::transmute_copy(&value) });
1040                    true
1041                } else {
1042                    false
1043                }
1044            }
1045            Self::VecF64(vec) => {
1046                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<f64>() {
1047                    vec.push(unsafe { mem::transmute_copy(&value) });
1048                    true
1049                } else {
1050                    false
1051                }
1052            }
1053            _ => false,
1054        }
1055    }
1056
1057    pub fn push_dynamic(&mut self, value: Dynamic) -> bool {
1058        match self {
1059            Self::List(list) => {
1060                list.write().push(value);
1061                true
1062            }
1063            Self::Bytes(vec) => value.try_into().map(|value| vec.push(value)).is_ok(),
1064            Self::VecI8(vec) => value.try_into().map(|value| vec.push(value)).is_ok(),
1065            Self::VecU16(vec) => value.try_into().map(|value| vec.push(value)).is_ok(),
1066            Self::VecI16(vec) => value.try_into().map(|value| vec.push(value)).is_ok(),
1067            Self::VecU32(vec) => value.try_into().map(|value| vec.push(value)).is_ok(),
1068            Self::VecI32(vec) => value.try_into().map(|value| vec.push(value)).is_ok(),
1069            Self::VecF32(vec) => value.try_into().map(|value| vec.push(value)).is_ok(),
1070            Self::VecU64(vec) => value.try_into().map(|value| vec.push(value)).is_ok(),
1071            Self::VecI64(vec) => value.try_into().map(|value| vec.push(value)).is_ok(),
1072            Self::VecF64(vec) => value.try_into().map(|value| vec.push(value)).is_ok(),
1073            _ => false,
1074        }
1075    }
1076
1077    pub fn pop(&mut self) -> Option<Dynamic> {
1078        match self {
1079            Self::List(list) => list.write().pop(),
1080            Self::Bytes(vec) => vec.pop().map(Dynamic::U8),
1081            Self::VecI8(vec) => vec.pop().map(Dynamic::I8),
1082            Self::VecU16(vec) => vec.pop().map(Dynamic::U16),
1083            Self::VecI16(vec) => vec.pop().map(Dynamic::I16),
1084            Self::VecU32(vec) => vec.pop().map(Dynamic::U32),
1085            Self::VecI32(vec) => vec.pop().map(Dynamic::I32),
1086            Self::VecF32(vec) => vec.pop().map(Dynamic::F32),
1087            Self::VecU64(vec) => vec.pop().map(Dynamic::U64),
1088            Self::VecI64(vec) => vec.pop().map(Dynamic::I64),
1089            Self::VecF64(vec) => vec.pop().map(Dynamic::F64),
1090            _ => None,
1091        }
1092    }
1093
1094    pub fn is_null(&self) -> bool {
1095        match self {
1096            Self::Null => true,
1097            _ => false,
1098        }
1099    }
1100
1101    pub fn as_bool(&self) -> Option<bool> {
1102        if let Self::Bool(b) = self { Some(*b) } else { None }
1103    }
1104
1105    pub fn is_true(&self) -> bool {
1106        match self {
1107            Self::Bool(b) => *b,
1108            _ => false,
1109        }
1110    }
1111
1112    pub fn is_false(&self) -> bool {
1113        match self {
1114            Self::Bool(b) => !*b,
1115            _ => false,
1116        }
1117    }
1118
1119    pub fn is_int(&self) -> bool {
1120        match self {
1121            Self::I8(_) | Self::I16(_) | Self::I32(_) | Self::I64(_) => true,
1122            Self::U8(_) | Self::U16(_) | Self::U32(_) | Self::U64(_) => true,
1123            _ => false,
1124        }
1125    }
1126
1127    pub fn as_int(&self) -> Option<i64> {
1128        match self {
1129            Self::U8(u) => Some(*u as i64),
1130            Self::U16(u) => Some(*u as i64),
1131            Self::U32(u) => Some(*u as i64),
1132            Self::U64(u) => i64::try_from(*u).ok(),
1133            Self::I8(i) => Some(*i as i64),
1134            Self::I16(i) => Some(*i as i64),
1135            Self::I32(i) => Some(*i as i64),
1136            Self::I64(i) => Some(*i as i64),
1137            _ => None,
1138        }
1139    }
1140
1141    pub fn is_uint(&self) -> bool {
1142        match self {
1143            Self::U8(_) | Self::U16(_) | Self::U32(_) | Self::U64(_) => true,
1144            _ => false,
1145        }
1146    }
1147
1148    pub fn as_uint(&self) -> Option<u64> {
1149        match self {
1150            Self::U8(i) => Some(*i as u64),
1151            Self::U16(i) => Some(*i as u64),
1152            Self::U32(i) => Some(*i as u64),
1153            Self::U64(i) => Some(*i as u64),
1154            _ => None,
1155        }
1156    }
1157
1158    pub fn is_f32(&self) -> bool {
1159        if let Self::F32(_) = self { true } else { false }
1160    }
1161
1162    pub fn is_f16(&self) -> bool {
1163        if let Self::F16(_) = self { true } else { false }
1164    }
1165
1166    pub fn is_str(&self) -> bool {
1167        if let Self::String(_) | Self::StringBuf(_) = self { true } else { false }
1168    }
1169
1170    pub fn is_f64(&self) -> bool {
1171        if let Self::F64(_) = self { true } else { false }
1172    }
1173
1174    pub fn as_float(&self) -> Option<f64> {
1175        match self {
1176            Self::U8(u) => Some(*u as f64),
1177            Self::U16(u) => Some(*u as f64),
1178            Self::U32(u) => Some(*u as f64),
1179            Self::U64(u) => Some(*u as f64),
1180            Self::I8(i) => Some(*i as f64),
1181            Self::I16(i) => Some(*i as f64),
1182            Self::I32(i) => Some(*i as f64),
1183            Self::I64(i) => Some(*i as f64),
1184            Self::F16(bits) => Some(f16_to_f64(*bits)),
1185            Self::F32(f) => Some(*f as f64),
1186            Self::F64(f) => Some(*f),
1187            _ => None,
1188        }
1189    }
1190
1191    pub fn is_signed(&self) -> bool {
1192        match self {
1193            Self::I8(_) | Self::I16(_) | Self::I32(_) | Self::I64(_) | Self::F16(_) | Self::F32(_) | Self::F64(_) => true,
1194            _ => false,
1195        }
1196    }
1197
1198    pub fn size_of(&self) -> usize {
1199        match self {
1200            Self::I8(_) | Self::U8(_) => 1,
1201            Self::I16(_) | Self::U16(_) => 2,
1202            Self::I32(_) | Self::U32(_) | Self::F32(_) => 4,
1203            Self::I64(_) | Self::U64(_) | Self::F64(_) => 8,
1204            Self::F16(_) => 2,
1205            Self::String(s) => s.len(),
1206            Self::StringBuf(s) => s.len(),
1207            Self::Bytes(bytes) => bytes.len(),
1208            Self::VecI8(vec) => vec.len(),
1209            Self::VecU16(vec) => vec.len(),
1210            Self::VecI16(vec) => vec.len(),
1211            Self::VecU32(vec) => vec.len(),
1212            Self::VecI32(vec) => vec.len(),
1213            Self::VecF32(vec) => vec.len(),
1214            Self::VecI64(vec) => vec.len(),
1215            Self::VecU64(vec) => vec.len(),
1216            Self::VecF64(vec) => vec.len(),
1217            Self::List(list) => list.read().len(),
1218            Self::Map(obj) => obj.read().len(),
1219            Self::StructView { ty, .. } | Self::StructOwned { ty, .. } => ty.len(),
1220            Self::Custom(_) => 0,
1221            _ => 1,
1222        }
1223    }
1224
1225    pub fn list(v: Vec<Dynamic>) -> Self {
1226        Dynamic::List(Arc::new(RwLock::new(v)))
1227    }
1228
1229    pub fn is_list(&self) -> bool {
1230        match self {
1231            Self::List(_) | Self::VecF32(_) | Self::VecF64(_) | Self::VecI16(_) | Self::VecI32(_) | Self::VecI64(_) | Self::VecU16(_) | Self::VecU32(_) | Self::VecU64(_) => true,
1232            Self::StructView { ty, .. } | Self::StructOwned { ty, .. } => ty.is_array() || ty.is_vec(),
1233            _ => false,
1234        }
1235    }
1236
1237    pub fn split(self, tag: &str) -> Self {
1238        match self {
1239            Self::String(s) => Self::list(s.split(tag).map(|p| Dynamic::from(p)).collect()),
1240            Self::StringBuf(s) => Self::list(s.split(tag).map(|p| Dynamic::from(p)).collect()),
1241            _ => self,
1242        }
1243    }
1244
1245    pub fn map(m: BTreeMap<SmolStr, Dynamic>) -> Self {
1246        // 入参保持 BTreeMap 以兼容已有调用点;底层用 IndexMap(O(1) 访问)。
1247        // BTreeMap 已按 key 排序,转入后即为初始(有序)插入序。
1248        Dynamic::Map(Arc::new(RwLock::new(m.into_iter().collect())))
1249    }
1250
1251    pub fn into_map(self) -> Option<IndexMap<SmolStr, Dynamic>> {
1252        if let Self::Map(map) = self { Arc::try_unwrap(map).ok().map(|m| m.into_inner()) } else { None }
1253    }
1254
1255    pub fn is_map(&self) -> bool {
1256        if let Self::Map(_) | Self::StructView { .. } | Self::StructOwned { .. } = self { true } else { false }
1257    }
1258
1259    pub fn insert<K: Into<SmolStr>, T: Into<Self>>(&self, key: K, value: T) {
1260        match self {
1261            Self::Map(obj) => {
1262                obj.write().insert(key.into(), value.into());
1263            }
1264            _ => {}
1265        }
1266    }
1267
1268    pub fn len(&self) -> usize {
1269        match self {
1270            Self::String(value) => value.len(),
1271            Self::StringBuf(value) => value.len(),
1272            Self::List(list) => list.read().len(),
1273            Self::Bytes(bytes) => bytes.len(),
1274            Self::VecI8(vec) => vec.len(),
1275            Self::VecU16(vec) => vec.len(),
1276            Self::VecI16(vec) => vec.len(),
1277            Self::VecU32(vec) => vec.len(),
1278            Self::VecI32(vec) => vec.len(),
1279            Self::VecF32(vec) => vec.len(),
1280            Self::VecI64(vec) => vec.len(),
1281            Self::VecU64(vec) => vec.len(),
1282            Self::VecF64(vec) => vec.len(),
1283            Self::Map(obj) => obj.read().len(),
1284            Self::Custom(_) => 0,
1285            _ => 0,
1286        }
1287    }
1288
1289    pub fn keys(&self) -> Vec<SmolStr> {
1290        if let Self::Map(map) = self {
1291            map.read().keys().cloned().collect()
1292        } else if let Some((_, Type::Struct { params: _, fields })) = self.struct_addr_ty() {
1293            fields.iter().map(|(name, _)| name.clone()).collect()
1294        } else {
1295            Vec::new()
1296        }
1297    }
1298
1299    pub fn contains(&self, key: &str) -> bool {
1300        if let Self::Map(map) = self {
1301            map.read().get(key).is_some_and(|value| !value.is_null())
1302        } else if let Self::StructView { ty, .. } | Self::StructOwned { ty, .. } = self {
1303            ty.get_field(key).is_ok()
1304        } else if let Self::List(list) = self {
1305            list.read().iter().find(|l| l.as_str() == key).is_some()
1306        } else if let Self::String(s) = self {
1307            s.contains(key)
1308        } else if let Self::StringBuf(s) = self {
1309            s.contains(key)
1310        } else if let Self::Custom(value) = self {
1311            value.contains_key(key)
1312        } else {
1313            false
1314        }
1315    }
1316
1317    pub fn starts_with(&self, prefix: &str) -> bool {
1318        if let Self::String(s) = self {
1319            s.starts_with(prefix)
1320        } else if let Self::StringBuf(s) = self {
1321            s.starts_with(prefix)
1322        } else {
1323            false
1324        }
1325    }
1326
1327    pub fn ends_with(&self, suffix: &str) -> bool {
1328        if let Self::String(s) = self {
1329            s.ends_with(suffix)
1330        } else if let Self::StringBuf(s) = self {
1331            s.ends_with(suffix)
1332        } else {
1333            false
1334        }
1335    }
1336
1337    pub fn get_dynamic(&self, key: &str) -> Option<Dynamic> {
1338        if let Self::Map(map) = self {
1339            map.read().get(key).cloned()
1340        } else if let Some((addr, ty)) = self.struct_addr_ty() {
1341            let (idx, field_ty) = ty.get_field(key).ok()?;
1342            Self::read_struct_field(addr, idx, field_ty, ty, self.struct_storage())
1343        } else if let Self::Custom(value) = self {
1344            value.get_key(key)
1345        } else {
1346            None
1347        }
1348    }
1349
1350    pub fn set_dynamic(&self, key: SmolStr, value: impl Into<Dynamic>) {
1351        if let Self::Map(map) = self {
1352            map.write().insert(key, value.into());
1353        } else if let Some((addr, ty)) = self.struct_addr_ty()
1354            && let Ok((idx, field_ty)) = ty.get_field(key.as_str())
1355        {
1356            Self::write_struct_field(addr, idx, field_ty, ty, value.into(), self.struct_storage());
1357        } else if let Self::Custom(custom) = self {
1358            custom.set_key(key.as_str(), value.into());
1359        }
1360    }
1361
1362    fn field_addr(addr: usize, idx: usize, struct_ty: &Type) -> Option<usize> {
1363        struct_ty.field_offset(idx).map(|offset| addr + offset as usize)
1364    }
1365
1366    fn read_dynamic_ptr(addr: usize, storage: Option<&StructBytes>, offset: usize) -> Option<Dynamic> {
1367        if let Some(storage) = storage {
1368            return storage.read_dynamic_ptr_at(offset);
1369        }
1370        let ptr = unsafe { std::ptr::read_unaligned(addr as *const usize) };
1371        if ptr == 0 { None } else { Some(unsafe { (&*(ptr as *const Dynamic)).clone() }) }
1372    }
1373
1374    fn write_dynamic_ptr(addr: usize, value: Dynamic, storage: Option<&StructBytes>, offset: usize) {
1375        if let Some(storage) = storage {
1376            storage.write_dynamic_ptr_at(offset, value);
1377        } else {
1378            let ptr = Box::into_raw(Box::new(value)) as usize;
1379            unsafe {
1380                std::ptr::write_unaligned(addr as *mut usize, ptr);
1381            }
1382        }
1383    }
1384
1385    fn read_struct_field(addr: usize, idx: usize, field_ty: &Type, struct_ty: &Type, storage: Option<&StructBytes>) -> Option<Dynamic> {
1386        let field_addr = Self::field_addr(addr, idx, struct_ty)?;
1387        let offset = field_addr.saturating_sub(addr);
1388        match field_ty {
1389            Type::Bool => Some(Dynamic::Bool(unsafe { std::ptr::read_unaligned(field_addr as *const u8) } != 0)),
1390            Type::I8 => Some(Dynamic::I8(unsafe { std::ptr::read_unaligned(field_addr as *const i8) })),
1391            Type::U8 => Some(Dynamic::U8(unsafe { std::ptr::read_unaligned(field_addr as *const u8) })),
1392            Type::I16 => Some(Dynamic::I16(unsafe { std::ptr::read_unaligned(field_addr as *const i16) })),
1393            Type::U16 => Some(Dynamic::U16(unsafe { std::ptr::read_unaligned(field_addr as *const u16) })),
1394            Type::I32 => Some(Dynamic::I32(unsafe { std::ptr::read_unaligned(field_addr as *const i32) })),
1395            Type::U32 => Some(Dynamic::U32(unsafe { std::ptr::read_unaligned(field_addr as *const u32) })),
1396            Type::I64 => Some(Dynamic::I64(unsafe { std::ptr::read_unaligned(field_addr as *const i64) })),
1397            Type::U64 => Some(Dynamic::U64(unsafe { std::ptr::read_unaligned(field_addr as *const u64) })),
1398            Type::F32 => Some(Dynamic::F32(unsafe { std::ptr::read_unaligned(field_addr as *const f32) })),
1399            Type::F64 => Some(Dynamic::F64(unsafe { std::ptr::read_unaligned(field_addr as *const f64) })),
1400            ty if ty.is_struct() || ty.is_array() || ty.is_vec() => {
1401                if storage.is_some() {
1402                    Some(Dynamic::owned_struct_from_ptr(field_addr, field_ty.clone()))
1403                } else {
1404                    Some(Dynamic::struct_view(field_addr, field_ty.clone()))
1405                }
1406            }
1407            _ => Self::read_dynamic_ptr(field_addr, storage, offset),
1408        }
1409    }
1410
1411    fn write_struct_field(addr: usize, idx: usize, field_ty: &Type, struct_ty: &Type, value: Dynamic, storage: Option<&StructBytes>) {
1412        let Some(field_addr) = Self::field_addr(addr, idx, struct_ty) else {
1413            return;
1414        };
1415        let offset = field_addr.saturating_sub(addr);
1416        if let Some(storage) = storage {
1417            storage.clear_dynamic_fields_in(offset, field_ty.storage_width() as usize);
1418        }
1419        match field_ty {
1420            Type::Bool => unsafe {
1421                std::ptr::write_unaligned(field_addr as *mut u8, if value.is_true() { 1 } else { 0 });
1422            },
1423            Type::I8 => unsafe {
1424                std::ptr::write_unaligned(field_addr as *mut i8, value.try_into().unwrap_or_default());
1425            },
1426            Type::U8 => unsafe {
1427                std::ptr::write_unaligned(field_addr as *mut u8, value.try_into().unwrap_or_default());
1428            },
1429            Type::I16 => unsafe {
1430                std::ptr::write_unaligned(field_addr as *mut i16, value.try_into().unwrap_or_default());
1431            },
1432            Type::U16 => unsafe {
1433                std::ptr::write_unaligned(field_addr as *mut u16, value.try_into().unwrap_or_default());
1434            },
1435            Type::I32 => unsafe {
1436                std::ptr::write_unaligned(field_addr as *mut i32, value.try_into().unwrap_or_default());
1437            },
1438            Type::U32 => unsafe {
1439                std::ptr::write_unaligned(field_addr as *mut u32, value.try_into().unwrap_or_default());
1440            },
1441            Type::I64 => unsafe {
1442                std::ptr::write_unaligned(field_addr as *mut i64, value.try_into().unwrap_or_default());
1443            },
1444            Type::U64 => unsafe {
1445                std::ptr::write_unaligned(field_addr as *mut u64, value.try_into().unwrap_or_default());
1446            },
1447            Type::F32 => unsafe {
1448                std::ptr::write_unaligned(field_addr as *mut f32, f32::try_from(value).unwrap_or_default());
1449            },
1450            Type::F64 => unsafe {
1451                std::ptr::write_unaligned(field_addr as *mut f64, f64::try_from(value).unwrap_or_default());
1452            },
1453            ty if ty.is_struct() || ty.is_array() || ty.is_vec() => {
1454                if let Some((src_addr, _)) = value.struct_addr_ty() {
1455                    if let Some(storage) = storage {
1456                        unsafe {
1457                            std::ptr::copy_nonoverlapping(src_addr as *const u8, field_addr as *mut u8, field_ty.storage_width() as usize);
1458                        }
1459                        storage.clone_dynamic_fields_from(src_addr, field_ty, offset);
1460                    } else {
1461                        unsafe {
1462                            std::ptr::copy_nonoverlapping(src_addr as *const u8, field_addr as *mut u8, field_ty.storage_width() as usize);
1463                        }
1464                    }
1465                }
1466            }
1467            _ => Self::write_dynamic_ptr(field_addr, value, storage, offset),
1468        }
1469    }
1470
1471    pub fn remove_dynamic(&self, key: &str) -> Option<Dynamic> {
1472        // shift_remove 保留插入顺序(swap_remove 会打乱),与原 BTreeMap 删除后仍有序的语义最接近
1473        if let Self::Map(map) = self { map.write().shift_remove(key) } else { None }
1474    }
1475
1476    pub fn get_idx(&self, idx: usize) -> Option<Self> {
1477        match self {
1478            Self::List(list) => list.read().get(idx).cloned(),
1479            Self::VecI8(vec) => vec.get(idx).map(Self::I8),
1480            Self::VecU16(vec) => vec.get(idx).map(Self::U16),
1481            Self::VecI16(vec) => vec.get(idx).map(Self::I16),
1482            Self::VecU32(vec) => vec.get(idx).map(Self::U32),
1483            Self::VecI32(vec) => vec.get(idx).map(Self::I32),
1484            Self::VecF32(vec) => vec.get(idx).map(Self::F32),
1485            Self::VecI64(vec) => vec.get(idx).cloned().map(Self::I64),
1486            Self::VecU64(vec) => vec.get(idx).cloned().map(Self::U64),
1487            Self::VecF64(vec) => vec.get(idx).cloned().map(Self::F64),
1488            Self::StructView { addr, ty } => {
1489                if let Type::Struct { params: _, fields } = ty.as_ref() {
1490                    fields.get(idx).and_then(|(_, field_ty)| Self::read_struct_field(*addr, idx, field_ty, ty.as_ref(), None))
1491                } else {
1492                    Self::read_aggregate_index(*addr, idx, ty.as_ref(), None)
1493                }
1494            }
1495            Self::StructOwned { storage, ty } => Self::read_aggregate_index(storage.addr(), idx, ty.as_ref(), Some(storage)),
1496            _ => None,
1497        }
1498    }
1499
1500    fn read_aggregate_index(addr: usize, idx: usize, ty: &Type, storage: Option<&StructBytes>) -> Option<Self> {
1501        match ty {
1502            Type::Struct { fields, .. } => fields.get(idx).and_then(|(_, field_ty)| Self::read_struct_field(addr, idx, field_ty, ty, storage)),
1503            Type::Array(elem_ty, len) | Type::Vec(elem_ty, len) => {
1504                if idx >= *len as usize {
1505                    return None;
1506                }
1507                let elem_addr = addr + idx * elem_ty.storage_width() as usize;
1508                Some(Self::read_aggregate_value(elem_addr, elem_ty, storage, elem_addr.saturating_sub(addr)))
1509            }
1510            _ => None,
1511        }
1512    }
1513
1514    fn read_aggregate_value(addr: usize, ty: &Type, storage: Option<&StructBytes>, offset: usize) -> Self {
1515        match ty {
1516            Type::Bool => Dynamic::Bool(unsafe { std::ptr::read_unaligned(addr as *const u8) } != 0),
1517            Type::I8 => Dynamic::I8(unsafe { std::ptr::read_unaligned(addr as *const i8) }),
1518            Type::U8 => Dynamic::U8(unsafe { std::ptr::read_unaligned(addr as *const u8) }),
1519            Type::I16 => Dynamic::I16(unsafe { std::ptr::read_unaligned(addr as *const i16) }),
1520            Type::U16 => Dynamic::U16(unsafe { std::ptr::read_unaligned(addr as *const u16) }),
1521            Type::I32 => Dynamic::I32(unsafe { std::ptr::read_unaligned(addr as *const i32) }),
1522            Type::U32 => Dynamic::U32(unsafe { std::ptr::read_unaligned(addr as *const u32) }),
1523            Type::I64 => Dynamic::I64(unsafe { std::ptr::read_unaligned(addr as *const i64) }),
1524            Type::U64 => Dynamic::U64(unsafe { std::ptr::read_unaligned(addr as *const u64) }),
1525            Type::F32 => Dynamic::F32(unsafe { std::ptr::read_unaligned(addr as *const f32) }),
1526            Type::F64 => Dynamic::F64(unsafe { std::ptr::read_unaligned(addr as *const f64) }),
1527            ty if ty.is_struct() || ty.is_array() || ty.is_vec() => {
1528                if storage.is_some() {
1529                    Dynamic::owned_struct_from_ptr(addr, ty.clone())
1530                } else {
1531                    Dynamic::struct_view(addr, ty.clone())
1532                }
1533            }
1534            _ => Self::read_dynamic_ptr(addr, storage, offset).unwrap_or(Dynamic::Null),
1535        }
1536    }
1537
1538    pub fn into_iter(self) -> Self {
1539        if self.is_map() {
1540            let keys = self.keys();
1541            Self::Iter { idx: 0, keys, value: Box::new(self) }
1542        } else {
1543            Self::Iter { idx: 0, keys: Vec::new(), value: Box::new(self) }
1544        }
1545    }
1546
1547    pub fn next(&mut self) -> Option<Self> {
1548        if let Self::Iter { idx, keys, value } = self {
1549            if !keys.is_empty() {
1550                if *idx < keys.len() {
1551                    let k = keys[*idx].clone();
1552                    let v = value.get_dynamic(k.as_str()).unwrap();
1553                    *idx += 1;
1554                    return Some(v);
1555                }
1556            } else {
1557                if let Some(v) = value.get_idx(*idx) {
1558                    *idx += 1;
1559                    return Some(v);
1560                }
1561            }
1562        }
1563        None
1564    }
1565
1566    pub fn next_pair(&mut self) -> Option<Self> {
1567        if let Self::Iter { idx, keys, value } = self {
1568            if !keys.is_empty() {
1569                if *idx < keys.len() {
1570                    let k = keys[*idx].clone();
1571                    let v = value.get_dynamic(k.as_str()).unwrap();
1572                    *idx += 1;
1573                    return Some(list!(k, v));
1574                }
1575            } else {
1576                if let Some(v) = value.get_idx(*idx) {
1577                    *idx += 1;
1578                    return Some(v);
1579                }
1580            }
1581        }
1582        None
1583    }
1584
1585    pub fn set_idx(&mut self, idx: usize, val: Dynamic) {
1586        match self {
1587            Self::List(list) => {
1588                list.write().get_mut(idx).map(|l| *l = val);
1589            }
1590            Self::VecI8(vec) => {
1591                if let Ok(value) = val.try_into() {
1592                    vec.set(idx, value);
1593                }
1594            }
1595            Self::VecU16(vec) => {
1596                if let Ok(value) = val.try_into() {
1597                    vec.set(idx, value);
1598                }
1599            }
1600            Self::VecI16(vec) => {
1601                if let Ok(value) = val.try_into() {
1602                    vec.set(idx, value);
1603                }
1604            }
1605            Self::VecU32(vec) => {
1606                if let Ok(value) = val.try_into() {
1607                    vec.set(idx, value);
1608                }
1609            }
1610            Self::VecI32(vec) => {
1611                if let Ok(value) = val.try_into() {
1612                    vec.set(idx, value);
1613                }
1614            }
1615            Self::VecF32(vec) => {
1616                if let Ok(value) = val.try_into() {
1617                    vec.set(idx, value);
1618                }
1619            }
1620            Self::VecI64(vec) => {
1621                if let Some(slot) = vec.get_mut(idx)
1622                    && let Ok(value) = val.try_into()
1623                {
1624                    *slot = value;
1625                }
1626            }
1627            Self::VecU64(vec) => {
1628                if let Some(slot) = vec.get_mut(idx)
1629                    && let Ok(value) = val.try_into()
1630                {
1631                    *slot = value;
1632                }
1633            }
1634            Self::VecF64(vec) => {
1635                if let Some(slot) = vec.get_mut(idx)
1636                    && let Ok(value) = val.try_into()
1637                {
1638                    *slot = value;
1639                }
1640            }
1641            Self::StructView { addr, ty } => {
1642                if let Type::Struct { params: _, fields } = ty.as_ref()
1643                    && let Some((_, field_ty)) = fields.get(idx)
1644                {
1645                    Self::write_struct_field(*addr, idx, field_ty, ty.as_ref(), val, None);
1646                } else {
1647                    Self::write_aggregate_index(*addr, idx, ty.as_ref(), val, None);
1648                }
1649            }
1650            Self::StructOwned { storage, ty } => {
1651                if let Type::Struct { params: _, fields } = ty.as_ref()
1652                    && let Some((_, field_ty)) = fields.get(idx)
1653                {
1654                    Self::write_struct_field(storage.addr(), idx, field_ty, ty.as_ref(), val, Some(storage));
1655                } else {
1656                    Self::write_aggregate_index(storage.addr(), idx, ty.as_ref(), val, Some(storage));
1657                }
1658            }
1659            _ => {}
1660        }
1661    }
1662
1663    fn write_aggregate_index(addr: usize, idx: usize, ty: &Type, val: Dynamic, storage: Option<&StructBytes>) {
1664        let (elem_ty, len) = match ty {
1665            Type::Array(elem_ty, len) | Type::Vec(elem_ty, len) => (elem_ty.as_ref(), *len as usize),
1666            _ => return,
1667        };
1668        if idx >= len {
1669            return;
1670        }
1671        let offset = idx * elem_ty.storage_width() as usize;
1672        let elem_addr = addr + offset;
1673        if let Some(storage) = storage {
1674            storage.clear_dynamic_fields_in(offset, elem_ty.storage_width() as usize);
1675        }
1676        match elem_ty {
1677            Type::Bool => unsafe { std::ptr::write_unaligned(elem_addr as *mut u8, if val.is_true() { 1 } else { 0 }) },
1678            Type::I8 => unsafe { std::ptr::write_unaligned(elem_addr as *mut i8, val.try_into().unwrap_or_default()) },
1679            Type::U8 => unsafe { std::ptr::write_unaligned(elem_addr as *mut u8, val.try_into().unwrap_or_default()) },
1680            Type::I16 => unsafe { std::ptr::write_unaligned(elem_addr as *mut i16, val.try_into().unwrap_or_default()) },
1681            Type::U16 => unsafe { std::ptr::write_unaligned(elem_addr as *mut u16, val.try_into().unwrap_or_default()) },
1682            Type::I32 => unsafe { std::ptr::write_unaligned(elem_addr as *mut i32, val.try_into().unwrap_or_default()) },
1683            Type::U32 => unsafe { std::ptr::write_unaligned(elem_addr as *mut u32, val.try_into().unwrap_or_default()) },
1684            Type::I64 => unsafe { std::ptr::write_unaligned(elem_addr as *mut i64, val.try_into().unwrap_or_default()) },
1685            Type::U64 => unsafe { std::ptr::write_unaligned(elem_addr as *mut u64, val.try_into().unwrap_or_default()) },
1686            Type::F32 => unsafe { std::ptr::write_unaligned(elem_addr as *mut f32, f32::try_from(val).unwrap_or_default()) },
1687            Type::F64 => unsafe { std::ptr::write_unaligned(elem_addr as *mut f64, f64::try_from(val).unwrap_or_default()) },
1688            ty if ty.is_struct() || ty.is_array() || ty.is_vec() => {
1689                if let Some((src_addr, _)) = val.struct_addr_ty() {
1690                    unsafe {
1691                        std::ptr::copy_nonoverlapping(src_addr as *const u8, elem_addr as *mut u8, elem_ty.storage_width() as usize);
1692                    }
1693                    if let Some(storage) = storage {
1694                        storage.clone_dynamic_fields_from(src_addr, elem_ty, offset);
1695                    }
1696                }
1697            }
1698            _ => Self::write_dynamic_ptr(elem_addr, val, storage, offset),
1699        }
1700    }
1701
1702    pub fn to_markdown(&self) -> String {
1703        let mut s = String::new();
1704        if let Self::Map(m) = self {
1705            for (key, v) in m.read().iter() {
1706                s.push_str(&format!("#### ```{}```\n", key));
1707                s.push_str(&v.to_markdown());
1708                s.push('\n');
1709            }
1710        } else if let Self::Bytes(bytes) = self {
1711            s = format!("[{}...]", hex::encode(&bytes[..8]));
1712        } else {
1713            let len = self.len();
1714            if len > 0 {
1715                for idx in 0..len {
1716                    s.push_str(&format!("- {}\n", self.get_idx(idx).unwrap().to_markdown()));
1717                }
1718            } else {
1719                s = self.to_string();
1720            }
1721        }
1722        s
1723    }
1724}
1725
1726#[cfg(test)]
1727mod tests {
1728    use super::*;
1729    use parking_lot::RwLock;
1730
1731    #[derive(Debug, PartialEq)]
1732    struct CustomCounter {
1733        value: i64,
1734    }
1735
1736    #[test]
1737    fn type_add_promotion_rules() {
1738        use crate::Type;
1739        // 相同类型保持
1740        assert_eq!(Type::I32 + Type::I32, Type::I32);
1741        // 字符串吸收一切
1742        assert_eq!(Type::I32 + Type::Str, Type::Str);
1743        // Any 退化
1744        assert_eq!(Type::I32 + Type::Any, Type::Any);
1745        // 浮点优先,取较宽
1746        assert_eq!(Type::I64 + Type::F32, Type::F32);
1747        assert_eq!(Type::F32 + Type::F64, Type::F64);
1748        // 整数取较大宽度
1749        assert_eq!(Type::I8 + Type::I32, Type::I32);
1750        assert_eq!(Type::I32 + Type::I64, Type::I64);
1751        // 有符号先于无符号被处理:i32 + u32 -> i32
1752        assert_eq!(Type::I32 + Type::U32, Type::I32);
1753        // 无符号同宽
1754        assert_eq!(Type::U8 + Type::U32, Type::U32);
1755    }
1756
1757    #[test]
1758    fn dynamic_enum_stays_compact() {
1759        assert_eq!(std::mem::size_of::<Dynamic>(), 40);
1760    }
1761
1762    #[test]
1763    fn custom_values_can_be_downcast_and_shared_by_clone() {
1764        let value = Dynamic::custom(RwLock::new(CustomCounter { value: 7 }));
1765        assert!(value.is_custom());
1766        assert!(value.custom_type_name().is_some());
1767
1768        let cloned = value.clone();
1769        assert_eq!(cloned.as_custom::<RwLock<CustomCounter>>().unwrap().read().value, 7);
1770
1771        cloned.as_custom::<RwLock<CustomCounter>>().unwrap().write().value = 9;
1772        assert_eq!(value.as_custom::<RwLock<CustomCounter>>().unwrap().read().value, 9);
1773        assert_eq!(value, cloned);
1774    }
1775
1776    #[derive(Debug, Default)]
1777    struct CustomPropertyBag {
1778        values: RwLock<BTreeMap<SmolStr, Dynamic>>,
1779    }
1780
1781    impl CustomProperty for CustomPropertyBag {
1782        fn get_key(&self, key: &str) -> Option<Dynamic> {
1783            self.values.read().get(key).cloned()
1784        }
1785
1786        fn set_key(&self, key: &str, value: Dynamic) -> bool {
1787            self.values.write().insert(key.into(), value);
1788            true
1789        }
1790    }
1791
1792    #[test]
1793    fn custom_values_can_forward_dynamic_properties() {
1794        let value = Dynamic::custom_with_properties(CustomPropertyBag::default());
1795
1796        value.set_dynamic("file_mode".into(), 2i64);
1797
1798        assert!(value.contains("file_mode"));
1799        assert_eq!(value.get_dynamic("file_mode").and_then(|value| value.as_int()), Some(2));
1800    }
1801
1802    #[test]
1803    fn deep_clone_recursively_copies_maps_and_lists() {
1804        let nested = Dynamic::map(Default::default());
1805        nested.insert("score", 1);
1806
1807        let value = Dynamic::map(Default::default());
1808        value.insert("nested", nested.clone());
1809        value.insert("items", Dynamic::list(vec![nested.clone()]));
1810
1811        let cloned = value.deep_clone();
1812        cloned.get_dynamic("nested").unwrap().insert("score", 2);
1813        cloned.get_dynamic("items").unwrap().get_idx(0).unwrap().insert("score", 3);
1814
1815        assert_eq!(value.get_dynamic("nested").unwrap().get_dynamic("score").and_then(|v| v.as_int()), Some(1));
1816        assert_eq!(value.get_dynamic("items").unwrap().get_idx(0).unwrap().get_dynamic("score").and_then(|v| v.as_int()), Some(1));
1817    }
1818
1819    #[test]
1820    fn string_add_keeps_concat_semantics() {
1821        let left = Dynamic::from("hello");
1822        let right = Dynamic::from(" world");
1823        let joined = left + right;
1824        assert!(matches!(joined, Dynamic::StringBuf(_)));
1825        assert_eq!(joined.as_str(), "hello world");
1826
1827        assert_eq!((Dynamic::from("level ") + Dynamic::I64(7)).as_str(), "level 7");
1828        assert_eq!((Dynamic::I64(7) + Dynamic::from(" days")).as_str(), "7 days");
1829    }
1830
1831    #[test]
1832    fn string_add_reuses_string_buf_after_first_concat() {
1833        let mut value = Dynamic::from("a") + Dynamic::from("b");
1834        assert!(matches!(value, Dynamic::StringBuf(_)));
1835
1836        value = value + Dynamic::from("c");
1837        assert!(matches!(value, Dynamic::StringBuf(_)));
1838        assert_eq!(value.as_str(), "abc");
1839    }
1840
1841    #[test]
1842    fn u64_as_int_does_not_wrap() {
1843        assert_eq!(Dynamic::U64(i64::MAX as u64).as_int(), Some(i64::MAX));
1844        assert_eq!(Dynamic::U64(i64::MAX as u64 + 1).as_int(), None);
1845    }
1846
1847    #[test]
1848    fn dynamic_integer_ops_report_fault_instead_of_panicking() {
1849        let _ = take_fault();
1850        assert_eq!(Dynamic::U64(u64::MAX) + Dynamic::U64(1), Dynamic::Null);
1851        assert!(take_fault().is_some());
1852
1853        assert_eq!(Dynamic::I64(i64::MAX) + Dynamic::I64(1), Dynamic::Null);
1854        assert!(take_fault().is_some());
1855
1856        assert_eq!(Dynamic::I32(1) << Dynamic::I32(64), Dynamic::Null);
1857        assert!(take_fault().is_some());
1858    }
1859
1860    #[test]
1861    fn typed_vec_set_idx_ignores_bad_index_or_value_without_panicking() {
1862        let mut values = Dynamic::VecI64(vec![1, 2, 3]);
1863        values.set_idx(10, Dynamic::I64(99));
1864        assert_eq!(values.get_idx(2).and_then(|value| value.as_int()), Some(3));
1865
1866        values.set_idx(1, Dynamic::from("bad"));
1867        assert_eq!(values.get_idx(1).and_then(|value| value.as_int()), Some(2));
1868
1869        values.set_idx(1, Dynamic::I64(7));
1870        assert_eq!(values.get_idx(1).and_then(|value| value.as_int()), Some(7));
1871    }
1872
1873    #[test]
1874    fn nested_struct_fields_use_inline_storage() {
1875        let inner_ty = Type::Struct { params: vec![], fields: vec![("value".into(), Type::I64)] };
1876        let outer_ty = Type::Struct { params: vec![], fields: vec![("inner".into(), inner_ty.clone()), ("tag".into(), Type::I64)] };
1877
1878        let mut inner_bytes = vec![0u8; inner_ty.storage_width() as usize];
1879        let mut outer_bytes = vec![0u8; outer_ty.storage_width() as usize];
1880        let inner = Dynamic::struct_view(inner_bytes.as_mut_ptr() as usize, inner_ty);
1881        let outer = Dynamic::struct_view(outer_bytes.as_mut_ptr() as usize, outer_ty);
1882
1883        inner.set_dynamic("value".into(), Dynamic::I64(17));
1884        outer.set_dynamic("inner".into(), inner);
1885        outer.set_dynamic("tag".into(), Dynamic::I64(3));
1886
1887        let read_inner = outer.get_dynamic("inner").expect("inner field");
1888        assert_eq!(read_inner.get_dynamic("value").and_then(|value| value.as_int()), Some(17));
1889        assert_eq!(outer.get_dynamic("tag").and_then(|value| value.as_int()), Some(3));
1890    }
1891
1892    #[test]
1893    fn owned_struct_clones_dynamic_pointer_fields() {
1894        let ty = Type::Struct { params: vec![], fields: vec![("name".into(), Type::Str)] };
1895        let mut bytes = vec![0u8; ty.storage_width() as usize];
1896        let original = Box::into_raw(Box::new(Dynamic::from("alpha"))) as usize;
1897        unsafe {
1898            std::ptr::write_unaligned(bytes.as_mut_ptr() as *mut usize, original);
1899        }
1900
1901        let owned = Dynamic::owned_struct_from_ptr(bytes.as_ptr() as usize, ty);
1902        unsafe {
1903            drop(Box::from_raw(original as *mut Dynamic));
1904        }
1905
1906        assert_eq!(owned.get_dynamic("name").map(|value| value.as_str().to_string()), Some("alpha".to_string()));
1907        owned.set_dynamic("name".into(), Dynamic::from("beta"));
1908        assert_eq!(owned.get_dynamic("name").map(|value| value.as_str().to_string()), Some("beta".to_string()));
1909    }
1910
1911    #[test]
1912    fn aggregate_array_fields_support_dynamic_index_access() {
1913        let ty = Type::Array(std::rc::Rc::new(Type::I64), 3);
1914        let mut bytes = vec![0u8; ty.storage_width() as usize];
1915        for (idx, value) in [3i64, 5, 7].into_iter().enumerate() {
1916            unsafe {
1917                std::ptr::write_unaligned(bytes.as_mut_ptr().add(idx * 8) as *mut i64, value);
1918            }
1919        }
1920
1921        let mut array = Dynamic::owned_struct_from_ptr(bytes.as_ptr() as usize, ty);
1922        assert_eq!(array.get_idx(1).and_then(|value| value.as_int()), Some(5));
1923        array.set_idx(1, Dynamic::I64(11));
1924        assert_eq!(array.get_idx(1).and_then(|value| value.as_int()), Some(11));
1925    }
1926
1927    #[test]
1928    fn f16_roundtrip_via_helpers() {
1929        let bits = f64_to_f16(1.0);
1930        assert_eq!(bits, 0x3C00);
1931        assert_eq!(f16_to_f64(bits), 1.0);
1932        let bits = f64_to_f16(0.5);
1933        assert_eq!(bits, 0x3800);
1934        assert_eq!(f16_to_f64(bits), 0.5);
1935    }
1936
1937    #[test]
1938    fn f16_dynamic_get_type_and_is_float() {
1939        let v = Dynamic::F16(0x3C00);
1940        assert_eq!(v.get_type(), Type::F16);
1941        assert!(v.is_f16());
1942        assert!(v.is_signed());
1943        assert_eq!(v.size_of(), 2);
1944        assert_eq!(v.as_float(), Some(1.0));
1945    }
1946
1947    #[test]
1948    fn f16_force_from_f64_preserves_value() {
1949        let d = Type::F16.force(Dynamic::F64(2.0)).unwrap();
1950        let Dynamic::F16(bits) = d else {
1951            panic!("expected F16");
1952        };
1953        assert_eq!(bits, 0x4000);
1954        assert_eq!(f16_to_f64(bits), 2.0);
1955    }
1956
1957    #[test]
1958    fn f16_compare_equal_by_bits() {
1959        assert_eq!(Dynamic::F16(0x3C00), Dynamic::F16(0x3C00));
1960        assert_ne!(Dynamic::F16(0x3C00), Dynamic::F16(0x4000));
1961    }
1962
1963    #[test]
1964    fn f16_subnormal_roundtrip() {
1965        // 最小 subnormal (0x0001) ≈ 5.960464477539063e-8
1966        let bits = f64_to_f16(5.96e-8);
1967        assert_eq!(bits, 0x0001);
1968        let back = f16_to_f64(bits);
1969        let expected = half::f16::from_bits(0x0001).to_f64();
1970        assert_eq!(back, expected, "got {back}");
1971    }
1972
1973    #[test]
1974    fn f16_infinity_roundtrip() {
1975        let bits = f64_to_f16(f64::INFINITY);
1976        assert_eq!(bits, 0x7C00);
1977        assert!(f16_to_f64(bits).is_infinite());
1978
1979        let bits = f64_to_f16(f64::NEG_INFINITY);
1980        assert_eq!(bits, 0xFC00);
1981        assert!(f16_to_f64(bits).is_sign_negative());
1982    }
1983
1984    #[test]
1985    fn fn_type_partial_eq_with_diff_ret_returns_false_not_panic() {
1986        use std::rc::Rc;
1987        let a = Type::Fn { tys: vec![Type::I32], ret: Rc::new(Type::I32) };
1988        let b = Type::Fn { tys: vec![Type::I32], ret: Rc::new(Type::F32) };
1989        assert!(a != b);
1990        assert!(!(a == b));
1991    }
1992
1993    #[test]
1994    fn fn_type_partial_eq_same_args_same_ret_is_true() {
1995        use std::rc::Rc;
1996        let a = Type::Fn { tys: vec![Type::I32], ret: Rc::new(Type::I32) };
1997        let b = Type::Fn { tys: vec![Type::I32], ret: Rc::new(Type::I32) };
1998        assert!(a == b);
1999    }
2000
2001    #[test]
2002    fn fn_type_partial_eq_diff_args_returns_false() {
2003        use std::rc::Rc;
2004        let a = Type::Fn { tys: vec![Type::I32], ret: Rc::new(Type::Void) };
2005        let b = Type::Fn { tys: vec![Type::I64], ret: Rc::new(Type::Void) };
2006        assert!(a != b);
2007    }
2008
2009    #[test]
2010    fn fn_type_partial_eq_with_any_ret_is_false() {
2011        use std::rc::Rc;
2012        let a = Type::Fn { tys: vec![Type::I32], ret: Rc::new(Type::Any) };
2013        let b = Type::Fn { tys: vec![Type::I32], ret: Rc::new(Type::I32) };
2014        assert!(a != b);
2015    }
2016}
2017
2018#[macro_export]
2019macro_rules! assert_ok {
2020    ( $x: expr, $ok: expr) => {
2021        if $x {
2022            return Ok($ok);
2023        }
2024    };
2025}
2026
2027#[macro_export]
2028macro_rules! assert_err {
2029    ( $x: expr, $err: expr) => {
2030        if $x {
2031            return Err($err);
2032        }
2033    };
2034}
2035
2036pub struct ZOnce {
2037    first: Option<&'static str>,
2038    other: &'static str,
2039}
2040
2041impl ZOnce {
2042    pub fn new(first: &'static str, other: &'static str) -> Self {
2043        Self { first: Some(first), other }
2044    }
2045    pub fn take(&mut self) -> &'static str {
2046        self.first.take().unwrap_or(self.other)
2047    }
2048}
2049
2050mod fixvec;
2051pub use fixvec::FixVec;
2052mod msgpack;
2053pub use msgpack::{MsgPack, MsgUnpack};
2054
2055pub use json::{FromJson, ToJson};
2056
2057mod fault;
2058pub use fault::{has_fault, set_fault, take_fault};
2059mod ops;
2060mod types;
2061pub use types::{ConstIntOp, Type, call_fn, set_dynamic_return_handler};
2062
2063#[macro_export]
2064macro_rules! list {
2065    ($($v:expr),+ $(,)?) => {{
2066        let mut list = Vec::new();
2067        $( let _ = list.push(Dynamic::from($v)); )*
2068        Dynamic::List(::std::sync::Arc::new($crate::RwLock::new(list)))
2069    }};
2070}
2071
2072#[macro_export]
2073macro_rules! map {
2074    ($($k:expr => $v:expr), *) => {{
2075        let mut obj = std::collections::BTreeMap::new();
2076        $( let _ = obj.insert(smol_str::SmolStr::from($k), Dynamic::from($v)); )*
2077        Dynamic::map(obj)
2078    }};
2079}