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::U8(v) => v.try_into().map_err(|_| DynamicErr::OutOfRange),
411 Dynamic::U16(v) => v.try_into().map_err(|_| DynamicErr::OutOfRange),
412 Dynamic::U32(v) => v.try_into().map_err(|_| DynamicErr::OutOfRange),
413 Dynamic::U64(v) => v.try_into().map_err(|_| DynamicErr::OutOfRange),
414 Dynamic::I8(v) => v.try_into().map_err(|_| DynamicErr::OutOfRange),
415 Dynamic::I16(v) => v.try_into().map_err(|_| DynamicErr::OutOfRange),
416 Dynamic::I32(v) => v.try_into().map_err(|_| DynamicErr::OutOfRange),
417 Dynamic::I64(v) => v.try_into().map_err(|_| DynamicErr::OutOfRange),
418 _ => Err(DynamicErr::TypeMismatch),
419 }
420 }
421 }
422 )+
423 };
424}
425impl_try_from_dynamic_int!(u8, u16, u32, u64, i8, i16, i32, i64);
426
427impl TryFrom<Dynamic> for f64 {
428 type Error = DynamicErr;
429 fn try_from(value: Dynamic) -> Result<Self, Self::Error> {
430 match value {
431 Dynamic::F32(v) => Ok(v as f64),
432 Dynamic::F64(v) => Ok(v),
433 Dynamic::U8(v) => Ok(v as f64),
434 Dynamic::U16(v) => Ok(v as f64),
435 Dynamic::U32(v) => Ok(v as f64),
436 Dynamic::U64(v) => Ok(v as f64),
437 Dynamic::I8(v) => Ok(v as f64),
438 Dynamic::I16(v) => Ok(v as f64),
439 Dynamic::I32(v) => Ok(v as f64),
440 Dynamic::I64(v) => Ok(v as f64),
441 _ => Err(DynamicErr::TypeMismatch),
442 }
443 }
444}
445
446impl TryFrom<Dynamic> for f32 {
447 type Error = DynamicErr;
448 fn try_from(value: Dynamic) -> Result<Self, Self::Error> {
449 match value {
450 Dynamic::F32(v) => Ok(v),
451 Dynamic::F64(v) => Ok(v as f32),
452 Dynamic::U8(v) => Ok(v as f32),
453 Dynamic::U16(v) => Ok(v as f32),
454 Dynamic::U32(v) => Ok(v as f32),
455 Dynamic::U64(v) => Ok(v as f32),
456 Dynamic::I8(v) => Ok(v as f32),
457 Dynamic::I16(v) => Ok(v as f32),
458 Dynamic::I32(v) => Ok(v as f32),
459 Dynamic::I64(v) => Ok(v as f32),
460 _ => Err(DynamicErr::TypeMismatch),
461 }
462 }
463}
464
465impl TryFrom<Dynamic> for bool {
466 type Error = DynamicErr;
467 fn try_from(value: Dynamic) -> Result<Self, Self::Error> {
468 match value {
469 Dynamic::Bool(v) => Ok(v),
470 Dynamic::U8(v) => Ok(v != 0),
471 Dynamic::U16(v) => Ok(v != 0),
472 Dynamic::U32(v) => Ok(v != 0),
473 Dynamic::U64(v) => Ok(v != 0),
474 Dynamic::I8(v) => Ok(v != 0),
475 Dynamic::I16(v) => Ok(v != 0),
476 Dynamic::I32(v) => Ok(v != 0),
477 Dynamic::I64(v) => Ok(v != 0),
478 _ => Err(DynamicErr::TypeMismatch),
479 }
480 }
481}
482
483impl TryFrom<Dynamic> for SmolStr {
484 type Error = DynamicErr;
485 fn try_from(value: Dynamic) -> Result<Self, Self::Error> {
486 match value {
487 Dynamic::String(s) => Ok(s),
488 Dynamic::StringBuf(s) => Ok(s.into()),
489 _ => Err(DynamicErr::TypeMismatch),
490 }
491 }
492}
493
494macro_rules! impl_dynamic_vec_from_slice {
495 ($variant:ident, $ty:ty) => {
496 impl From<&[$ty]> for Dynamic {
497 fn from(vec: &[$ty]) -> Self {
498 Dynamic::$variant(MyVec::from(vec))
499 }
500 }
501
502 impl<const N: usize> From<[$ty; N]> for Dynamic {
503 fn from(vec: [$ty; N]) -> Self {
504 Dynamic::$variant(MyVec::from(vec))
505 }
506 }
507 };
508}
509
510impl_dynamic_vec_from_slice!(VecI8, i8);
511impl_dynamic_vec_from_slice!(VecU16, u16);
512impl_dynamic_vec_from_slice!(VecI16, i16);
513impl_dynamic_vec_from_slice!(VecU32, u32);
514impl_dynamic_vec_from_slice!(VecI32, i32);
515impl_dynamic_vec_from_slice!(VecF32, f32);
516
517impl From<&[u8]> for Dynamic {
518 fn from(vec: &[u8]) -> Self {
519 Dynamic::Bytes(vec.to_vec())
520 }
521}
522
523impl From<Vec<u8>> for Dynamic {
524 fn from(vec: Vec<u8>) -> Self {
525 Dynamic::Bytes(vec)
526 }
527}
528
529impl From<&[u64]> for Dynamic {
530 fn from(vec: &[u64]) -> Self {
531 Dynamic::VecU64(vec.to_vec())
532 }
533}
534
535impl<const N: usize> From<[u64; N]> for Dynamic {
536 fn from(vec: [u64; N]) -> Self {
537 Dynamic::VecU64(vec.to_vec())
538 }
539}
540
541impl From<&[i64]> for Dynamic {
542 fn from(vec: &[i64]) -> Self {
543 Dynamic::VecI64(vec.to_vec())
544 }
545}
546impl<const N: usize> From<[i64; N]> for Dynamic {
547 fn from(vec: [i64; N]) -> Self {
548 Dynamic::VecI64(vec.to_vec())
549 }
550}
551
552impl From<&[f64]> for Dynamic {
553 fn from(vec: &[f64]) -> Self {
554 Dynamic::VecF64(vec.to_vec())
555 }
556}
557impl<const N: usize> From<[f64; N]> for Dynamic {
558 fn from(vec: [f64; N]) -> Self {
559 Dynamic::VecF64(vec.to_vec())
560 }
561}
562
563impl<T: Into<Dynamic>> From<Vec<T>> for Dynamic {
564 fn from(vec: Vec<T>) -> Self {
565 let vec = vec.into_iter().map(|v| v.into()).collect();
566 Dynamic::List(Arc::new(RwLock::new(vec)))
567 }
568}
569
570impl From<String> for Dynamic {
571 fn from(s: String) -> Self {
572 Dynamic::String(s.into())
573 }
574}
575
576impl ToString for Dynamic {
577 fn to_string(&self) -> String {
578 match self {
579 Self::Null => "()".into(),
580 Self::Bool(b) => {
581 if *b {
582 "true".into()
583 } else {
584 "false".into()
585 }
586 }
587 Self::U8(u) => u.to_string(),
588 Self::U16(u) => u.to_string(),
589 Self::U32(u) => u.to_string(),
590 Self::U64(u) => u.to_string(),
591 Self::I8(u) => u.to_string(),
592 Self::I16(u) => u.to_string(),
593 Self::I32(u) => u.to_string(),
594 Self::I64(u) => u.to_string(),
595 Self::F32(u) => u.to_string(),
596 Self::F64(u) => u.to_string(),
597 Self::String(s) => s.to_string(),
598 Self::StringBuf(s) => s.clone(),
599 _ => {
600 let mut buf = String::new();
601 self.to_json(&mut buf);
602 if buf.is_empty() { format!("{:?}", self) } else { buf }
603 }
604 }
605 }
606}
607
608use anyhow::Result;
609impl Dynamic {
610 pub fn custom<T>(value: T) -> Self
611 where
612 T: Any + Send + Sync + 'static,
613 {
614 Self::Custom(CustomValue::new(value))
615 }
616
617 pub fn custom_arc<T>(value: Arc<T>) -> Self
618 where
619 T: Any + Send + Sync + 'static,
620 {
621 Self::Custom(CustomValue::from_arc(value))
622 }
623
624 pub fn custom_with_properties<T>(value: T) -> Self
625 where
626 T: CustomProperty + 'static,
627 {
628 Self::Custom(CustomValue::new_with_properties(value))
629 }
630
631 pub fn custom_property_arc<T>(value: Arc<T>) -> Self
632 where
633 T: CustomProperty + 'static,
634 {
635 Self::Custom(CustomValue::from_property_arc(value))
636 }
637
638 pub fn is_custom(&self) -> bool {
639 matches!(self, Self::Custom(_))
640 }
641
642 pub fn custom_type_name(&self) -> Option<&'static str> {
643 if let Self::Custom(value) = self { Some(value.custom_type_name()) } else { None }
644 }
645
646 pub fn as_custom<T>(&self) -> Option<&T>
647 where
648 T: Any + Send + Sync,
649 {
650 if let Self::Custom(value) = self { value.as_any().downcast_ref::<T>() } else { None }
651 }
652
653 pub fn deep_clone(&self) -> Self {
654 match self {
655 Self::Map(m) => {
656 let m = m.read().unwrap().iter().map(|(k, v)| (k.clone(), v.deep_clone())).collect();
657 Self::map(m)
658 }
659 Self::List(l) => {
660 let l = l.read().unwrap().iter().map(|item| item.deep_clone()).collect();
661 Self::list(l)
662 }
663 Self::Struct { addr, ty } => Self::Struct { addr: *addr, ty: ty.clone() },
664 _ => self.clone(),
665 }
666 }
667
668 pub fn add(&mut self, val: i64) -> Option<i64> {
669 match self {
671 Self::U8(u) => {
672 let v = (*u as i64) + val;
673 *u = v as u8;
674 Some(v)
675 }
676 Self::U16(u) => {
677 let v = (*u as i64) + val;
678 *u = v as u16;
679 Some(v)
680 }
681 Self::U32(u) => {
682 let v = (*u as i64) + val;
683 *u = v as u32;
684 Some(v)
685 }
686 Self::U64(u) => {
687 let v = (*u as i64) + val;
688 *u = v as u64;
689 Some(v)
690 }
691 Self::I8(i) => {
692 let v = (*i as i64) + val;
693 *i = v as i8;
694 Some(v)
695 }
696 Self::I16(i) => {
697 let v = (*i as i64) + val;
698 *i = v as i16;
699 Some(v)
700 }
701 Self::I32(i) => {
702 let v = (*i as i64) + val;
703 *i = v as i32;
704 Some(v)
705 }
706 Self::I64(i) => {
707 let v = (*i as i64) + val;
708 *i = v;
709 Some(v)
710 }
711 _ => None,
712 }
713 }
714
715 pub fn is_vec(&self) -> bool {
716 use Dynamic::*;
717 match self {
718 VecI8(_) | VecU16(_) | Self::VecI16(_) | VecU32(_) | VecI32(_) | VecF32(_) | VecU64(_) | VecI64(_) | VecF64(_) => true,
719 _ => false,
720 }
721 }
722
723 pub fn as_bytes(&self) -> Option<&[u8]> {
724 match self {
725 Self::Bytes(b) => Some(b.as_slice()),
726 _ => None,
727 }
728 }
729
730 pub fn as_str(&self) -> &str {
731 match self {
732 Dynamic::String(s) => s.as_str(),
733 Dynamic::StringBuf(s) => s.as_str(),
734 _ => "",
735 }
736 }
737
738 pub fn is_native(&self) -> bool {
739 if self.is_f64() || self.is_f32() || self.is_int() || self.is_true() || self.is_false() { true } else { false }
740 }
741
742 pub fn from_utf8(buf: &[u8]) -> Result<Self> {
743 Ok(Dynamic::from(SmolStr::new(std::str::from_utf8(buf)?)))
744 }
745
746 pub fn append(&self, other: Self) {
747 match (self, other) {
748 (Self::List(left), rhs) => {
749 if let Self::List(right) = rhs {
750 left.write().unwrap().append(&mut right.write().unwrap());
751 } else {
752 left.write().unwrap().push(rhs);
753 }
754 }
755 (Self::Map(left), Self::Map(right)) => {
756 left.write().unwrap().append(&mut right.write().unwrap());
757 }
758 (_, _) => {}
759 }
760 }
761
762 pub fn into_vec<T: TryFrom<Self> + 'static>(self) -> Option<Vec<T>> {
763 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<Dynamic>() {
764 match self {
765 Dynamic::List(list) => {
766 match Arc::try_unwrap(list) {
767 Ok(vec) => vec.into_inner().map(|v| unsafe { mem::transmute::<Vec<Dynamic>, Vec<T>>(v) }).ok(), Err(_) => None, }
770 }
771 _ => {
772 let mut vec = Vec::with_capacity(self.len());
773 for idx in 0..self.len() {
774 if let Some(item) = self.get_idx(idx) {
775 vec.push(item);
776 }
777 }
778 Some(unsafe { mem::transmute(vec) })
779 }
780 }
781 } else {
782 match self {
783 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()),
784 Dynamic::Bytes(vec) => {
785 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u8>() {
786 let bytes_vec: Vec<u8> = Vec::from(vec);
787 Some(unsafe { mem::transmute(bytes_vec) })
788 } else {
789 None
790 }
791 }
792 Dynamic::VecI8(vec) => {
793 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i8>() {
794 let vec_i8: Vec<i8> = Vec::from(vec);
795 Some(unsafe { mem::transmute(vec_i8) })
796 } else {
797 None
798 }
799 }
800 Dynamic::VecU16(vec) => {
801 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u16>() {
802 let vec_u16: Vec<u16> = Vec::from(vec);
803 Some(unsafe { mem::transmute(vec_u16) })
804 } else {
805 None
806 }
807 }
808 Dynamic::VecI16(vec) => {
809 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i16>() {
810 let vec_i16: Vec<i16> = Vec::from(vec);
811 Some(unsafe { mem::transmute(vec_i16) })
812 } else {
813 None
814 }
815 }
816 Dynamic::VecU32(vec) => {
817 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u32>() {
818 let vec_u32: Vec<u32> = Vec::from(vec);
819 Some(unsafe { mem::transmute(vec_u32) })
820 } else {
821 None
822 }
823 }
824 Dynamic::VecI32(vec) => {
825 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i32>() {
826 let vec_i32: Vec<i32> = Vec::from(vec);
827 Some(unsafe { mem::transmute(vec_i32) })
828 } else {
829 None
830 }
831 }
832 Dynamic::VecF32(vec) => {
833 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<f32>() {
834 let vec_f32: Vec<f32> = Vec::from(vec);
835 Some(unsafe { mem::transmute(vec_f32) })
836 } else {
837 None
838 }
839 }
840 Dynamic::VecU64(vec) => {
841 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u64>() {
842 Some(unsafe { mem::transmute(vec) })
843 } else {
844 None
845 }
846 }
847 Dynamic::VecI64(vec) => {
848 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i64>() {
849 Some(unsafe { mem::transmute(vec) })
850 } else {
851 None
852 }
853 }
854 Dynamic::VecF64(vec) => {
855 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<f64>() {
856 Some(unsafe { mem::transmute(vec) })
857 } else {
858 None
859 }
860 }
861 _ => None,
862 }
863 }
864 }
865
866 pub fn push<T: Into<Dynamic> + 'static>(&mut self, value: T) -> bool {
867 match self {
868 Self::List(list) => {
869 list.write().unwrap().push(value.into());
870 true
871 }
872 Self::Bytes(vec) => {
873 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u8>() {
874 vec.push(unsafe { mem::transmute_copy(&value) });
875 true
876 } else {
877 false
878 }
879 }
880 Self::VecI8(vec) => {
881 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i8>() {
882 vec.push(unsafe { mem::transmute_copy(&value) });
883 true
884 } else {
885 false
886 }
887 }
888 Self::VecU16(vec) => {
889 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u16>() {
890 vec.push(unsafe { mem::transmute_copy(&value) });
891 true
892 } else {
893 false
894 }
895 }
896 Self::VecI16(vec) => {
897 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i16>() {
898 vec.push(unsafe { mem::transmute_copy(&value) });
899 true
900 } else {
901 false
902 }
903 }
904 Self::VecU32(vec) => {
905 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u32>() {
906 vec.push(unsafe { mem::transmute_copy(&value) });
907 true
908 } else {
909 false
910 }
911 }
912 Self::VecI32(vec) => {
913 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i32>() {
914 vec.push(unsafe { mem::transmute_copy(&value) });
915 true
916 } else {
917 false
918 }
919 }
920 Self::VecF32(vec) => {
921 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<f32>() {
922 vec.push(unsafe { mem::transmute_copy(&value) });
923 true
924 } else {
925 false
926 }
927 }
928 Self::VecU64(vec) => {
929 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u64>() {
930 vec.push(unsafe { mem::transmute_copy(&value) });
931 true
932 } else {
933 false
934 }
935 }
936 Self::VecI64(vec) => {
937 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<i64>() {
938 vec.push(unsafe { mem::transmute_copy(&value) });
939 true
940 } else {
941 false
942 }
943 }
944 Self::VecF64(vec) => {
945 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<f64>() {
946 vec.push(unsafe { mem::transmute_copy(&value) });
947 true
948 } else {
949 false
950 }
951 }
952 _ => false,
953 }
954 }
955
956 pub fn push_dynamic(&mut self, value: Dynamic) -> bool {
957 match self {
958 Self::List(list) => {
959 list.write().unwrap().push(value);
960 true
961 }
962 Self::Bytes(vec) => value.try_into().map(|value| vec.push(value)).is_ok(),
963 Self::VecI8(vec) => value.try_into().map(|value| vec.push(value)).is_ok(),
964 Self::VecU16(vec) => value.try_into().map(|value| vec.push(value)).is_ok(),
965 Self::VecI16(vec) => value.try_into().map(|value| vec.push(value)).is_ok(),
966 Self::VecU32(vec) => value.try_into().map(|value| vec.push(value)).is_ok(),
967 Self::VecI32(vec) => value.try_into().map(|value| vec.push(value)).is_ok(),
968 Self::VecF32(vec) => value.try_into().map(|value| vec.push(value)).is_ok(),
969 Self::VecU64(vec) => value.try_into().map(|value| vec.push(value)).is_ok(),
970 Self::VecI64(vec) => value.try_into().map(|value| vec.push(value)).is_ok(),
971 Self::VecF64(vec) => value.try_into().map(|value| vec.push(value)).is_ok(),
972 _ => false,
973 }
974 }
975
976 pub fn pop(&mut self) -> Option<Dynamic> {
977 match self {
978 Self::List(list) => list.write().unwrap().pop(),
979 Self::Bytes(vec) => vec.pop().map(Dynamic::U8),
980 Self::VecI8(vec) => vec.pop().map(Dynamic::I8),
981 Self::VecU16(vec) => vec.pop().map(Dynamic::U16),
982 Self::VecI16(vec) => vec.pop().map(Dynamic::I16),
983 Self::VecU32(vec) => vec.pop().map(Dynamic::U32),
984 Self::VecI32(vec) => vec.pop().map(Dynamic::I32),
985 Self::VecF32(vec) => vec.pop().map(Dynamic::F32),
986 Self::VecU64(vec) => vec.pop().map(Dynamic::U64),
987 Self::VecI64(vec) => vec.pop().map(Dynamic::I64),
988 Self::VecF64(vec) => vec.pop().map(Dynamic::F64),
989 _ => None,
990 }
991 }
992
993 pub fn is_null(&self) -> bool {
994 match self {
995 Self::Null => true,
996 _ => false,
997 }
998 }
999
1000 pub fn as_bool(&self) -> Option<bool> {
1001 if let Self::Bool(b) = self { Some(*b) } else { None }
1002 }
1003
1004 pub fn is_true(&self) -> bool {
1005 match self {
1006 Self::Bool(b) => *b,
1007 _ => false,
1008 }
1009 }
1010
1011 pub fn is_false(&self) -> bool {
1012 match self {
1013 Self::Bool(b) => !*b,
1014 _ => false,
1015 }
1016 }
1017
1018 pub fn is_int(&self) -> bool {
1019 match self {
1020 Self::I8(_) | Self::I16(_) | Self::I32(_) | Self::I64(_) => true,
1021 Self::U8(_) | Self::U16(_) | Self::U32(_) | Self::U64(_) => true,
1022 _ => false,
1023 }
1024 }
1025
1026 pub fn as_int(&self) -> Option<i64> {
1027 match self {
1028 Self::U8(u) => Some(*u as i64),
1029 Self::U16(u) => Some(*u as i64),
1030 Self::U32(u) => Some(*u as i64),
1031 Self::U64(u) => i64::try_from(*u).ok(),
1032 Self::I8(i) => Some(*i as i64),
1033 Self::I16(i) => Some(*i as i64),
1034 Self::I32(i) => Some(*i as i64),
1035 Self::I64(i) => Some(*i as i64),
1036 _ => None,
1037 }
1038 }
1039
1040 pub fn is_uint(&self) -> bool {
1041 match self {
1042 Self::U8(_) | Self::U16(_) | Self::U32(_) | Self::U64(_) => true,
1043 _ => false,
1044 }
1045 }
1046
1047 pub fn as_uint(&self) -> Option<u64> {
1048 match self {
1049 Self::U8(i) => Some(*i as u64),
1050 Self::U16(i) => Some(*i as u64),
1051 Self::U32(i) => Some(*i as u64),
1052 Self::U64(i) => Some(*i as u64),
1053 _ => None,
1054 }
1055 }
1056
1057 pub fn is_f32(&self) -> bool {
1058 if let Self::F32(_) = self { true } else { false }
1059 }
1060
1061 pub fn is_str(&self) -> bool {
1062 if let Self::String(_) | Self::StringBuf(_) = self { true } else { false }
1063 }
1064
1065 pub fn is_f64(&self) -> bool {
1066 if let Self::F64(_) = self { true } else { false }
1067 }
1068
1069 pub fn as_float(&self) -> Option<f64> {
1070 match self {
1071 Self::U8(u) => Some(*u as f64),
1072 Self::U16(u) => Some(*u as f64),
1073 Self::U32(u) => Some(*u as f64),
1074 Self::U64(u) => Some(*u as f64),
1075 Self::I8(i) => Some(*i as f64),
1076 Self::I16(i) => Some(*i as f64),
1077 Self::I32(i) => Some(*i as f64),
1078 Self::I64(i) => Some(*i as f64),
1079 Self::F32(f) => Some(*f as f64),
1080 Self::F64(f) => Some(*f),
1081 _ => None,
1082 }
1083 }
1084
1085 pub fn is_signed(&self) -> bool {
1086 match self {
1087 Self::I8(_) | Self::I16(_) | Self::I32(_) | Self::I64(_) | Self::F32(_) | Self::F64(_) => true,
1088 _ => false,
1089 }
1090 }
1091
1092 pub fn size_of(&self) -> usize {
1093 match self {
1094 Self::I8(_) | Self::U8(_) => 1,
1095 Self::I16(_) | Self::U16(_) => 2,
1096 Self::I32(_) | Self::U32(_) | Self::F32(_) => 4,
1097 Self::I64(_) | Self::U64(_) | Self::F64(_) => 8,
1098 Self::String(s) => s.len(),
1099 Self::StringBuf(s) => s.len(),
1100 Self::Bytes(bytes) => bytes.len(),
1101 Self::VecI8(vec) => vec.len(),
1102 Self::VecU16(vec) => vec.len(),
1103 Self::VecI16(vec) => vec.len(),
1104 Self::VecU32(vec) => vec.len(),
1105 Self::VecI32(vec) => vec.len(),
1106 Self::VecF32(vec) => vec.len(),
1107 Self::VecI64(vec) => vec.len(),
1108 Self::VecU64(vec) => vec.len(),
1109 Self::VecF64(vec) => vec.len(),
1110 Self::List(list) => list.read().unwrap().len(),
1111 Self::Map(obj) => obj.read().unwrap().len(),
1112 Self::Struct { ty, .. } => ty.len(),
1113 Self::Custom(_) => 0,
1114 _ => 1,
1115 }
1116 }
1117
1118 pub fn list(v: Vec<Dynamic>) -> Self {
1119 Dynamic::List(Arc::new(RwLock::new(v)))
1120 }
1121
1122 pub fn is_list(&self) -> bool {
1123 match self {
1124 Self::List(_) | Self::VecF32(_) | Self::VecF64(_) | Self::VecI16(_) | Self::VecI32(_) | Self::VecI64(_) | Self::VecU16(_) | Self::VecU32(_) | Self::VecU64(_) => true,
1125 _ => false,
1126 }
1127 }
1128
1129 pub fn split(self, tag: &str) -> Self {
1130 match self {
1131 Self::String(s) => Self::list(s.split(tag).map(|p| Dynamic::from(p)).collect()),
1132 Self::StringBuf(s) => Self::list(s.split(tag).map(|p| Dynamic::from(p)).collect()),
1133 _ => self,
1134 }
1135 }
1136
1137 pub fn map(m: BTreeMap<SmolStr, Dynamic>) -> Self {
1138 Dynamic::Map(Arc::new(RwLock::new(m)))
1139 }
1140
1141 pub fn into_map(self) -> Option<BTreeMap<SmolStr, Dynamic>> {
1142 if let Self::Map(map) = self { Arc::try_unwrap(map).ok().and_then(|m| m.into_inner().ok()) } else { None }
1143 }
1144
1145 pub fn is_map(&self) -> bool {
1146 if let Self::Map(_) | Self::Struct { .. } = self { true } else { false }
1147 }
1148
1149 pub fn insert<K: Into<SmolStr>, T: Into<Self>>(&self, key: K, value: T) {
1150 match self {
1151 Self::Map(obj) => {
1152 obj.write().unwrap().insert(key.into(), value.into());
1153 }
1154 _ => {}
1155 }
1156 }
1157
1158 pub fn len(&self) -> usize {
1159 match self {
1160 Self::String(value) => value.len(),
1161 Self::StringBuf(value) => value.len(),
1162 Self::List(list) => list.read().unwrap().len(),
1163 Self::Bytes(bytes) => bytes.len(),
1164 Self::VecI8(vec) => vec.len(),
1165 Self::VecU16(vec) => vec.len(),
1166 Self::VecI16(vec) => vec.len(),
1167 Self::VecU32(vec) => vec.len(),
1168 Self::VecI32(vec) => vec.len(),
1169 Self::VecF32(vec) => vec.len(),
1170 Self::VecI64(vec) => vec.len(),
1171 Self::VecU64(vec) => vec.len(),
1172 Self::VecF64(vec) => vec.len(),
1173 Self::Map(obj) => obj.read().unwrap().len(),
1174 Self::Custom(_) => 0,
1175 _ => 0,
1176 }
1177 }
1178
1179 pub fn keys(&self) -> Vec<SmolStr> {
1180 if let Self::Map(map) = self {
1181 map.read().unwrap().keys().cloned().collect()
1182 } else if let Self::Struct { ty: Type::Struct { params: _, fields }, .. } = self {
1183 fields.iter().map(|(name, _)| name.clone()).collect()
1184 } else {
1185 Vec::new()
1186 }
1187 }
1188
1189 pub fn contains(&self, key: &str) -> bool {
1190 if let Self::Map(map) = self {
1191 map.read().unwrap().get(key).is_some_and(|value| !value.is_null())
1192 } else if let Self::Struct { ty, .. } = self {
1193 ty.get_field(key).is_ok()
1194 } else if let Self::List(list) = self {
1195 list.read().unwrap().iter().find(|l| l.as_str() == key).is_some()
1196 } else if let Self::String(s) = self {
1197 s.contains(key)
1198 } else if let Self::StringBuf(s) = self {
1199 s.contains(key)
1200 } else if let Self::Custom(value) = self {
1201 value.contains_key(key)
1202 } else {
1203 false
1204 }
1205 }
1206
1207 pub fn starts_with(&self, prefix: &str) -> bool {
1208 if let Self::String(s) = self {
1209 s.starts_with(prefix)
1210 } else if let Self::StringBuf(s) = self {
1211 s.starts_with(prefix)
1212 } else {
1213 false
1214 }
1215 }
1216
1217 pub fn get_dynamic(&self, key: &str) -> Option<Dynamic> {
1218 if let Self::Map(map) = self {
1219 map.read().unwrap().get(key).cloned()
1220 } else if let Self::Struct { addr, ty } = self {
1221 let (idx, field_ty) = ty.get_field(key).ok()?;
1222 Self::read_struct_field(*addr, idx, field_ty, ty)
1223 } else if let Self::Custom(value) = self {
1224 value.get_key(key)
1225 } else {
1226 None
1227 }
1228 }
1229
1230 pub fn set_dynamic(&self, key: SmolStr, value: impl Into<Dynamic>) {
1231 if let Self::Map(map) = self {
1232 map.write().unwrap().insert(key, value.into());
1233 } else if let Self::Struct { addr, ty } = self
1234 && let Ok((idx, field_ty)) = ty.get_field(key.as_str())
1235 {
1236 Self::write_struct_field(*addr, idx, field_ty, ty, value.into());
1237 } else if let Self::Custom(custom) = self {
1238 custom.set_key(key.as_str(), value.into());
1239 }
1240 }
1241
1242 fn field_addr(addr: usize, idx: usize, struct_ty: &Type) -> Option<usize> {
1243 struct_ty.field_offset(idx).map(|offset| addr + offset as usize)
1244 }
1245
1246 fn read_dynamic_ptr(addr: usize) -> Option<Dynamic> {
1247 let ptr = unsafe { std::ptr::read_unaligned(addr as *const usize) };
1248 if ptr == 0 { None } else { Some(unsafe { (&*(ptr as *const Dynamic)).clone() }) }
1249 }
1250
1251 fn write_dynamic_ptr(addr: usize, value: Dynamic) {
1252 let ptr = Box::into_raw(Box::new(value)) as usize;
1253 unsafe {
1254 std::ptr::write_unaligned(addr as *mut usize, ptr);
1255 }
1256 }
1257
1258 fn read_struct_field(addr: usize, idx: usize, field_ty: &Type, struct_ty: &Type) -> Option<Dynamic> {
1259 let field_addr = Self::field_addr(addr, idx, struct_ty)?;
1260 match field_ty {
1261 Type::Bool => Some(Dynamic::Bool(unsafe { std::ptr::read_unaligned(field_addr as *const u8) } != 0)),
1262 Type::I8 => Some(Dynamic::I8(unsafe { std::ptr::read_unaligned(field_addr as *const i8) })),
1263 Type::U8 => Some(Dynamic::U8(unsafe { std::ptr::read_unaligned(field_addr as *const u8) })),
1264 Type::I16 => Some(Dynamic::I16(unsafe { std::ptr::read_unaligned(field_addr as *const i16) })),
1265 Type::U16 => Some(Dynamic::U16(unsafe { std::ptr::read_unaligned(field_addr as *const u16) })),
1266 Type::I32 => Some(Dynamic::I32(unsafe { std::ptr::read_unaligned(field_addr as *const i32) })),
1267 Type::U32 => Some(Dynamic::U32(unsafe { std::ptr::read_unaligned(field_addr as *const u32) })),
1268 Type::I64 => Some(Dynamic::I64(unsafe { std::ptr::read_unaligned(field_addr as *const i64) })),
1269 Type::U64 => Some(Dynamic::U64(unsafe { std::ptr::read_unaligned(field_addr as *const u64) })),
1270 Type::F32 => Some(Dynamic::F32(unsafe { std::ptr::read_unaligned(field_addr as *const f32) })),
1271 Type::F64 => Some(Dynamic::F64(unsafe { std::ptr::read_unaligned(field_addr as *const f64) })),
1272 Type::Struct { .. } => {
1273 let ptr = unsafe { std::ptr::read_unaligned(field_addr as *const usize) };
1274 Some(Dynamic::Struct { addr: ptr, ty: field_ty.clone() })
1275 }
1276 _ => Self::read_dynamic_ptr(field_addr),
1277 }
1278 }
1279
1280 fn write_struct_field(addr: usize, idx: usize, field_ty: &Type, struct_ty: &Type, value: Dynamic) {
1281 let Some(field_addr) = Self::field_addr(addr, idx, struct_ty) else {
1282 return;
1283 };
1284 match field_ty {
1285 Type::Bool => unsafe {
1286 std::ptr::write_unaligned(field_addr as *mut u8, if value.is_true() { 1 } else { 0 });
1287 },
1288 Type::I8 => unsafe {
1289 std::ptr::write_unaligned(field_addr as *mut i8, value.try_into().unwrap_or_default());
1290 },
1291 Type::U8 => unsafe {
1292 std::ptr::write_unaligned(field_addr as *mut u8, value.try_into().unwrap_or_default());
1293 },
1294 Type::I16 => unsafe {
1295 std::ptr::write_unaligned(field_addr as *mut i16, value.try_into().unwrap_or_default());
1296 },
1297 Type::U16 => unsafe {
1298 std::ptr::write_unaligned(field_addr as *mut u16, value.try_into().unwrap_or_default());
1299 },
1300 Type::I32 => unsafe {
1301 std::ptr::write_unaligned(field_addr as *mut i32, value.try_into().unwrap_or_default());
1302 },
1303 Type::U32 => unsafe {
1304 std::ptr::write_unaligned(field_addr as *mut u32, value.try_into().unwrap_or_default());
1305 },
1306 Type::I64 => unsafe {
1307 std::ptr::write_unaligned(field_addr as *mut i64, value.try_into().unwrap_or_default());
1308 },
1309 Type::U64 => unsafe {
1310 std::ptr::write_unaligned(field_addr as *mut u64, value.try_into().unwrap_or_default());
1311 },
1312 Type::F32 => unsafe {
1313 std::ptr::write_unaligned(field_addr as *mut f32, f32::try_from(value).unwrap_or_default());
1314 },
1315 Type::F64 => unsafe {
1316 std::ptr::write_unaligned(field_addr as *mut f64, f64::try_from(value).unwrap_or_default());
1317 },
1318 Type::Struct { .. } => {
1319 if let Dynamic::Struct { addr, ty: _ } = value {
1320 unsafe {
1321 std::ptr::write_unaligned(field_addr as *mut usize, addr);
1322 }
1323 }
1324 }
1325 _ => Self::write_dynamic_ptr(field_addr, value),
1326 }
1327 }
1328
1329 pub fn remove_dynamic(&self, key: &str) -> Option<Dynamic> {
1330 if let Self::Map(map) = self { map.write().unwrap().remove(key) } else { None }
1331 }
1332
1333 pub fn get_idx(&self, idx: usize) -> Option<Self> {
1334 match self {
1335 Self::List(list) => list.read().unwrap().get(idx).cloned(),
1336 Self::VecI8(vec) => vec.get(idx).map(Self::I8),
1337 Self::VecU16(vec) => vec.get(idx).map(Self::U16),
1338 Self::VecI16(vec) => vec.get(idx).map(Self::I16),
1339 Self::VecU32(vec) => vec.get(idx).map(Self::U32),
1340 Self::VecI32(vec) => vec.get(idx).map(Self::I32),
1341 Self::VecF32(vec) => vec.get(idx).map(Self::F32),
1342 Self::VecI64(vec) => vec.get(idx).cloned().map(Self::I64),
1343 Self::VecU64(vec) => vec.get(idx).cloned().map(Self::U64),
1344 Self::VecF64(vec) => vec.get(idx).cloned().map(Self::F64),
1345 Self::Struct { addr, ty } => {
1346 if let Type::Struct { params: _, fields } = ty {
1347 fields.get(idx).and_then(|(_, field_ty)| Self::read_struct_field(*addr, idx, field_ty, ty))
1348 } else {
1349 None
1350 }
1351 }
1352 _ => None,
1353 }
1354 }
1355
1356 pub fn into_iter(self) -> Self {
1357 if self.is_map() {
1358 let keys = self.keys();
1359 Self::Iter { idx: 0, keys, value: Box::new(self) }
1360 } else {
1361 Self::Iter { idx: 0, keys: Vec::new(), value: Box::new(self) }
1362 }
1363 }
1364
1365 pub fn next(&mut self) -> Option<Self> {
1366 if let Self::Iter { idx, keys, value } = self {
1367 if !keys.is_empty() {
1368 if *idx < keys.len() {
1369 let k = keys[*idx].clone();
1370 let v = value.get_dynamic(k.as_str()).unwrap();
1371 *idx += 1;
1372 return Some(list!(k, v));
1373 }
1374 } else {
1375 if let Some(v) = value.get_idx(*idx) {
1376 *idx += 1;
1377 return Some(v);
1378 }
1379 }
1380 }
1381 None
1382 }
1383
1384 pub fn set_idx(&mut self, idx: usize, val: Dynamic) {
1385 match self {
1386 Self::List(list) => {
1387 list.write().unwrap().get_mut(idx).map(|l| *l = val);
1388 }
1389 Self::VecI8(vec) => vec.set(idx, val.try_into().unwrap()),
1390 Self::VecU16(vec) => vec.set(idx, val.try_into().unwrap()),
1391 Self::VecI16(vec) => vec.set(idx, val.try_into().unwrap()),
1392 Self::VecU32(vec) => vec.set(idx, val.try_into().unwrap()),
1393 Self::VecI32(vec) => vec.set(idx, val.try_into().unwrap()),
1394 Self::VecF32(vec) => vec.set(idx, val.try_into().unwrap()),
1395 Self::VecI64(vec) => vec[idx] = val.try_into().unwrap(),
1396 Self::VecU64(vec) => vec[idx] = val.try_into().unwrap(),
1397 Self::VecF64(vec) => vec[idx] = val.try_into().unwrap(),
1398 Self::Struct { addr, ty } => {
1399 if let Type::Struct { params: _, fields } = ty.clone()
1400 && let Some((_, field_ty)) = fields.get(idx)
1401 {
1402 Self::write_struct_field(*addr, idx, field_ty, &ty, val);
1403 }
1404 }
1405 _ => {}
1406 }
1407 }
1408
1409 pub fn to_markdown(&self) -> String {
1410 let mut s = String::new();
1411 if let Self::Map(m) = self {
1412 for (key, v) in m.read().unwrap().iter() {
1413 s.push_str(&format!("#### ```{}```\n", key));
1414 s.push_str(&v.to_markdown());
1415 s.push('\n');
1416 }
1417 } else if let Self::Bytes(bytes) = self {
1418 s = format!("[{}...]", hex::encode(&bytes[..8]));
1419 } else {
1420 let len = self.len();
1421 if len > 0 {
1422 for idx in 0..len {
1423 s.push_str(&format!("- {}\n", self.get_idx(idx).unwrap().to_markdown()));
1424 }
1425 } else {
1426 s = self.to_string();
1427 }
1428 }
1429 s
1430 }
1431}
1432
1433#[cfg(test)]
1434mod tests {
1435 use super::*;
1436 use std::sync::RwLock;
1437
1438 #[derive(Debug, PartialEq)]
1439 struct CustomCounter {
1440 value: i64,
1441 }
1442
1443 #[test]
1444 fn custom_values_can_be_downcast_and_shared_by_clone() {
1445 let value = Dynamic::custom(RwLock::new(CustomCounter { value: 7 }));
1446 assert!(value.is_custom());
1447 assert!(value.custom_type_name().is_some());
1448
1449 let cloned = value.clone();
1450 assert_eq!(cloned.as_custom::<RwLock<CustomCounter>>().unwrap().read().unwrap().value, 7);
1451
1452 cloned.as_custom::<RwLock<CustomCounter>>().unwrap().write().unwrap().value = 9;
1453 assert_eq!(value.as_custom::<RwLock<CustomCounter>>().unwrap().read().unwrap().value, 9);
1454 assert_eq!(value, cloned);
1455 }
1456
1457 #[derive(Debug, Default)]
1458 struct CustomPropertyBag {
1459 values: RwLock<BTreeMap<SmolStr, Dynamic>>,
1460 }
1461
1462 impl CustomProperty for CustomPropertyBag {
1463 fn get_key(&self, key: &str) -> Option<Dynamic> {
1464 self.values.read().unwrap().get(key).cloned()
1465 }
1466
1467 fn set_key(&self, key: &str, value: Dynamic) -> bool {
1468 self.values.write().unwrap().insert(key.into(), value);
1469 true
1470 }
1471 }
1472
1473 #[test]
1474 fn custom_values_can_forward_dynamic_properties() {
1475 let value = Dynamic::custom_with_properties(CustomPropertyBag::default());
1476
1477 value.set_dynamic("file_mode".into(), 2i64);
1478
1479 assert!(value.contains("file_mode"));
1480 assert_eq!(value.get_dynamic("file_mode").and_then(|value| value.as_int()), Some(2));
1481 }
1482
1483 #[test]
1484 fn deep_clone_recursively_copies_maps_and_lists() {
1485 let nested = Dynamic::map(Default::default());
1486 nested.insert("score", 1);
1487
1488 let value = Dynamic::map(Default::default());
1489 value.insert("nested", nested.clone());
1490 value.insert("items", Dynamic::list(vec![nested.clone()]));
1491
1492 let cloned = value.deep_clone();
1493 cloned.get_dynamic("nested").unwrap().insert("score", 2);
1494 cloned.get_dynamic("items").unwrap().get_idx(0).unwrap().insert("score", 3);
1495
1496 assert_eq!(value.get_dynamic("nested").unwrap().get_dynamic("score").and_then(|v| v.as_int()), Some(1));
1497 assert_eq!(value.get_dynamic("items").unwrap().get_idx(0).unwrap().get_dynamic("score").and_then(|v| v.as_int()), Some(1));
1498 }
1499
1500 #[test]
1501 fn string_add_keeps_concat_semantics() {
1502 let left = Dynamic::from("hello");
1503 let right = Dynamic::from(" world");
1504 let joined = left + right;
1505 assert!(matches!(joined, Dynamic::StringBuf(_)));
1506 assert_eq!(joined.as_str(), "hello world");
1507
1508 assert_eq!((Dynamic::from("level ") + Dynamic::I64(7)).as_str(), "level 7");
1509 assert_eq!((Dynamic::I64(7) + Dynamic::from(" days")).as_str(), "7 days");
1510 }
1511
1512 #[test]
1513 fn string_add_reuses_string_buf_after_first_concat() {
1514 let mut value = Dynamic::from("a") + Dynamic::from("b");
1515 assert!(matches!(value, Dynamic::StringBuf(_)));
1516
1517 value = value + Dynamic::from("c");
1518 assert!(matches!(value, Dynamic::StringBuf(_)));
1519 assert_eq!(value.as_str(), "abc");
1520 }
1521
1522 #[test]
1523 fn u64_as_int_does_not_wrap() {
1524 assert_eq!(Dynamic::U64(i64::MAX as u64).as_int(), Some(i64::MAX));
1525 assert_eq!(Dynamic::U64(i64::MAX as u64 + 1).as_int(), None);
1526 }
1527}
1528
1529#[macro_export]
1530macro_rules! assert_ok {
1531 ( $x: expr, $ok: expr) => {
1532 if $x {
1533 return Ok($ok);
1534 }
1535 };
1536}
1537
1538#[macro_export]
1539macro_rules! assert_err {
1540 ( $x: expr, $err: expr) => {
1541 if $x {
1542 return Err($err);
1543 }
1544 };
1545}
1546
1547pub struct ZOnce {
1548 first: Option<&'static str>,
1549 other: &'static str,
1550}
1551
1552impl ZOnce {
1553 pub fn new(first: &'static str, other: &'static str) -> Self {
1554 Self { first: Some(first), other }
1555 }
1556 pub fn take(&mut self) -> &'static str {
1557 self.first.take().unwrap_or(self.other)
1558 }
1559}
1560
1561mod fixvec;
1562pub use fixvec::FixVec;
1563mod msgpack;
1564pub use msgpack::{MsgPack, MsgUnpack};
1565
1566pub use json::{FromJson, ToJson};
1567
1568mod ops;
1569mod types;
1570pub use types::{ConstIntOp, Type, call_fn, set_dynamic_return_handler};
1571
1572#[macro_export]
1573macro_rules! list {
1574 ($($v:expr),+ $(,)?) => {{
1575 let mut list = Vec::new();
1576 $( let _ = list.push(Dynamic::from($v)); )*
1577 Dynamic::List(std::sync::Arc::new(std::sync::RwLock::new(list)))
1578 }};
1579}
1580
1581#[macro_export]
1582macro_rules! map {
1583 ($($k:expr => $v:expr), *) => {{
1584 let mut obj = std::collections::BTreeMap::new();
1585 $( let _ = obj.insert(smol_str::SmolStr::from($k), Dynamic::from($v)); )*
1586 Dynamic::Map(std::sync::Arc::new(std::sync::RwLock::new(obj)))
1587 }};
1588}