assert_type_match/
utils.rs

1use crate::fields::FieldArgs;
2use crate::variants::VariantArgs;
3use crate::ATTRIBUTE;
4use syn::{Attribute, Field, Member};
5
6/// Extracts all `cfg` attributes from the given list of attributes.
7pub(crate) fn extract_cfg_attrs(attrs: &[Attribute]) -> impl Iterator<Item = &Attribute> {
8    attrs.iter().filter(|attr| attr.path().is_ident("cfg"))
9}
10
11pub(crate) fn extract_field_args(attrs: &[Attribute]) -> syn::Result<FieldArgs> {
12    let mut args = FieldArgs::default();
13
14    for attr in attrs.iter().filter(|attr| attr.path().is_ident(ATTRIBUTE)) {
15        args = args.merge(attr.parse_args::<FieldArgs>()?)?;
16    }
17
18    Ok(args)
19}
20
21pub(crate) fn extract_variant_args(attrs: &[Attribute]) -> syn::Result<VariantArgs> {
22    let mut args = VariantArgs::default();
23
24    for attr in attrs.iter().filter(|attr| attr.path().is_ident(ATTRIBUTE)) {
25        args = args.merge(attr.parse_args::<VariantArgs>()?)?;
26    }
27
28    Ok(args)
29}
30
31/// Creates a [`Member`] from the given field and index.
32pub(crate) fn create_member(field: &Field, index: usize) -> Member {
33    field
34        .ident
35        .clone()
36        .map(Member::from)
37        .unwrap_or_else(|| Member::from(index))
38}
39
40/// Unzips an iterator of results into a result of two collections.
41///
42/// Taken from [this] post.
43///
44/// [this]: https://users.rust-lang.org/t/unzip-with-error-handling/110250/4
45pub(crate) fn try_unzip<I, C, T, E>(iter: I) -> Result<C, E>
46where
47    I: IntoIterator<Item = Result<T, E>>,
48    C: Extend<T> + Default,
49{
50    iter.into_iter().try_fold(C::default(), |mut c, r| {
51        c.extend([r?]);
52        Ok(c)
53    })
54}