godot_binary_serialization/encoder/
mod.rs

1use anyhow::anyhow;
2
3use crate::types::{
4    primitive::{GodotBool, GodotFloat, GodotInteger, GodotString},
5    structures::{GodotDictionary, GodotVector2, GodotVector3},
6    variant::{AsVariant, GodotVariant},
7};
8
9pub mod dictionary;
10pub mod float;
11pub mod int;
12pub mod string;
13pub mod vector;
14pub mod bool;
15
16/// Encodes a variant from its type into bytes
17pub struct Encoder;
18
19impl Encoder {
20    /// Takes in a Godot variant and determines how to encode it based on its type
21    pub fn encode_variant(variant: &dyn GodotVariant) -> anyhow::Result<Vec<u8>> {
22        if let Some(bool) = variant.as_var::<GodotBool>() {
23            return Self::encode_bool(bool);
24        }
25
26        if let Some(integer) = variant.as_var::<GodotInteger>() {
27            return Self::encode_int(integer);
28        }
29
30        if let Some(float) = variant.as_var::<GodotFloat>() {
31            return Self::encode_float(float);
32        }
33
34        if let Some(string) = variant.as_var::<GodotString>() {
35            return Self::encode_string(string);
36        }
37
38        if let Some(vector2) = variant.as_var::<GodotVector2>() {
39            return Self::encode_vector2(vector2);
40        }
41
42        if let Some(vector3) = variant.as_var::<GodotVector3>() {
43            return Self::encode_vector3(vector3);
44        }
45
46        if let Some(dictionary) = variant.as_var::<GodotDictionary>() {
47            return Self::encode_dictionary(dictionary);
48        }
49
50        Err(anyhow!(
51            "Variant of {:?} is not supported by the encoder",
52            variant
53        ))
54    }
55}