codama_attributes/codama_directives/
encoding_directive.rs1use crate::{Attribute, CodamaAttribute, CodamaDirective};
2use codama_errors::CodamaError;
3use codama_nodes::BytesEncoding;
4use codama_syn_helpers::{extensions::*, Meta};
5
6#[derive(Debug, PartialEq)]
7pub struct EncodingDirective {
8 pub encoding: BytesEncoding,
9}
10
11impl EncodingDirective {
12 pub fn parse(meta: &Meta) -> syn::Result<Self> {
13 let path = meta.assert_directive("encoding")?.as_value()?.as_path()?;
14 match BytesEncoding::try_from(path.to_string()) {
15 Ok(encoding) => Ok(Self { encoding }),
16 _ => Err(path.error("invalid encoding")),
17 }
18 }
19}
20
21impl<'a> TryFrom<&'a CodamaAttribute<'a>> for &'a EncodingDirective {
22 type Error = CodamaError;
23
24 fn try_from(attribute: &'a CodamaAttribute) -> Result<Self, Self::Error> {
25 match attribute.directive {
26 CodamaDirective::Encoding(ref a) => Ok(a),
27 _ => Err(CodamaError::InvalidCodamaDirective {
28 expected: "encoding".to_string(),
29 actual: attribute.directive.name().to_string(),
30 }),
31 }
32 }
33}
34
35impl<'a> TryFrom<&'a Attribute<'a>> for &'a EncodingDirective {
36 type Error = CodamaError;
37
38 fn try_from(attribute: &'a Attribute) -> Result<Self, Self::Error> {
39 <&CodamaAttribute>::try_from(attribute)?.try_into()
40 }
41}
42
43#[cfg(test)]
44mod tests {
45 use super::*;
46
47 #[test]
48 fn ok() {
49 let meta: Meta = syn::parse_quote! { encoding = base64 };
50 let directive = EncodingDirective::parse(&meta).unwrap();
51 assert_eq!(
52 directive,
53 EncodingDirective {
54 encoding: BytesEncoding::Base64
55 }
56 );
57 }
58}