diff --git a/services/comm-services-lib/src/database.rs b/services/comm-services-lib/src/database.rs --- a/services/comm-services-lib/src/database.rs +++ b/services/comm-services-lib/src/database.rs @@ -63,6 +63,40 @@ InvalidNumberFormat(ParseIntError), } +/// Conversion trait for [`AttributeValue`] +/// +/// Types implementing this trait are able to do the following: +/// ```rust +/// use comm_services_lib::database::{TryFromAttribute, AttributeTryInto}; +/// +/// let foo = SomeType::try_from_attr("MyAttribute", Some(attribute)); +/// +/// // if `AttributeTryInto` is imported, also: +/// let bar = Some(attribute).attr_try_into("MyAttribute"); +pub trait TryFromAttribute: Sized { + fn try_from_attr( + attribute_name: impl Into, + attribute: Option, + ) -> Result; +} + +/// Do NOT implement this trait directly. Implement [`TryFromAttribute`] instead +pub trait AttributeTryInto { + fn attr_try_into( + self, + attribute_name: impl Into, + ) -> Result; +} +// automatic attr_try_into() for all attributevalues that have TryFromAttribute implemented +impl AttributeTryInto for Option { + fn attr_try_into( + self, + attribute_name: impl Into, + ) -> Result { + T::try_from_attr(attribute_name, self) + } +} + pub fn parse_string_attribute( attribute_name: impl Into, attribute_value: Option,