cooplan_definitions_lib/
source_attribute.rs

1use serde::{Deserialize, Serialize};
2
3use super::{attribute::Attribute, error::Error, error::ErrorKind};
4
5/// Partial or full, input based attribute.
6#[derive(Serialize, Deserialize, Debug, Clone)]
7pub struct SourceAttribute {
8    pub id: Option<String>,
9    pub name: String,
10    pub data_type: String,
11    pub unit: Option<String>,
12    pub optional: Option<bool>,
13}
14
15impl SourceAttribute {
16    pub fn to_attribute(&self) -> Result<Attribute, Error> {
17        match &self.id {
18            Some(id) => {
19                let optional = match self.optional {
20                    Some(value) => value,
21                    None => false,
22                };
23
24                Ok(Attribute {
25                    id: id.clone(),
26                    name: self.name.clone(),
27                    data_type: self.data_type.clone(),
28                    unit: self.unit.clone(),
29                    optional,
30                })
31            }
32            None => Err(Error::new(
33                ErrorKind::MissingId,
34                "source attribute cannot be converted to attribute without an id",
35            )),
36        }
37    }
38
39    pub fn to_attributes(source_attributes: &[SourceAttribute]) -> Result<Vec<Attribute>, Error> {
40        let mut attributes = Vec::new();
41
42        for source_attribute in source_attributes {
43            match source_attribute.to_attribute() {
44                Ok(attribute) => attributes.push(attribute),
45                Err(error) => return Err(error),
46            }
47        }
48
49        Ok(attributes)
50    }
51}