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