1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use std::ops::Deref;

use syn::{Ident, NestedMeta, Meta};

use {FromMetaItem, Result, Error};

/// A list of `syn::Ident` instances. This type is used to extract a list of words from an 
/// attribute.
///
/// # Usage
/// An `IdentList` field on a struct implementing `FromMetaItem` will turn `#[builder(derive(Debug, Clone))]` into:
///
/// ```rust,ignore
/// StructOptions {
///     derive: IdentList(vec![syn::Ident::new("Debug"), syn::Ident::new("Clone")])
/// }
/// ```
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct IdentList(Vec<Ident>);

impl IdentList {
    /// Create a new list.
    pub fn new<T: Into<Ident>>(vals: Vec<T>) -> Self {
        IdentList(vals.into_iter().map(T::into).collect())
    }

    /// Creates a view of the contained identifiers as `&str`s.
    pub fn as_strs<'a>(&'a self) -> Vec<&'a str> {
        self.iter().map(|i| i.as_ref()).collect()
    }
}

impl Deref for IdentList {
    type Target = Vec<Ident>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl From<Vec<Ident>> for IdentList {
    fn from(v: Vec<Ident>) -> Self {
        IdentList(v)
    }
}

impl FromMetaItem for IdentList {
    fn from_list(v: &[NestedMeta]) -> Result<Self> {
        let mut idents = Vec::with_capacity(v.len());
        for nmi in v {
            if let NestedMeta::Meta(Meta::Word(ref ident)) = *nmi {
                idents.push(ident.clone());
            } else {
                return Err(Error::unexpected_type("non-word"))
            }
        }

        Ok(IdentList(idents))
    }
}