1use serde::{ser::Serialize as SerTrait, Deserialize, Serialize};
2use std::fmt;
3use uuid::Uuid;
4
5#[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 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 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 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 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 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}