godot_binary_serialization/types/
variant.rs

1use std::{fmt::Debug, hash::Hash};
2
3/// Describes a godot variant
4pub trait GodotVariant: Debug + Send + Sync {
5    /// Describes the byte length of a variant, most primitive variants have a static byte length.
6    /// However some variants like a dictionary may have dynamic sizes
7    fn byte_length(&self) -> usize;
8
9    /// Allows us to downcast ref a variant for use
10    fn as_any(&self) -> &dyn std::any::Any;
11
12    /// Checks if a variant is equal to another variant
13    fn variant_eq(&self, other: &dyn GodotVariant) -> bool;
14
15    /// The variant as a byte vector
16    fn bytes(&self) -> Vec<u8>;
17}
18
19impl PartialEq for dyn GodotVariant {
20    fn eq(&self, other: &Self) -> bool {
21        self.variant_eq(other)
22    }
23}
24
25impl Eq for dyn GodotVariant {}
26
27impl Hash for Box<dyn GodotVariant> {
28    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
29        self.bytes().hash(state)
30    }
31}
32
33/// Converts a type to a variant godot type
34pub trait AsVariant {
35    fn as_var<T>(&self) -> Option<&T> where T: GodotVariant + 'static;
36}
37
38impl AsVariant for dyn GodotVariant + '_ {
39    fn as_var<T>(&self) -> Option<&T> where T: GodotVariant + Send + Sync + 'static {
40        self.as_any().downcast_ref::<T>()
41    }
42}