codama_attributes/codama_directives/
fixed_size_directive.rs

1use crate::{utils::FromMeta, Attribute, CodamaAttribute, CodamaDirective};
2use codama_errors::CodamaError;
3use codama_syn_helpers::Meta;
4
5#[derive(Debug, PartialEq)]
6pub struct FixedSizeDirective {
7    pub size: usize,
8}
9
10impl FixedSizeDirective {
11    pub fn parse(meta: &Meta) -> syn::Result<Self> {
12        meta.assert_directive("fixed_size")?;
13        Ok(Self {
14            size: usize::from_meta(meta)?,
15        })
16    }
17}
18
19impl<'a> TryFrom<&'a CodamaAttribute<'a>> for &'a FixedSizeDirective {
20    type Error = CodamaError;
21
22    fn try_from(attribute: &'a CodamaAttribute) -> Result<Self, Self::Error> {
23        match attribute.directive {
24            CodamaDirective::FixedSize(ref a) => Ok(a),
25            _ => Err(CodamaError::InvalidCodamaDirective {
26                expected: "fixed_size".to_string(),
27                actual: attribute.directive.name().to_string(),
28            }),
29        }
30    }
31}
32
33impl<'a> TryFrom<&'a Attribute<'a>> for &'a FixedSizeDirective {
34    type Error = CodamaError;
35
36    fn try_from(attribute: &'a Attribute) -> Result<Self, Self::Error> {
37        <&CodamaAttribute>::try_from(attribute)?.try_into()
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[test]
46    fn ok() {
47        let meta: Meta = syn::parse_quote! { fixed_size = 42 };
48        let directive = FixedSizeDirective::parse(&meta).unwrap();
49        assert_eq!(directive, FixedSizeDirective { size: 42 });
50    }
51}