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 pv = meta.assert_directive("encoding")?.as_path_value()?;
14 let value = pv.value.as_path()?;
15 match BytesEncoding::try_from(value.to_string()) {
16 Ok(encoding) => Ok(Self { encoding }),
17 _ => Err(value.error("invalid encoding")),
18 }
19 }
20}
21
22impl<'a> TryFrom<&'a CodamaAttribute<'a>> for &'a EncodingDirective {
23 type Error = CodamaError;
24
25 fn try_from(attribute: &'a CodamaAttribute) -> Result<Self, Self::Error> {
26 match attribute.directive {
27 CodamaDirective::Encoding(ref a) => Ok(a),
28 _ => Err(CodamaError::InvalidCodamaDirective {
29 expected: "encoding".to_string(),
30 actual: attribute.directive.name().to_string(),
31 }),
32 }
33 }
34}
35
36impl<'a> TryFrom<&'a Attribute<'a>> for &'a EncodingDirective {
37 type Error = CodamaError;
38
39 fn try_from(attribute: &'a Attribute) -> Result<Self, Self::Error> {
40 <&CodamaAttribute>::try_from(attribute)?.try_into()
41 }
42}
43
44#[cfg(test)]
45mod tests {
46 use super::*;
47
48 #[test]
49 fn ok() {
50 let meta: Meta = syn::parse_quote! { encoding = base64 };
51 let directive = EncodingDirective::parse(&meta).unwrap();
52 assert_eq!(
53 directive,
54 EncodingDirective {
55 encoding: BytesEncoding::Base64
56 }
57 );
58 }
59}