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#[inline]
15pub fn f16_to_f64(bits: u16) -> f64 {
16 f16::from_bits(bits).to_f64()
17}
18
19#[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), U64(u64),
337 I64(i64),
338 F16(u16), F32(f32), 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 (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 (a, b) if a.is_int() && b.is_int() => a.as_int() == b.as_int(),
392 (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 (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 (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 (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 (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 } else if self.is_true() && other.is_false() {
464 Ordering::Greater } 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 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 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 get_dynamic(&self, key: &str) -> Option<Dynamic> {
1328 if let Self::Map(map) = self {
1329 map.read().get(key).cloned()
1330 } else if let Some((addr, ty)) = self.struct_addr_ty() {
1331 let (idx, field_ty) = ty.get_field(key).ok()?;
1332 Self::read_struct_field(addr, idx, field_ty, ty, self.struct_storage())
1333 } else if let Self::Custom(value) = self {
1334 value.get_key(key)
1335 } else {
1336 None
1337 }
1338 }
1339
1340 pub fn set_dynamic(&self, key: SmolStr, value: impl Into<Dynamic>) {
1341 if let Self::Map(map) = self {
1342 map.write().insert(key, value.into());
1343 } else if let Some((addr, ty)) = self.struct_addr_ty()
1344 && let Ok((idx, field_ty)) = ty.get_field(key.as_str())
1345 {
1346 Self::write_struct_field(addr, idx, field_ty, ty, value.into(), self.struct_storage());
1347 } else if let Self::Custom(custom) = self {
1348 custom.set_key(key.as_str(), value.into());
1349 }
1350 }
1351
1352 fn field_addr(addr: usize, idx: usize, struct_ty: &Type) -> Option<usize> {
1353 struct_ty.field_offset(idx).map(|offset| addr + offset as usize)
1354 }
1355
1356 fn read_dynamic_ptr(addr: usize, storage: Option<&StructBytes>, offset: usize) -> Option<Dynamic> {
1357 if let Some(storage) = storage {
1358 return storage.read_dynamic_ptr_at(offset);
1359 }
1360 let ptr = unsafe { std::ptr::read_unaligned(addr as *const usize) };
1361 if ptr == 0 { None } else { Some(unsafe { (&*(ptr as *const Dynamic)).clone() }) }
1362 }
1363
1364 fn write_dynamic_ptr(addr: usize, value: Dynamic, storage: Option<&StructBytes>, offset: usize) {
1365 if let Some(storage) = storage {
1366 storage.write_dynamic_ptr_at(offset, value);
1367 } else {
1368 let ptr = Box::into_raw(Box::new(value)) as usize;
1369 unsafe {
1370 std::ptr::write_unaligned(addr as *mut usize, ptr);
1371 }
1372 }
1373 }
1374
1375 fn read_struct_field(addr: usize, idx: usize, field_ty: &Type, struct_ty: &Type, storage: Option<&StructBytes>) -> Option<Dynamic> {
1376 let field_addr = Self::field_addr(addr, idx, struct_ty)?;
1377 let offset = field_addr.saturating_sub(addr);
1378 match field_ty {
1379 Type::Bool => Some(Dynamic::Bool(unsafe { std::ptr::read_unaligned(field_addr as *const u8) } != 0)),
1380 Type::I8 => Some(Dynamic::I8(unsafe { std::ptr::read_unaligned(field_addr as *const i8) })),
1381 Type::U8 => Some(Dynamic::U8(unsafe { std::ptr::read_unaligned(field_addr as *const u8) })),
1382 Type::I16 => Some(Dynamic::I16(unsafe { std::ptr::read_unaligned(field_addr as *const i16) })),
1383 Type::U16 => Some(Dynamic::U16(unsafe { std::ptr::read_unaligned(field_addr as *const u16) })),
1384 Type::I32 => Some(Dynamic::I32(unsafe { std::ptr::read_unaligned(field_addr as *const i32) })),
1385 Type::U32 => Some(Dynamic::U32(unsafe { std::ptr::read_unaligned(field_addr as *const u32) })),
1386 Type::I64 => Some(Dynamic::I64(unsafe { std::ptr::read_unaligned(field_addr as *const i64) })),
1387 Type::U64 => Some(Dynamic::U64(unsafe { std::ptr::read_unaligned(field_addr as *const u64) })),
1388 Type::F32 => Some(Dynamic::F32(unsafe { std::ptr::read_unaligned(field_addr as *const f32) })),
1389 Type::F64 => Some(Dynamic::F64(unsafe { std::ptr::read_unaligned(field_addr as *const f64) })),
1390 ty if ty.is_struct() || ty.is_array() || ty.is_vec() => {
1391 if storage.is_some() {
1392 Some(Dynamic::owned_struct_from_ptr(field_addr, field_ty.clone()))
1393 } else {
1394 Some(Dynamic::struct_view(field_addr, field_ty.clone()))
1395 }
1396 }
1397 _ => Self::read_dynamic_ptr(field_addr, storage, offset),
1398 }
1399 }
1400
1401 fn write_struct_field(addr: usize, idx: usize, field_ty: &Type, struct_ty: &Type, value: Dynamic, storage: Option<&StructBytes>) {
1402 let Some(field_addr) = Self::field_addr(addr, idx, struct_ty) else {
1403 return;
1404 };
1405 let offset = field_addr.saturating_sub(addr);
1406 if let Some(storage) = storage {
1407 storage.clear_dynamic_fields_in(offset, field_ty.storage_width() as usize);
1408 }
1409 match field_ty {
1410 Type::Bool => unsafe {
1411 std::ptr::write_unaligned(field_addr as *mut u8, if value.is_true() { 1 } else { 0 });
1412 },
1413 Type::I8 => unsafe {
1414 std::ptr::write_unaligned(field_addr as *mut i8, value.try_into().unwrap_or_default());
1415 },
1416 Type::U8 => unsafe {
1417 std::ptr::write_unaligned(field_addr as *mut u8, value.try_into().unwrap_or_default());
1418 },
1419 Type::I16 => unsafe {
1420 std::ptr::write_unaligned(field_addr as *mut i16, value.try_into().unwrap_or_default());
1421 },
1422 Type::U16 => unsafe {
1423 std::ptr::write_unaligned(field_addr as *mut u16, value.try_into().unwrap_or_default());
1424 },
1425 Type::I32 => unsafe {
1426 std::ptr::write_unaligned(field_addr as *mut i32, value.try_into().unwrap_or_default());
1427 },
1428 Type::U32 => unsafe {
1429 std::ptr::write_unaligned(field_addr as *mut u32, value.try_into().unwrap_or_default());
1430 },
1431 Type::I64 => unsafe {
1432 std::ptr::write_unaligned(field_addr as *mut i64, value.try_into().unwrap_or_default());
1433 },
1434 Type::U64 => unsafe {
1435 std::ptr::write_unaligned(field_addr as *mut u64, value.try_into().unwrap_or_default());
1436 },
1437 Type::F32 => unsafe {
1438 std::ptr::write_unaligned(field_addr as *mut f32, f32::try_from(value).unwrap_or_default());
1439 },
1440 Type::F64 => unsafe {
1441 std::ptr::write_unaligned(field_addr as *mut f64, f64::try_from(value).unwrap_or_default());
1442 },
1443 ty if ty.is_struct() || ty.is_array() || ty.is_vec() => {
1444 if let Some((src_addr, _)) = value.struct_addr_ty() {
1445 if let Some(storage) = storage {
1446 unsafe {
1447 std::ptr::copy_nonoverlapping(src_addr as *const u8, field_addr as *mut u8, field_ty.storage_width() as usize);
1448 }
1449 storage.clone_dynamic_fields_from(src_addr, field_ty, offset);
1450 } else {
1451 unsafe {
1452 std::ptr::copy_nonoverlapping(src_addr as *const u8, field_addr as *mut u8, field_ty.storage_width() as usize);
1453 }
1454 }
1455 }
1456 }
1457 _ => Self::write_dynamic_ptr(field_addr, value, storage, offset),
1458 }
1459 }
1460
1461 pub fn remove_dynamic(&self, key: &str) -> Option<Dynamic> {
1462 if let Self::Map(map) = self { map.write().shift_remove(key) } else { None }
1464 }
1465
1466 pub fn get_idx(&self, idx: usize) -> Option<Self> {
1467 match self {
1468 Self::List(list) => list.read().get(idx).cloned(),
1469 Self::VecI8(vec) => vec.get(idx).map(Self::I8),
1470 Self::VecU16(vec) => vec.get(idx).map(Self::U16),
1471 Self::VecI16(vec) => vec.get(idx).map(Self::I16),
1472 Self::VecU32(vec) => vec.get(idx).map(Self::U32),
1473 Self::VecI32(vec) => vec.get(idx).map(Self::I32),
1474 Self::VecF32(vec) => vec.get(idx).map(Self::F32),
1475 Self::VecI64(vec) => vec.get(idx).cloned().map(Self::I64),
1476 Self::VecU64(vec) => vec.get(idx).cloned().map(Self::U64),
1477 Self::VecF64(vec) => vec.get(idx).cloned().map(Self::F64),
1478 Self::StructView { addr, ty } => {
1479 if let Type::Struct { params: _, fields } = ty.as_ref() {
1480 fields.get(idx).and_then(|(_, field_ty)| Self::read_struct_field(*addr, idx, field_ty, ty.as_ref(), None))
1481 } else {
1482 Self::read_aggregate_index(*addr, idx, ty.as_ref(), None)
1483 }
1484 }
1485 Self::StructOwned { storage, ty } => Self::read_aggregate_index(storage.addr(), idx, ty.as_ref(), Some(storage)),
1486 _ => None,
1487 }
1488 }
1489
1490 fn read_aggregate_index(addr: usize, idx: usize, ty: &Type, storage: Option<&StructBytes>) -> Option<Self> {
1491 match ty {
1492 Type::Struct { fields, .. } => fields.get(idx).and_then(|(_, field_ty)| Self::read_struct_field(addr, idx, field_ty, ty, storage)),
1493 Type::Array(elem_ty, len) | Type::Vec(elem_ty, len) => {
1494 if idx >= *len as usize {
1495 return None;
1496 }
1497 let elem_addr = addr + idx * elem_ty.storage_width() as usize;
1498 Some(Self::read_aggregate_value(elem_addr, elem_ty, storage, elem_addr.saturating_sub(addr)))
1499 }
1500 _ => None,
1501 }
1502 }
1503
1504 fn read_aggregate_value(addr: usize, ty: &Type, storage: Option<&StructBytes>, offset: usize) -> Self {
1505 match ty {
1506 Type::Bool => Dynamic::Bool(unsafe { std::ptr::read_unaligned(addr as *const u8) } != 0),
1507 Type::I8 => Dynamic::I8(unsafe { std::ptr::read_unaligned(addr as *const i8) }),
1508 Type::U8 => Dynamic::U8(unsafe { std::ptr::read_unaligned(addr as *const u8) }),
1509 Type::I16 => Dynamic::I16(unsafe { std::ptr::read_unaligned(addr as *const i16) }),
1510 Type::U16 => Dynamic::U16(unsafe { std::ptr::read_unaligned(addr as *const u16) }),
1511 Type::I32 => Dynamic::I32(unsafe { std::ptr::read_unaligned(addr as *const i32) }),
1512 Type::U32 => Dynamic::U32(unsafe { std::ptr::read_unaligned(addr as *const u32) }),
1513 Type::I64 => Dynamic::I64(unsafe { std::ptr::read_unaligned(addr as *const i64) }),
1514 Type::U64 => Dynamic::U64(unsafe { std::ptr::read_unaligned(addr as *const u64) }),
1515 Type::F32 => Dynamic::F32(unsafe { std::ptr::read_unaligned(addr as *const f32) }),
1516 Type::F64 => Dynamic::F64(unsafe { std::ptr::read_unaligned(addr as *const f64) }),
1517 ty if ty.is_struct() || ty.is_array() || ty.is_vec() => {
1518 if storage.is_some() {
1519 Dynamic::owned_struct_from_ptr(addr, ty.clone())
1520 } else {
1521 Dynamic::struct_view(addr, ty.clone())
1522 }
1523 }
1524 _ => Self::read_dynamic_ptr(addr, storage, offset).unwrap_or(Dynamic::Null),
1525 }
1526 }
1527
1528 pub fn into_iter(self) -> Self {
1529 if self.is_map() {
1530 let keys = self.keys();
1531 Self::Iter { idx: 0, keys, value: Box::new(self) }
1532 } else {
1533 Self::Iter { idx: 0, keys: Vec::new(), value: Box::new(self) }
1534 }
1535 }
1536
1537 pub fn next(&mut self) -> Option<Self> {
1538 if let Self::Iter { idx, keys, value } = self {
1539 if !keys.is_empty() {
1540 if *idx < keys.len() {
1541 let k = keys[*idx].clone();
1542 let v = value.get_dynamic(k.as_str()).unwrap();
1543 *idx += 1;
1544 return Some(v);
1545 }
1546 } else {
1547 if let Some(v) = value.get_idx(*idx) {
1548 *idx += 1;
1549 return Some(v);
1550 }
1551 }
1552 }
1553 None
1554 }
1555
1556 pub fn next_pair(&mut self) -> Option<Self> {
1557 if let Self::Iter { idx, keys, value } = self {
1558 if !keys.is_empty() {
1559 if *idx < keys.len() {
1560 let k = keys[*idx].clone();
1561 let v = value.get_dynamic(k.as_str()).unwrap();
1562 *idx += 1;
1563 return Some(list!(k, v));
1564 }
1565 } else {
1566 if let Some(v) = value.get_idx(*idx) {
1567 *idx += 1;
1568 return Some(v);
1569 }
1570 }
1571 }
1572 None
1573 }
1574
1575 pub fn set_idx(&mut self, idx: usize, val: Dynamic) {
1576 match self {
1577 Self::List(list) => {
1578 list.write().get_mut(idx).map(|l| *l = val);
1579 }
1580 Self::VecI8(vec) => {
1581 if let Ok(value) = val.try_into() {
1582 vec.set(idx, value);
1583 }
1584 }
1585 Self::VecU16(vec) => {
1586 if let Ok(value) = val.try_into() {
1587 vec.set(idx, value);
1588 }
1589 }
1590 Self::VecI16(vec) => {
1591 if let Ok(value) = val.try_into() {
1592 vec.set(idx, value);
1593 }
1594 }
1595 Self::VecU32(vec) => {
1596 if let Ok(value) = val.try_into() {
1597 vec.set(idx, value);
1598 }
1599 }
1600 Self::VecI32(vec) => {
1601 if let Ok(value) = val.try_into() {
1602 vec.set(idx, value);
1603 }
1604 }
1605 Self::VecF32(vec) => {
1606 if let Ok(value) = val.try_into() {
1607 vec.set(idx, value);
1608 }
1609 }
1610 Self::VecI64(vec) => {
1611 if let Some(slot) = vec.get_mut(idx)
1612 && let Ok(value) = val.try_into()
1613 {
1614 *slot = value;
1615 }
1616 }
1617 Self::VecU64(vec) => {
1618 if let Some(slot) = vec.get_mut(idx)
1619 && let Ok(value) = val.try_into()
1620 {
1621 *slot = value;
1622 }
1623 }
1624 Self::VecF64(vec) => {
1625 if let Some(slot) = vec.get_mut(idx)
1626 && let Ok(value) = val.try_into()
1627 {
1628 *slot = value;
1629 }
1630 }
1631 Self::StructView { addr, ty } => {
1632 if let Type::Struct { params: _, fields } = ty.as_ref()
1633 && let Some((_, field_ty)) = fields.get(idx)
1634 {
1635 Self::write_struct_field(*addr, idx, field_ty, ty.as_ref(), val, None);
1636 } else {
1637 Self::write_aggregate_index(*addr, idx, ty.as_ref(), val, None);
1638 }
1639 }
1640 Self::StructOwned { storage, ty } => {
1641 if let Type::Struct { params: _, fields } = ty.as_ref()
1642 && let Some((_, field_ty)) = fields.get(idx)
1643 {
1644 Self::write_struct_field(storage.addr(), idx, field_ty, ty.as_ref(), val, Some(storage));
1645 } else {
1646 Self::write_aggregate_index(storage.addr(), idx, ty.as_ref(), val, Some(storage));
1647 }
1648 }
1649 _ => {}
1650 }
1651 }
1652
1653 fn write_aggregate_index(addr: usize, idx: usize, ty: &Type, val: Dynamic, storage: Option<&StructBytes>) {
1654 let (elem_ty, len) = match ty {
1655 Type::Array(elem_ty, len) | Type::Vec(elem_ty, len) => (elem_ty.as_ref(), *len as usize),
1656 _ => return,
1657 };
1658 if idx >= len {
1659 return;
1660 }
1661 let offset = idx * elem_ty.storage_width() as usize;
1662 let elem_addr = addr + offset;
1663 if let Some(storage) = storage {
1664 storage.clear_dynamic_fields_in(offset, elem_ty.storage_width() as usize);
1665 }
1666 match elem_ty {
1667 Type::Bool => unsafe { std::ptr::write_unaligned(elem_addr as *mut u8, if val.is_true() { 1 } else { 0 }) },
1668 Type::I8 => unsafe { std::ptr::write_unaligned(elem_addr as *mut i8, val.try_into().unwrap_or_default()) },
1669 Type::U8 => unsafe { std::ptr::write_unaligned(elem_addr as *mut u8, val.try_into().unwrap_or_default()) },
1670 Type::I16 => unsafe { std::ptr::write_unaligned(elem_addr as *mut i16, val.try_into().unwrap_or_default()) },
1671 Type::U16 => unsafe { std::ptr::write_unaligned(elem_addr as *mut u16, val.try_into().unwrap_or_default()) },
1672 Type::I32 => unsafe { std::ptr::write_unaligned(elem_addr as *mut i32, val.try_into().unwrap_or_default()) },
1673 Type::U32 => unsafe { std::ptr::write_unaligned(elem_addr as *mut u32, val.try_into().unwrap_or_default()) },
1674 Type::I64 => unsafe { std::ptr::write_unaligned(elem_addr as *mut i64, val.try_into().unwrap_or_default()) },
1675 Type::U64 => unsafe { std::ptr::write_unaligned(elem_addr as *mut u64, val.try_into().unwrap_or_default()) },
1676 Type::F32 => unsafe { std::ptr::write_unaligned(elem_addr as *mut f32, f32::try_from(val).unwrap_or_default()) },
1677 Type::F64 => unsafe { std::ptr::write_unaligned(elem_addr as *mut f64, f64::try_from(val).unwrap_or_default()) },
1678 ty if ty.is_struct() || ty.is_array() || ty.is_vec() => {
1679 if let Some((src_addr, _)) = val.struct_addr_ty() {
1680 unsafe {
1681 std::ptr::copy_nonoverlapping(src_addr as *const u8, elem_addr as *mut u8, elem_ty.storage_width() as usize);
1682 }
1683 if let Some(storage) = storage {
1684 storage.clone_dynamic_fields_from(src_addr, elem_ty, offset);
1685 }
1686 }
1687 }
1688 _ => Self::write_dynamic_ptr(elem_addr, val, storage, offset),
1689 }
1690 }
1691
1692 pub fn to_markdown(&self) -> String {
1693 let mut s = String::new();
1694 if let Self::Map(m) = self {
1695 for (key, v) in m.read().iter() {
1696 s.push_str(&format!("#### ```{}```\n", key));
1697 s.push_str(&v.to_markdown());
1698 s.push('\n');
1699 }
1700 } else if let Self::Bytes(bytes) = self {
1701 s = format!("[{}...]", hex::encode(&bytes[..8]));
1702 } else {
1703 let len = self.len();
1704 if len > 0 {
1705 for idx in 0..len {
1706 s.push_str(&format!("- {}\n", self.get_idx(idx).unwrap().to_markdown()));
1707 }
1708 } else {
1709 s = self.to_string();
1710 }
1711 }
1712 s
1713 }
1714}
1715
1716#[cfg(test)]
1717mod tests {
1718 use super::*;
1719 use parking_lot::RwLock;
1720
1721 #[derive(Debug, PartialEq)]
1722 struct CustomCounter {
1723 value: i64,
1724 }
1725
1726 #[test]
1727 fn type_add_promotion_rules() {
1728 use crate::Type;
1729 assert_eq!(Type::I32 + Type::I32, Type::I32);
1731 assert_eq!(Type::I32 + Type::Str, Type::Str);
1733 assert_eq!(Type::I32 + Type::Any, Type::Any);
1735 assert_eq!(Type::I64 + Type::F32, Type::F32);
1737 assert_eq!(Type::F32 + Type::F64, Type::F64);
1738 assert_eq!(Type::I8 + Type::I32, Type::I32);
1740 assert_eq!(Type::I32 + Type::I64, Type::I64);
1741 assert_eq!(Type::I32 + Type::U32, Type::I32);
1743 assert_eq!(Type::U8 + Type::U32, Type::U32);
1745 }
1746
1747 #[test]
1748 fn dynamic_enum_stays_compact() {
1749 assert_eq!(std::mem::size_of::<Dynamic>(), 40);
1750 }
1751
1752 #[test]
1753 fn custom_values_can_be_downcast_and_shared_by_clone() {
1754 let value = Dynamic::custom(RwLock::new(CustomCounter { value: 7 }));
1755 assert!(value.is_custom());
1756 assert!(value.custom_type_name().is_some());
1757
1758 let cloned = value.clone();
1759 assert_eq!(cloned.as_custom::<RwLock<CustomCounter>>().unwrap().read().value, 7);
1760
1761 cloned.as_custom::<RwLock<CustomCounter>>().unwrap().write().value = 9;
1762 assert_eq!(value.as_custom::<RwLock<CustomCounter>>().unwrap().read().value, 9);
1763 assert_eq!(value, cloned);
1764 }
1765
1766 #[derive(Debug, Default)]
1767 struct CustomPropertyBag {
1768 values: RwLock<BTreeMap<SmolStr, Dynamic>>,
1769 }
1770
1771 impl CustomProperty for CustomPropertyBag {
1772 fn get_key(&self, key: &str) -> Option<Dynamic> {
1773 self.values.read().get(key).cloned()
1774 }
1775
1776 fn set_key(&self, key: &str, value: Dynamic) -> bool {
1777 self.values.write().insert(key.into(), value);
1778 true
1779 }
1780 }
1781
1782 #[test]
1783 fn custom_values_can_forward_dynamic_properties() {
1784 let value = Dynamic::custom_with_properties(CustomPropertyBag::default());
1785
1786 value.set_dynamic("file_mode".into(), 2i64);
1787
1788 assert!(value.contains("file_mode"));
1789 assert_eq!(value.get_dynamic("file_mode").and_then(|value| value.as_int()), Some(2));
1790 }
1791
1792 #[test]
1793 fn deep_clone_recursively_copies_maps_and_lists() {
1794 let nested = Dynamic::map(Default::default());
1795 nested.insert("score", 1);
1796
1797 let value = Dynamic::map(Default::default());
1798 value.insert("nested", nested.clone());
1799 value.insert("items", Dynamic::list(vec![nested.clone()]));
1800
1801 let cloned = value.deep_clone();
1802 cloned.get_dynamic("nested").unwrap().insert("score", 2);
1803 cloned.get_dynamic("items").unwrap().get_idx(0).unwrap().insert("score", 3);
1804
1805 assert_eq!(value.get_dynamic("nested").unwrap().get_dynamic("score").and_then(|v| v.as_int()), Some(1));
1806 assert_eq!(value.get_dynamic("items").unwrap().get_idx(0).unwrap().get_dynamic("score").and_then(|v| v.as_int()), Some(1));
1807 }
1808
1809 #[test]
1810 fn string_add_keeps_concat_semantics() {
1811 let left = Dynamic::from("hello");
1812 let right = Dynamic::from(" world");
1813 let joined = left + right;
1814 assert!(matches!(joined, Dynamic::StringBuf(_)));
1815 assert_eq!(joined.as_str(), "hello world");
1816
1817 assert_eq!((Dynamic::from("level ") + Dynamic::I64(7)).as_str(), "level 7");
1818 assert_eq!((Dynamic::I64(7) + Dynamic::from(" days")).as_str(), "7 days");
1819 }
1820
1821 #[test]
1822 fn string_add_reuses_string_buf_after_first_concat() {
1823 let mut value = Dynamic::from("a") + Dynamic::from("b");
1824 assert!(matches!(value, Dynamic::StringBuf(_)));
1825
1826 value = value + Dynamic::from("c");
1827 assert!(matches!(value, Dynamic::StringBuf(_)));
1828 assert_eq!(value.as_str(), "abc");
1829 }
1830
1831 #[test]
1832 fn u64_as_int_does_not_wrap() {
1833 assert_eq!(Dynamic::U64(i64::MAX as u64).as_int(), Some(i64::MAX));
1834 assert_eq!(Dynamic::U64(i64::MAX as u64 + 1).as_int(), None);
1835 }
1836
1837 #[test]
1838 fn dynamic_integer_ops_report_fault_instead_of_panicking() {
1839 let _ = take_fault();
1840 assert_eq!(Dynamic::U64(u64::MAX) + Dynamic::U64(1), Dynamic::Null);
1841 assert!(take_fault().is_some());
1842
1843 assert_eq!(Dynamic::I64(i64::MAX) + Dynamic::I64(1), Dynamic::Null);
1844 assert!(take_fault().is_some());
1845
1846 assert_eq!(Dynamic::I32(1) << Dynamic::I32(64), Dynamic::Null);
1847 assert!(take_fault().is_some());
1848 }
1849
1850 #[test]
1851 fn typed_vec_set_idx_ignores_bad_index_or_value_without_panicking() {
1852 let mut values = Dynamic::VecI64(vec![1, 2, 3]);
1853 values.set_idx(10, Dynamic::I64(99));
1854 assert_eq!(values.get_idx(2).and_then(|value| value.as_int()), Some(3));
1855
1856 values.set_idx(1, Dynamic::from("bad"));
1857 assert_eq!(values.get_idx(1).and_then(|value| value.as_int()), Some(2));
1858
1859 values.set_idx(1, Dynamic::I64(7));
1860 assert_eq!(values.get_idx(1).and_then(|value| value.as_int()), Some(7));
1861 }
1862
1863 #[test]
1864 fn nested_struct_fields_use_inline_storage() {
1865 let inner_ty = Type::Struct { params: vec![], fields: vec![("value".into(), Type::I64)] };
1866 let outer_ty = Type::Struct { params: vec![], fields: vec![("inner".into(), inner_ty.clone()), ("tag".into(), Type::I64)] };
1867
1868 let mut inner_bytes = vec![0u8; inner_ty.storage_width() as usize];
1869 let mut outer_bytes = vec![0u8; outer_ty.storage_width() as usize];
1870 let inner = Dynamic::struct_view(inner_bytes.as_mut_ptr() as usize, inner_ty);
1871 let outer = Dynamic::struct_view(outer_bytes.as_mut_ptr() as usize, outer_ty);
1872
1873 inner.set_dynamic("value".into(), Dynamic::I64(17));
1874 outer.set_dynamic("inner".into(), inner);
1875 outer.set_dynamic("tag".into(), Dynamic::I64(3));
1876
1877 let read_inner = outer.get_dynamic("inner").expect("inner field");
1878 assert_eq!(read_inner.get_dynamic("value").and_then(|value| value.as_int()), Some(17));
1879 assert_eq!(outer.get_dynamic("tag").and_then(|value| value.as_int()), Some(3));
1880 }
1881
1882 #[test]
1883 fn owned_struct_clones_dynamic_pointer_fields() {
1884 let ty = Type::Struct { params: vec![], fields: vec![("name".into(), Type::Str)] };
1885 let mut bytes = vec![0u8; ty.storage_width() as usize];
1886 let original = Box::into_raw(Box::new(Dynamic::from("alpha"))) as usize;
1887 unsafe {
1888 std::ptr::write_unaligned(bytes.as_mut_ptr() as *mut usize, original);
1889 }
1890
1891 let owned = Dynamic::owned_struct_from_ptr(bytes.as_ptr() as usize, ty);
1892 unsafe {
1893 drop(Box::from_raw(original as *mut Dynamic));
1894 }
1895
1896 assert_eq!(owned.get_dynamic("name").map(|value| value.as_str().to_string()), Some("alpha".to_string()));
1897 owned.set_dynamic("name".into(), Dynamic::from("beta"));
1898 assert_eq!(owned.get_dynamic("name").map(|value| value.as_str().to_string()), Some("beta".to_string()));
1899 }
1900
1901 #[test]
1902 fn aggregate_array_fields_support_dynamic_index_access() {
1903 let ty = Type::Array(std::rc::Rc::new(Type::I64), 3);
1904 let mut bytes = vec![0u8; ty.storage_width() as usize];
1905 for (idx, value) in [3i64, 5, 7].into_iter().enumerate() {
1906 unsafe {
1907 std::ptr::write_unaligned(bytes.as_mut_ptr().add(idx * 8) as *mut i64, value);
1908 }
1909 }
1910
1911 let mut array = Dynamic::owned_struct_from_ptr(bytes.as_ptr() as usize, ty);
1912 assert_eq!(array.get_idx(1).and_then(|value| value.as_int()), Some(5));
1913 array.set_idx(1, Dynamic::I64(11));
1914 assert_eq!(array.get_idx(1).and_then(|value| value.as_int()), Some(11));
1915 }
1916
1917 #[test]
1918 fn f16_roundtrip_via_helpers() {
1919 let bits = f64_to_f16(1.0);
1920 assert_eq!(bits, 0x3C00);
1921 assert_eq!(f16_to_f64(bits), 1.0);
1922 let bits = f64_to_f16(0.5);
1923 assert_eq!(bits, 0x3800);
1924 assert_eq!(f16_to_f64(bits), 0.5);
1925 }
1926
1927 #[test]
1928 fn f16_dynamic_get_type_and_is_float() {
1929 let v = Dynamic::F16(0x3C00);
1930 assert_eq!(v.get_type(), Type::F16);
1931 assert!(v.is_f16());
1932 assert!(v.is_signed());
1933 assert_eq!(v.size_of(), 2);
1934 assert_eq!(v.as_float(), Some(1.0));
1935 }
1936
1937 #[test]
1938 fn f16_force_from_f64_preserves_value() {
1939 let d = Type::F16.force(Dynamic::F64(2.0)).unwrap();
1940 let Dynamic::F16(bits) = d else {
1941 panic!("expected F16");
1942 };
1943 assert_eq!(bits, 0x4000);
1944 assert_eq!(f16_to_f64(bits), 2.0);
1945 }
1946
1947 #[test]
1948 fn f16_compare_equal_by_bits() {
1949 assert_eq!(Dynamic::F16(0x3C00), Dynamic::F16(0x3C00));
1950 assert_ne!(Dynamic::F16(0x3C00), Dynamic::F16(0x4000));
1951 }
1952
1953 #[test]
1954 fn f16_subnormal_roundtrip() {
1955 let bits = f64_to_f16(5.96e-8);
1957 assert_eq!(bits, 0x0001);
1958 let back = f16_to_f64(bits);
1959 let expected = half::f16::from_bits(0x0001).to_f64();
1960 assert_eq!(back, expected, "got {back}");
1961 }
1962
1963 #[test]
1964 fn f16_infinity_roundtrip() {
1965 let bits = f64_to_f16(f64::INFINITY);
1966 assert_eq!(bits, 0x7C00);
1967 assert!(f16_to_f64(bits).is_infinite());
1968
1969 let bits = f64_to_f16(f64::NEG_INFINITY);
1970 assert_eq!(bits, 0xFC00);
1971 assert!(f16_to_f64(bits).is_sign_negative());
1972 }
1973
1974 #[test]
1975 fn fn_type_partial_eq_with_diff_ret_returns_false_not_panic() {
1976 use std::rc::Rc;
1977 let a = Type::Fn { tys: vec![Type::I32], ret: Rc::new(Type::I32) };
1978 let b = Type::Fn { tys: vec![Type::I32], ret: Rc::new(Type::F32) };
1979 assert!(a != b);
1980 assert!(!(a == b));
1981 }
1982
1983 #[test]
1984 fn fn_type_partial_eq_same_args_same_ret_is_true() {
1985 use std::rc::Rc;
1986 let a = Type::Fn { tys: vec![Type::I32], ret: Rc::new(Type::I32) };
1987 let b = Type::Fn { tys: vec![Type::I32], ret: Rc::new(Type::I32) };
1988 assert!(a == b);
1989 }
1990
1991 #[test]
1992 fn fn_type_partial_eq_diff_args_returns_false() {
1993 use std::rc::Rc;
1994 let a = Type::Fn { tys: vec![Type::I32], ret: Rc::new(Type::Void) };
1995 let b = Type::Fn { tys: vec![Type::I64], ret: Rc::new(Type::Void) };
1996 assert!(a != b);
1997 }
1998
1999 #[test]
2000 fn fn_type_partial_eq_with_any_ret_is_false() {
2001 use std::rc::Rc;
2002 let a = Type::Fn { tys: vec![Type::I32], ret: Rc::new(Type::Any) };
2003 let b = Type::Fn { tys: vec![Type::I32], ret: Rc::new(Type::I32) };
2004 assert!(a != b);
2005 }
2006}
2007
2008#[macro_export]
2009macro_rules! assert_ok {
2010 ( $x: expr, $ok: expr) => {
2011 if $x {
2012 return Ok($ok);
2013 }
2014 };
2015}
2016
2017#[macro_export]
2018macro_rules! assert_err {
2019 ( $x: expr, $err: expr) => {
2020 if $x {
2021 return Err($err);
2022 }
2023 };
2024}
2025
2026pub struct ZOnce {
2027 first: Option<&'static str>,
2028 other: &'static str,
2029}
2030
2031impl ZOnce {
2032 pub fn new(first: &'static str, other: &'static str) -> Self {
2033 Self { first: Some(first), other }
2034 }
2035 pub fn take(&mut self) -> &'static str {
2036 self.first.take().unwrap_or(self.other)
2037 }
2038}
2039
2040mod fixvec;
2041pub use fixvec::FixVec;
2042mod msgpack;
2043pub use msgpack::{MsgPack, MsgUnpack};
2044
2045pub use json::{FromJson, ToJson};
2046
2047mod fault;
2048pub use fault::{has_fault, set_fault, take_fault};
2049mod ops;
2050mod types;
2051pub use types::{ConstIntOp, Type, call_fn, set_dynamic_return_handler};
2052
2053#[macro_export]
2054macro_rules! list {
2055 ($($v:expr),+ $(,)?) => {{
2056 let mut list = Vec::new();
2057 $( let _ = list.push(Dynamic::from($v)); )*
2058 Dynamic::List(::std::sync::Arc::new($crate::RwLock::new(list)))
2059 }};
2060}
2061
2062#[macro_export]
2063macro_rules! map {
2064 ($($k:expr => $v:expr), *) => {{
2065 let mut obj = std::collections::BTreeMap::new();
2066 $( let _ = obj.insert(smol_str::SmolStr::from($k), Dynamic::from($v)); )*
2067 Dynamic::map(obj)
2068 }};
2069}