cooplan_definitions_lib/
validated_source_attribute.rs1use crate::source_attribute::SourceAttribute;
2use serde::{Deserialize, Serialize};
3
4use crate::error::{Error, ErrorKind};
5
6#[derive(Serialize, Deserialize, Debug, Clone)]
8pub struct ValidatedSourceAttribute {
9 pub id: String,
10 pub name: String,
11 pub data_type: String,
12 pub unit: Option<String>,
13 pub optional: bool,
14}
15
16impl ValidatedSourceAttribute {
17 pub fn validate_attributes(
18 source_attributes: Vec<SourceAttribute>,
19 ) -> Result<Vec<ValidatedSourceAttribute>, Error> {
20 let mut validated_attributes: Vec<ValidatedSourceAttribute> = Vec::new();
21
22 for source_attribute in source_attributes {
23 match ValidatedSourceAttribute::try_from(source_attribute) {
24 Ok(validated_attribute) => validated_attributes.push(validated_attribute),
25 Err(error) => {
26 return Err(Error::new(
27 ErrorKind::FailedToValidateSourceAttribute,
28 format!("failed to validate source attribute: {}", error).as_str(),
29 ));
30 }
31 }
32 }
33
34 Ok(validated_attributes)
35 }
36}
37
38impl TryFrom<SourceAttribute> for ValidatedSourceAttribute {
39 type Error = String;
40
41 fn try_from(value: SourceAttribute) -> Result<Self, Self::Error> {
42 match &value.id {
43 Some(id) => Ok(ValidatedSourceAttribute {
44 id: id.clone(),
45 name: value.name,
46 data_type: value.data_type,
47 unit: value.unit,
48 optional: value.optional.unwrap_or(false),
49 }),
50 None => Err(String::from(format!(
51 "source attribute '{}' has no id",
52 value.name
53 ))),
54 }
55 }
56}
57
58impl PartialEq for ValidatedSourceAttribute {
59 fn eq(&self, other: &Self) -> bool {
60 self.id == other.id
61 && self.name == other.name
62 && self.data_type == other.data_type
63 && self.unit == other.unit
64 && self.optional == other.optional
65 }
66}