binrw_derive/binrw/parser/types/
condition.rs

1use crate::binrw::parser::attrs;
2use proc_macro2::TokenStream;
3use quote::ToTokens;
4use syn::spanned::Spanned;
5
6#[derive(Debug, Clone)]
7pub(crate) struct Condition {
8    pub(crate) condition: TokenStream,
9    pub(crate) alternate: Option<TokenStream>,
10}
11
12impl TryFrom<attrs::If> for Condition {
13    type Error = syn::Error;
14
15    fn try_from(value: attrs::If) -> Result<Self, Self::Error> {
16        let mut args = value.fields.iter();
17
18        let condition = if let Some(cond) = args.next() {
19            cond.into_token_stream()
20        } else {
21            return Err(Self::Error::new(
22                value.ident.span(),
23                "`if` requires a boolean expression as an argument",
24            ));
25        };
26
27        let alternate = args.next().map(ToTokens::into_token_stream);
28
29        super::assert_all_args_consumed(args, value.ident.span())?;
30
31        Ok(Self {
32            condition,
33            alternate,
34        })
35    }
36}