konduto/types/vehicle/
vehicle_usage.rs1use crate::types::validation_errors::ValidationError;
2use serde::{Deserialize, Serialize};
3use std::fmt;
4
5#[derive(Debug, Clone, PartialEq, Eq, Hash)]
7pub enum VehicleUsage {
8 Private,
9 Commercial,
10 Experimental,
11 Government,
12 Military,
13 Instruction,
14 Other(String),
16}
17
18impl VehicleUsage {
19 pub fn new(value: impl Into<String>) -> Result<Self, ValidationError> {
21 let input = value.into();
22 let trimmed = input.trim().to_lowercase();
23
24 if trimmed.is_empty() {
25 return Err(ValidationError::EmptyField("vehicle_usage".to_string()));
26 }
27
28 Ok(match trimmed.as_str() {
29 "private" => Self::Private,
30 "commercial" => Self::Commercial,
31 "experimental" => Self::Experimental,
32 "government" => Self::Government,
33 "military" => Self::Military,
34 "instruction" => Self::Instruction,
35 other => Self::Other(other.to_string()),
36 })
37 }
38
39 pub fn as_str(&self) -> &str {
40 match self {
41 Self::Private => "private",
42 Self::Commercial => "commercial",
43 Self::Experimental => "experimental",
44 Self::Government => "government",
45 Self::Military => "military",
46 Self::Instruction => "instruction",
47 Self::Other(s) => s,
48 }
49 }
50}
51
52impl fmt::Display for VehicleUsage {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54 write!(f, "{}", self.as_str())
55 }
56}
57
58impl Serialize for VehicleUsage {
59 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
60 where
61 S: serde::Serializer,
62 {
63 serializer.serialize_str(self.as_str())
64 }
65}
66
67impl<'de> Deserialize<'de> for VehicleUsage {
68 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
69 where
70 D: serde::Deserializer<'de>,
71 {
72 let s = String::deserialize(deserializer)?;
73 VehicleUsage::new(s).map_err(serde::de::Error::custom)
74 }
75}
76
77#[cfg(test)]
78mod tests {
79 use super::*;
80
81 #[test]
82 fn test_vehicle_usage_from_str() {
83 assert_eq!(VehicleUsage::new("private").unwrap(), VehicleUsage::Private);
84 assert_eq!(
85 VehicleUsage::new("Commercial").unwrap(),
86 VehicleUsage::Commercial
87 );
88 assert_eq!(
89 VehicleUsage::new("MILITARY").unwrap(),
90 VehicleUsage::Military
91 );
92 }
93
94 #[test]
95 fn test_vehicle_usage_other() {
96 let custom = VehicleUsage::new("rental").unwrap();
97 assert_eq!(custom.as_str(), "rental");
98 }
99
100 #[test]
101 fn test_vehicle_usage_serialization() {
102 let private = VehicleUsage::Private;
103 let json = serde_json::to_string(&private).unwrap();
104 assert_eq!(json, r#""private""#);
105 }
106}
107