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