codama_attributes/codama_directives/
fixed_size_directive.rs

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