codama_attributes/codama_directives/
size_prefix_directive.rs1use crate::{utils::FromMeta, Attribute, CodamaAttribute, CodamaDirective};
2use codama_errors::CodamaError;
3use codama_nodes::{NestedTypeNode, NumberTypeNode, TypeNode};
4use codama_syn_helpers::{extensions::*, Meta};
5
6#[derive(Debug, PartialEq)]
7pub struct SizePrefixDirective {
8 pub prefix: NestedTypeNode<NumberTypeNode>,
9}
10
11impl SizePrefixDirective {
12 pub fn parse(meta: &Meta) -> syn::Result<Self> {
13 let pv = meta.assert_directive("size_prefix")?.as_path_value()?;
14 let node = TypeNode::from_meta(&pv.value)?;
15 let prefix = match NestedTypeNode::<NumberTypeNode>::try_from(node) {
16 Ok(node) => node,
17 Err(_) => return Err(pv.value.error("prefix must be a NumberTypeNode")),
18 };
19 Ok(Self { prefix })
20 }
21}
22
23impl<'a> TryFrom<&'a CodamaAttribute<'a>> for &'a SizePrefixDirective {
24 type Error = CodamaError;
25
26 fn try_from(attribute: &'a CodamaAttribute) -> Result<Self, Self::Error> {
27 match attribute.directive {
28 CodamaDirective::SizePrefix(ref a) => Ok(a),
29 _ => Err(CodamaError::InvalidCodamaDirective {
30 expected: "size_prefix".to_string(),
31 actual: attribute.directive.name().to_string(),
32 }),
33 }
34 }
35}
36
37impl<'a> TryFrom<&'a Attribute<'a>> for &'a SizePrefixDirective {
38 type Error = CodamaError;
39
40 fn try_from(attribute: &'a Attribute) -> Result<Self, Self::Error> {
41 <&CodamaAttribute>::try_from(attribute)?.try_into()
42 }
43}
44
45#[cfg(test)]
46mod tests {
47 use super::*;
48 use codama_nodes::NumberFormat::U32;
49
50 #[test]
51 fn ok() {
52 let meta: Meta = syn::parse_quote! { size_prefix = number(u32) };
53 let directive = SizePrefixDirective::parse(&meta).unwrap();
54 assert_eq!(
55 directive,
56 SizePrefixDirective {
57 prefix: NumberTypeNode::le(U32).into(),
58 }
59 );
60 }
61}