zerocopy_derive/
ext.rs

1// Copyright 2019 The Fuchsia Authors
2//
3// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
4// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
5// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
6// This file may not be copied, modified, or distributed except according to
7// those terms.
8
9use syn::{Data, DataEnum, DataStruct, DataUnion, Type};
10
11pub trait DataExt {
12    /// Extract the types of all fields. For enums, extract the types of fields
13    /// from each variant.
14    fn field_types(&self) -> Vec<&Type>;
15}
16
17impl DataExt for Data {
18    fn field_types(&self) -> Vec<&Type> {
19        match self {
20            Data::Struct(strc) => strc.field_types(),
21            Data::Enum(enm) => enm.field_types(),
22            Data::Union(un) => un.field_types(),
23        }
24    }
25}
26
27impl DataExt for DataStruct {
28    fn field_types(&self) -> Vec<&Type> {
29        self.fields.iter().map(|f| &f.ty).collect()
30    }
31}
32
33impl DataExt for DataEnum {
34    fn field_types(&self) -> Vec<&Type> {
35        self.variants.iter().flat_map(|var| &var.fields).map(|f| &f.ty).collect()
36    }
37}
38
39impl DataExt for DataUnion {
40    fn field_types(&self) -> Vec<&Type> {
41        self.fields.named.iter().map(|f| &f.ty).collect()
42    }
43}
44
45pub trait EnumExt {
46    fn is_c_like(&self) -> bool;
47}
48
49impl EnumExt for DataEnum {
50    fn is_c_like(&self) -> bool {
51        self.field_types().is_empty()
52    }
53}