Skip to main content

ed_journals/modules/ship/models/ship_module/
ship_cockpit_module.rs

1use std::str::FromStr;
2
3use lazy_static::lazy_static;
4use regex::Regex;
5use serde::Serialize;
6use thiserror::Error;
7
8use crate::from_str_deserialize_impl;
9use crate::modules::ship::ShipType;
10
11/// Represents the cockpit module, which is different per ship type.
12#[derive(Debug, Serialize, Clone, PartialEq)]
13pub struct ShipCockpitModule(pub ShipType);
14
15#[derive(Debug, Error)]
16pub enum ShipCockpitModuleError {
17    #[error("Failed to parse cockpit module")]
18    FailedRegex,
19
20    #[error("Unknown ship type")]
21    UnknownShipType,
22}
23
24lazy_static! {
25    static ref COCKPIT_MODULE_REGEX: Regex = Regex::new(r#"^(\$)?(.+)_cockpit(_name;)?$"#).unwrap();
26}
27
28impl FromStr for ShipCockpitModule {
29    type Err = ShipCockpitModuleError;
30
31    fn from_str(s: &str) -> Result<Self, Self::Err> {
32        let Some(captures) = COCKPIT_MODULE_REGEX.captures(s) else {
33            return Err(ShipCockpitModuleError::FailedRegex);
34        };
35
36        let ship_type = captures
37            .get(2)
38            .expect("Should have already been matched")
39            .as_str()
40            .parse()
41            .map_err(|_| ShipCockpitModuleError::UnknownShipType)?;
42
43        Ok(ShipCockpitModule(ship_type))
44    }
45}
46
47from_str_deserialize_impl!(ShipCockpitModule);