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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
#![warn(
unknown_lints,
absolute_paths_not_starting_with_crate,
elided_lifetimes_in_paths,
explicit_outlives_requirements,
macro_use_extern_crate,
nonstandard_style, noop_method_call,
rust_2018_idioms,
single_use_lifetimes,
trivial_casts,
trivial_numeric_casts,
future_incompatible, rust_2021_compatibility, missing_debug_implementations,
unreachable_pub,
unsafe_code,
unsafe_op_in_unsafe_fn,
unused, )]
#![deny(
exported_private_dependencies,
private_in_public,
anonymous_parameters,
bare_trait_objects,
ellipsis_inclusive_range_patterns,
deref_nullptr,
drop_bounds,
dyn_drop,
)]
use std::{
collections::BTreeMap,
env,
fmt::{Debug, Display},
fs::File,
hash::Hash,
path::Path,
str::FromStr,
};
use tera::{Map, Value};
pub const DEFAULT_NUMERIC_CODE_TYPE: &str = "u16";
pub const DEFAULT_DATA_DIR: &str = "data";
pub const DEFAULT_TEMPLATE_DIR: &str = "templates";
pub trait Code<T>: Clone + Debug + Display + FromStr + Into<T> + PartialEq + Eq + Hash {
fn is_valid<S>(s: S) -> bool
where
S: AsRef<str>,
{
Self::from_str(s.as_ref()).is_ok()
}
}
pub trait FixedLengthCode {
fn fixed_length() -> usize;
}
pub trait VariableLengthCode {
fn min_length() -> usize;
fn max_length() -> usize;
}
pub type DataRow = Map<String, Value>;
pub type DataMap = BTreeMap<String, Map<String, Value>>;
pub trait Data {
fn new(type_name: &'static str) -> Self
where
Self: Sized;
fn new_with_inner(type_name: &'static str, inner_type_name: &'static str) -> Self
where
Self: Sized;
fn type_name(&self) -> &'static str;
fn inner_type_name(&self) -> Option<&'static str>;
fn has_inner_type(&self) -> bool {
self.inner_type_name().is_some()
}
fn all_ids(&self) -> Vec<&String> {
self.rows().keys().collect()
}
fn all_ids_sorted(&self) -> Value {
let mut all_ids = self.all_ids();
all_ids.sort();
all_ids.dedup();
Value::Array(
all_ids
.into_iter()
.map(|s| Value::String(s.into()))
.collect(),
)
}
fn rows(&self) -> &DataMap;
fn rows_mut(&mut self) -> &mut DataMap;
fn into_rows(self) -> DataMap;
fn contains(&self, id: &str) -> bool {
self.rows().contains_key(id)
}
fn get(&self, id: &str) -> Option<&DataRow> {
self.rows().get(id)
}
fn get_mut(&mut self, id: &str) -> Option<&mut DataRow> {
self.rows_mut().get_mut(id)
}
fn insert_row(&mut self, id: &str, row: DataRow) {
self.rows_mut().insert(id.to_string(), row);
}
fn insert_row_value(&mut self, id: &str, key: &str, value: Value) {
let row = self.get_mut(id).unwrap();
row.insert(key.to_string(), value);
}
}
#[derive(Debug, Default)]
pub struct SimpleData {
type_name: &'static str,
inner_type_name: Option<&'static str>,
rows: DataMap,
}
#[macro_export]
macro_rules! code_impl {
($type_name:ty, $id_field:ident, $ltime:lifetime $id_type_ref:ty, $id_type:ty, $from_fn:ident) => {
impl ::std::fmt::Display for $type_name {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "{}", self.as_ref())
}
}
impl ::std::convert::AsRef<$id_type_ref> for $type_name {
fn as_ref(&self) -> &$ltime $id_type_ref {
&self.$id_field()
}
}
impl ::std::ops::Deref for $type_name {
type Target = $id_type_ref;
fn deref(&self) -> &$ltime Self::Target {
&self.$id_field()
}
}
impl ::std::convert::From<$type_name> for $id_type {
fn from(v: $type_name) -> Self {
v.$id_field().$from_fn()
}
}
impl $crate::Code<$id_type> for $type_name {}
};
($type_name:ty, $id_field:ident, $id_type_ref:ty, $id_type:ty, $from_fn:ident) => {
impl ::std::fmt::Display for $type_name {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "{}", self.as_ref())
}
}
impl ::std::convert::AsRef<$id_type_ref> for $type_name {
fn as_ref(&self) -> &$id_type_ref {
&self.$id_field()
}
}
impl ::std::ops::Deref for $type_name {
type Target = $id_type_ref;
fn deref(&self) -> &Self::Target {
&self.$id_field()
}
}
impl ::std::convert::From<$type_name> for $id_type {
fn from(v: $type_name) -> Self {
v.$id_field().$from_fn()
}
}
impl $crate::Code<$id_type> for $type_name {}
};
($type_name:ty, $id_field:ident, $id_type:ty) => {
impl ::std::fmt::Display for $type_name {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "{}", self.$id_field())
}
}
impl ::std::convert::From<$type_name> for $id_type {
fn from(v: $type_name) -> Self {
v.$id_field()
}
}
impl $crate::Code<$id_type> for $type_name {}
};
($type_name:ty, $id_field:ident) => {
code_impl!($type_name, $id_field, 'static str, String, to_string);
};
($type_name:ty) => {
code_impl!($type_name, code, 'static str, String, to_string);
};
}
#[cfg(feature = "csv_tools")]
#[macro_export]
macro_rules! insert_field {
($value:expr => $row:ident, $name:expr) => {
$row.insert($name.to_string(), $value.into());
};
($record:ident, $index:expr => $row:ident, $name:expr) => {
$row.insert($name.to_string(), $record.get($index).unwrap().into());
};
($record:ident, $index:expr => $row:ident, $name:expr) => {
$row.insert($name.to_string(), $record.get($index).unwrap().into());
};
($record:ident, $row:ident, $($index:expr => $name:expr),+) => {
$(
insert_field!($record, $index => $row, $name);
)+
};
($record:ident, $index:expr => $row:ident, $name:expr, $field_type:ty) => {{
let temp = $record.get($index).unwrap();
let temp = <$field_type>::from_str(temp).unwrap();
$row.insert($name.to_string(), temp.into());
}};
($record:ident, $row:ident, $($index:expr => $name:expr, $field_type:ty),+) => {
$(
insert_field!($record, $index => $row, $name, $field_type);
)+
};
}
#[cfg(feature = "csv_tools")]
#[macro_export]
macro_rules! insert_optional_field {
($record:ident, $index:expr => $row:ident, $name:expr) => {{
let temp = $record.get($index).unwrap();
if !temp.is_empty() {
$row.insert($name.to_string(), temp.into());
}
}};
($record:ident, $row:ident, $($index:expr => $name:expr),+) => {
$(
insert_optional_field!($record, $index => $row, $name);
)+
};
}
pub fn process<T, I, P, F, R>(
init: I,
process_data: P,
finalize: F,
render: R,
) -> Result<(), Box<dyn std::error::Error>>
where
I: FnOnce() -> Result<T, Box<dyn std::error::Error>>,
P: FnOnce(T) -> Result<T, Box<dyn std::error::Error>>,
F: FnOnce(T) -> Result<tera::Context, Box<dyn std::error::Error>>,
R: FnOnce(tera::Context) -> Result<tera::Context, Box<dyn std::error::Error>>,
{
init()
.and_then(process_data)
.and_then(finalize)
.and_then(render)?;
Ok(())
}
pub fn default_init<T>() -> Result<T, Box<dyn std::error::Error>>
where
T: Default,
{
Ok(Default::default())
}
pub fn default_finalize<T>(data: T) -> Result<tera::Context, Box<dyn std::error::Error>>
where
T: Into<tera::Context>,
{
Ok(data.into())
}
pub fn default_finalize_for<T>(data: T) -> Result<tera::Context, Box<dyn std::error::Error>>
where
T: Data,
{
let mut ctx = tera::Context::new();
ctx.insert("type_name", &Value::String(data.type_name().into()));
if let Some(inner_type_name) = data.inner_type_name() {
ctx.insert("inner_type_name", &Value::String(inner_type_name.into()));
}
ctx.insert("all_ids", &data.all_ids_sorted());
ctx.insert(
"codes",
&Value::Object(
data.into_rows()
.into_iter()
.map(|(key, value)| (key, Value::Object(value)))
.collect(),
),
);
Ok(ctx)
}
#[inline]
pub fn input_file_name(name: &str) -> String {
let file_name = format!("{}/{}", DEFAULT_DATA_DIR, name);
rerun_if_changed(&file_name);
file_name
}
#[inline]
pub fn rerun_if_changed(file_name: &str) {
println!("cargo:rerun-if-changed={}", file_name);
}
#[inline]
pub fn rerun_if_template_changed(file_name: &str) {
println!(
"cargo:rerun-if-changed={}/{}",
DEFAULT_TEMPLATE_DIR, file_name
);
}
pub fn make_default_renderer<S1, S2>(
template_name: S1,
generated_file_name: S2,
) -> impl Fn(tera::Context) -> Result<tera::Context, Box<dyn std::error::Error>>
where
S1: Into<String>,
S2: Into<String>,
{
let template_name = template_name.into();
let generated_file_name = generated_file_name.into();
move |ctx: tera::Context| -> Result<tera::Context, Box<dyn std::error::Error>> {
let output_dir: String = env::var("OUT_DIR").unwrap();
let file_name = Path::new(&output_dir).join(&generated_file_name);
rerun_if_template_changed(&template_name);
let tera = tera::Tera::new(&format!("{}/*._rs", DEFAULT_TEMPLATE_DIR))?;
let file = File::create(file_name)?;
tera.render_to(&template_name, &ctx, file)?;
Ok(ctx)
}
}
impl Data for SimpleData {
fn new(type_name: &'static str) -> Self
where
Self: Sized,
{
Self {
type_name,
inner_type_name: None,
rows: Default::default(),
}
}
fn new_with_inner(type_name: &'static str, inner_type_name: &'static str) -> Self
where
Self: Sized,
{
Self {
type_name,
inner_type_name: Some(inner_type_name),
rows: Default::default(),
}
}
fn type_name(&self) -> &'static str {
self.type_name
}
fn inner_type_name(&self) -> Option<&'static str> {
self.inner_type_name
}
fn rows(&self) -> &BTreeMap<String, Map<String, Value>> {
&self.rows
}
fn rows_mut(&mut self) -> &mut BTreeMap<String, Map<String, Value>> {
&mut self.rows
}
fn into_rows(self) -> BTreeMap<String, Map<String, Value>> {
self.rows
}
}
impl SimpleData {
pub fn retain<F>(&mut self, f: F)
where
F: FnMut(&String, &mut Map<String, Value>) -> bool,
{
self.rows.retain(f);
}
}
#[doc(hidden)]
mod error;
pub use error::{invalid_character, invalid_format, invalid_length, unknown_value, CodeParseError};
#[cfg(feature = "csv_tools")]
pub mod csv;