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
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
/*!
This create provides a derive macro for the `fixed_width` crate's `Field` trait by providing
a set of struct field attributes that can be used to more easily derive the trait.

The derive only works on structs. Additionally, this crate uses features that require Rust version 1.30.0+ to run.

# Installing

Start by adding the dependency to your project in `Cargo.toml`:

```toml
fixed_width = "0.1"
fixed_width_derive = "0.1"
```

Then in the root of your project:

```
#[macro_use]
extern crate fixed_width_derive;
extern crate fixed_width;
# fn main() {}
```

# Usage

```rust
#[macro_use]
extern crate fixed_width_derive;
extern crate fixed_width;

#[derive(FixedWidth)]
struct Person {
    #[fixed_width(range = "0..6")]
    pub name: String,
    #[fixed_width(range = "6..9", pad_with = "0")]
    pub age: usize,
    #[fixed_width(range = "9..11", name = "height_cm", justify = "right")]
    pub height: usize,
}
# fn main() {}
```

The above sample is equivalent to implementing the following with the `fixed_width`
crate alone:

```rust
extern crate fixed_width;

use fixed_width::{FixedWidth, Field, Justify};

struct Person {
    pub name: String,
    pub age: usize,
    pub height: usize,
}

impl FixedWidth for Person {
    fn fields() -> Vec<Field> {
        vec![
            Field::default().range(0..6),
            Field::default().range(6..9).pad_with('0'),
            Field::default().range(9..11).justify(Justify::Right).name(Some("height_cm")),
        ]
    }
}
# fn main() {}
```

The full set of options you can supply for the attribute annotations are:

### `range = "x..y"`
Required. Range values must be of type `usize`. The byte range of the given field.

### `pad_with = "c"`
Defaults to `' '`. Must be of type `char`. The character to pad to the left or right after the
value of the field has been converted to bytes. For instance, if the width of
the field was 5, and the value is `"foo"`, then a left justified field padded with `a`
results in: `"fooaa"`.

### `justify = "left|right"`
Defaults to `"left"`. Must be of enum type `Justify`. Indicates whether this field should be justified
left or right once it has been converted to bytes.

### `name = "s"`
Defaults to the name of the struct field. Indicates the name of the field. Useful if you wish to deserialize
fixed width data into a HashMap.
!*/

extern crate proc_macro;
extern crate proc_macro2;
#[macro_use]
extern crate syn;
#[macro_use]
extern crate quote;
extern crate fixed_width;

use proc_macro::TokenStream;
use std::result;
use syn::DeriveInput;

mod field_def;
use field_def::{Context, FieldDef};

#[proc_macro_derive(FixedWidth, attributes(fixed_width))]
pub fn fixed_width(input: TokenStream) -> TokenStream {
    let input: DeriveInput = syn::parse(input).unwrap();
    impl_fixed_width(&input)
}

fn impl_fixed_width(ast: &DeriveInput) -> TokenStream {
    let fields: Vec<syn::Field> = match ast.data {
        syn::Data::Struct(syn::DataStruct { ref fields, .. }) => {
            if fields.iter().any(|field| field.ident.is_none()) {
                panic!("struct has unnamed fields");
            }
            fields.iter().cloned().collect()
        }
        _ => panic!("#[derive(FixedWidth)] can only be used with structs"),
    };

    let ident = &ast.ident;
    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();

    let tokens: Vec<proc_macro2::TokenStream> = fields
        .iter()
        .map(build_field_def)
        .map(build_fixed_width_field)
        .collect();

    let quote = quote! {
        impl #impl_generics fixed_width::FixedWidth for #ident #ty_generics #where_clause {
            fn fields() -> Vec<fixed_width::Field> {
                vec![
                    #(#tokens),*
                ]
            }
        }
    };

    quote.into()
}

fn build_field_def(field: &syn::Field) -> FieldDef {
    let ctx = Context::from_field(field);

    let name = match ctx.metadata.get("name") {
        Some(name) => name.value.clone(),
        None => ctx.field_name(),
    };

    let range = if let Some(r) = ctx.metadata.get("range") {
        let range_parts = r
            .value
            .split("..")
            .map(|s| s.parse::<usize>())
            .filter_map(result::Result::ok)
            .collect::<Vec<usize>>();

        if range_parts.len() != 2 {
            panic!("Invalid range {} for field: {}", r.value, ctx.field_name());
        }

        range_parts[0]..range_parts[1]
    } else {
        panic!("Must supply a byte range for field: {}", ctx.field_name());
    };

    let pad_with = ctx.metadata.get("pad_with").map_or(' ', |c| {
        if c.value.len() != 1 {
            panic!("pad_with must be a char for field: {}", ctx.field_name());
        }

        c.value.chars().nth(0).unwrap()
    });

    let justify = match ctx.metadata.get("justify") {
        Some(j) => match j.value.to_lowercase().trim().as_ref() {
            "left" | "right" => j.value.clone(),
            _ => panic!(
                "justify must be 'left' or 'right' for field: {}",
                ctx.field_name()
            ),
        },
        None => "left".to_string(),
    };

    FieldDef {
        ident: ctx.field.clone().ident.unwrap(),
        field_type: field.ty.clone(),
        name,
        pad_with,
        range,
        justify,
    }
}

fn build_fixed_width_field(field_def: FieldDef) -> proc_macro2::TokenStream {
    let name = field_def.name;
    let start = field_def.range.start;
    let end = field_def.range.end;
    let pad_with = field_def.pad_with;
    let justify = field_def.justify;

    quote! {
        fixed_width::Field::default()
            .name(Some(#name))
            .range(#start..#end)
            .pad_with(#pad_with)
            .justify(#justify.to_string())
    }
}