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 serde::Serialize;
use tera::{Context, Tera};
use crate::*;
#[derive(Default, Serialize)]
pub struct Struct {
is_pub: bool,
name: String,
fields: Vec<Field>,
generics: Generics,
docs: Vec<String>,
}
impl Struct {
pub fn new<S: ToString>(name: S, is_pub: bool) -> Self {
let mut s = Struct::default();
s.name = name.to_string();
s.is_pub = is_pub;
s
}
pub fn add_field(&mut self, field: Field) {
self.fields.push(field)
}
pub fn add_generic(&mut self, generic: Generic) {
self.generics.add_generic(generic)
}
}
impl SrcCode for Struct {
fn generate(&self) -> String {
let template = r#"
{% if struct.is_pub %}pub {% endif %}struct {{ struct.name }}{{ generics }} {
{% for field in fields %}{{ field }}{% endfor %}
}
"#;
let mut context = Context::new();
context.insert("struct", &self);
let fields = self
.fields
.iter()
.map(|f| f.generate())
.collect::<Vec<String>>();
context.insert("fields", &fields);
context.insert("generics", &self.generics.generate());
Tera::one_off(template, &context, false).unwrap()
}
}