session_rust/
vector.rs

1use serde::{ser::Serialize as SerTrait, Deserialize, Serialize};
2use std::fmt;
3use uuid::Uuid;
4
5/// A 3D vector with visual properties and JSON serialization support.
6#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
7#[serde(tag = "type", rename = "Vector")]
8pub struct Vector {
9    pub guid: String,
10    pub name: String,
11    pub x: f32,
12    pub y: f32,
13    pub z: f32,
14}
15
16impl Vector {
17    /// Creates a new Vector with specified coordinates.
18    pub fn new(x: f32, y: f32, z: f32) -> Self {
19        Self {
20            x,
21            y,
22            z,
23            guid: Uuid::new_v4().to_string(),
24            name: "my_vector".to_string(),
25        }
26    }
27
28    ///////////////////////////////////////////////////////////////////////////////////////////
29    // JSON
30    ///////////////////////////////////////////////////////////////////////////////////////////
31
32    /// Serializes the Vector to a JSON string.
33    pub fn to_json_data(&self) -> Result<String, Box<dyn std::error::Error>> {
34        let mut buf = Vec::new();
35        let formatter = serde_json::ser::PrettyFormatter::with_indent(b"    ");
36        let mut ser = serde_json::Serializer::with_formatter(&mut buf, formatter);
37        SerTrait::serialize(self, &mut ser)?;
38        Ok(String::from_utf8(buf)?)
39    }
40
41    /// Deserializes a Vector from a JSON string.
42    pub fn from_json_data(json_data: &str) -> Result<Self, Box<dyn std::error::Error>> {
43        Ok(serde_json::from_str(json_data)?)
44    }
45
46    /// Serializes the Vector to a JSON file.
47    pub fn to_json(&self, filepath: &str) -> Result<(), Box<dyn std::error::Error>> {
48        let json = self.to_json_data()?;
49        std::fs::write(filepath, json)?;
50        Ok(())
51    }
52
53    /// Deserializes a Vector from a JSON file.
54    pub fn from_json(filepath: &str) -> Result<Self, Box<dyn std::error::Error>> {
55        let json = std::fs::read_to_string(filepath)?;
56        Self::from_json_data(&json)
57    }
58}
59
60impl Default for Vector {
61    fn default() -> Self {
62        Self::new(0.0, 0.0, 0.0)
63    }
64}
65
66impl fmt::Display for Vector {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        write!(
69            f,
70            "Vector({}, {}, {}, {}, {})",
71            self.x, self.y, self.z, self.guid, self.name
72        )
73    }
74}