hrdf-parser 0.9.4

This library is dedicated to the parsing of the HRDF format. For the moment, it can only parse the Swiss version of the HRDF format.
Documentation
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
use std::path::Path;

/// # BETRIEB_* files
///
/// List of transport companies. The term “transport company” is understood in different ways.
/// In the context of opentransportdata.swiss, it is understood that it is an organisation
/// that is responsible for the runs described in the FPLAN. A detailed description of
/// the transport companies and business organisations can be found here.
///
/// Each TU is described in detail with 2 lines:
///
///
/// - The first line:
///     - Operator no. (for BETRIEB / OPERATION file)
///         - Short name (after the “K”)
///         - Long name (after the “L”)
///         - Full name (after the”V”)
///
/// - The second line:
///     - Operator no. (for BETRIEB / OPERATION file)
///     - “:”
///     - TU code (or administration number)
///         - Several TU codes can be listed. These share the information in the first line.
///
/// ## Example (excerpt):
///
/// `
/// ...
/// 00379 K "SBB" L "SBB" V "Schweizerische Bundesbahnen SBB"     % Betrieb-Nr 00379, kurz sbb, lang sbb, voll schweizerische bundesbahn sbb
/// 00379 : 000011                                                % Betrieb-Nr 00379, TU-Code 000011
/// 00380 K "SOB" L "SOB-bt" V "Schweizerische Südostbahn (bt)"   % Betrieb-Nr 00380, kurz sob, lang sob-bt,  voll schweizerische südostbahn (bt)
/// 00380 : 000036                                                % Betrieb-Nr 00380, TU-Code 000036
/// 00381 K "SOB" L "SOB-sob" V "Schweizerische Südostbahn (sob)" % Betrieb-Nr 00381, kurz sob, lang sob-sob, voll schweizerische südostbahn (sob)
/// 00381 : 000082                                                % Betrieb-Nr 00381, TU-Code 000082
/// ...
/// `
///
/// 4 file(s).
/// File(s) read by the parser:
/// BETRIEB_DE, BETRIEB_EN, BETRIEB_FR, BETRIEB_IT
use nom::{
    IResult, Parser,
    branch::alt,
    bytes::{complete::take_until, tag},
    character::complete::{i32, space1},
    combinator::map,
    sequence::{preceded, terminated},
};
use rustc_hash::FxHashMap;

use crate::error::{HResult, HrdfError};
use crate::{
    models::{Language, TransportCompany},
    parsing::{
        error::PResult,
        helpers::{read_lines, string_till_eol_parser},
    },
    storage::ResourceStorage,
};

enum TransportCompanyLine {
    Kline {
        id: i32,
        short_name: String,
        long_name: String,
        full_name: String,
    },
    Nline {
        #[allow(unused)]
        id: i32,
        #[allow(unused)]
        sboid: String,
    },
    ColonLine {
        id: i32,
        administrations: Vec<String>,
    },
}

fn kline_combinator(input: &str) -> IResult<&str, TransportCompanyLine> {
    map(
        (
            i32,
            preceded(
                tag(" K"),
                preceded(
                    space1,
                    map(
                        terminated(preceded(tag("\""), take_until("\"")), tag("\"")),
                        String::from,
                    ),
                ),
            ),
            preceded(
                tag(" L"),
                preceded(
                    space1,
                    map(
                        terminated(preceded(tag("\""), take_until("\"")), tag("\"")),
                        String::from,
                    ),
                ),
            ),
            preceded(
                tag(" V"),
                preceded(
                    space1,
                    map(
                        terminated(preceded(tag("\""), take_until("\"")), tag("\"")),
                        String::from,
                    ),
                ),
            ),
        ),
        |(id, short_name, long_name, full_name)| TransportCompanyLine::Kline {
            id,
            short_name,
            long_name,
            full_name,
        },
    )
    .parse(input)
}

fn nline_combinator(input: &str) -> IResult<&str, TransportCompanyLine> {
    map(
        (
            i32,
            preceded(
                tag(" N"),
                preceded(
                    space1,
                    map(
                        terminated(preceded(tag("\""), take_until("\"")), tag("\"")),
                        String::from,
                    ),
                ),
            ),
        ),
        |(id, sboid)| TransportCompanyLine::Nline { id, sboid },
    )
    .parse(input)
}

fn colon_combinator(input: &str) -> IResult<&str, TransportCompanyLine> {
    map(
        (
            i32,
            preceded(
                space1,
                preceded(tag(":"), preceded(space1, string_till_eol_parser)),
            ),
        ),
        |(id, administrations)| {
            let administrations = administrations
                .split(" ")
                .map(String::from)
                .collect::<Vec<_>>();

            TransportCompanyLine::ColonLine {
                id,
                administrations,
            }
        },
    )
    .parse(input)
}

fn parse_transport_company_line(
    line: &str,
    transport_company: &mut FxHashMap<i32, TransportCompany>,
    language: Language,
) -> PResult<()> {
    let (_, tcl) = alt((kline_combinator, nline_combinator, colon_combinator)).parse(line)?;

    match tcl {
        TransportCompanyLine::Kline {
            id,
            short_name,
            long_name,
            full_name,
        } => {
            if let Some(tc) = transport_company.get_mut(&id) {
                tc.set_short_name(language, &short_name);
                tc.set_full_name(language, &full_name);
                tc.set_long_name(language, &long_name);
            } else {
                let mut tc = TransportCompany::new(id);
                tc.set_short_name(language, &short_name);
                tc.set_full_name(language, &full_name);
                tc.set_long_name(language, &long_name);
                transport_company.insert(id, tc);
            }
        }
        TransportCompanyLine::Nline { id: _, sboid: _ } => {
            // TODO: Use sboid some day
        }
        TransportCompanyLine::ColonLine {
            id,
            administrations,
        } => {
            if let Some(tc) = transport_company.get_mut(&id) {
                tc.set_administrations(administrations);
            } else {
                let mut tc = TransportCompany::new(id);
                tc.set_administrations(administrations);
                transport_company.insert(id, tc);
            }
        }
    }

    Ok(())
}

pub fn parse(path: &Path) -> HResult<ResourceStorage<TransportCompany>> {
    let languages = [
        Language::German,
        Language::English,
        Language::French,
        Language::Italian,
    ];
    let mut transport_company = FxHashMap::default();

    for language in languages {
        let postfix = match language {
            Language::German => "DE",
            Language::French => "FR",
            Language::English => "EN",
            Language::Italian => "IT",
        };
        log::info!("Parsing BETRIEB_{postfix}...");
        let file = path.join(format!("BETRIEB_{postfix}"));
        read_lines(&file, 0)?
            .into_iter()
            .enumerate()
            .filter(|(_, line)| !line.trim().is_empty())
            .try_for_each(|(line_number, line)| {
                parse_transport_company_line(&line, &mut transport_company, language).map_err(|e| {
                    HrdfError::Parsing {
                        error: e,
                        file: String::from(file.to_string_lossy()),
                        line,
                        line_number,
                    }
                })
            })?;
    }

    Ok(ResourceStorage::new(transport_company))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parsing::tests::get_json_values;
    use pretty_assertions::assert_eq;

    #[test]
    fn test_kline_combinator_basic() {
        let input = r#"00379 K "SBB" L "SBB" V "Schweizerische Bundesbahnen SBB""#;
        let result = kline_combinator(input);
        assert!(result.is_ok());
        let (_, tc_line) = result.unwrap();
        match tc_line {
            TransportCompanyLine::Kline {
                id,
                short_name,
                long_name,
                full_name,
            } => {
                assert_eq!(id, 379);
                assert_eq!(short_name, "SBB");
                assert_eq!(long_name, "SBB");
                assert_eq!(full_name, "Schweizerische Bundesbahnen SBB");
            }
            _ => panic!("Expected Kline variant"),
        }
    }

    #[test]
    fn test_kline_combinator_sob() {
        let input = r#"00380 K "SOB" L "SOB-bt" V "Schweizerische Südostbahn (bt)""#;
        let result = kline_combinator(input);
        assert!(result.is_ok());
        let (_, tc_line) = result.unwrap();
        match tc_line {
            TransportCompanyLine::Kline {
                id,
                short_name,
                long_name,
                full_name,
            } => {
                assert_eq!(id, 380);
                assert_eq!(short_name, "SOB");
                assert_eq!(long_name, "SOB-bt");
                assert_eq!(full_name, "Schweizerische Südostbahn (bt)");
            }
            _ => panic!("Expected Kline variant"),
        }
    }

    #[test]
    fn test_kline_combinator_with_spaces_in_names() {
        let input = r#"00381 K "SOB" L "SOB-sob" V "Schweizerische Südostbahn (sob)""#;
        let result = kline_combinator(input);
        assert!(result.is_ok());
        let (_, tc_line) = result.unwrap();
        match tc_line {
            TransportCompanyLine::Kline {
                id,
                short_name,
                long_name,
                full_name,
            } => {
                assert_eq!(id, 381);
                assert_eq!(short_name, "SOB");
                assert_eq!(long_name, "SOB-sob");
                assert_eq!(full_name, "Schweizerische Südostbahn (sob)");
            }
            _ => panic!("Expected Kline variant"),
        }
    }

    #[test]
    fn test_nline_combinator() {
        let input = r#"00379 N "ch:1:sboid:379""#;
        let result = nline_combinator(input);
        assert!(result.is_ok());
        let (_, tc_line) = result.unwrap();
        match tc_line {
            TransportCompanyLine::Nline { id, sboid } => {
                assert_eq!(id, 379);
                assert_eq!(sboid, "ch:1:sboid:379");
            }
            _ => panic!("Expected Nline variant"),
        }
    }

    #[test]
    fn test_colon_combinator_single_admin() {
        let input = "00379 : 000011";
        let result = colon_combinator(input);
        assert!(result.is_ok());
        let (_, tc_line) = result.unwrap();
        match tc_line {
            TransportCompanyLine::ColonLine {
                id,
                administrations,
            } => {
                assert_eq!(id, 379);
                assert_eq!(administrations.len(), 1);
                assert_eq!(administrations[0], "000011");
            }
            _ => panic!("Expected ColonLine variant"),
        }
    }

    #[test]
    fn test_colon_combinator_multiple_admins() {
        let input = "00380 : 000036 000082";
        let result = colon_combinator(input);
        assert!(result.is_ok());
        let (_, tc_line) = result.unwrap();
        match tc_line {
            TransportCompanyLine::ColonLine {
                id,
                administrations,
            } => {
                assert_eq!(id, 380);
                assert_eq!(administrations.len(), 2);
                assert_eq!(administrations[0], "000036");
                assert_eq!(administrations[1], "000082");
            }
            _ => panic!("Expected ColonLine variant"),
        }
    }

    #[test]
    fn test_parse_transport_company_line_creates_new_company() {
        let mut companies = FxHashMap::default();
        parse_transport_company_line(
            r#"00379 K "SBB" L "SBB" V "Schweizerische Bundesbahnen SBB""#,
            &mut companies,
            Language::German,
        )
        .unwrap();
        assert_eq!(companies.len(), 1);
        let company = companies.get(&379).unwrap();
        let reference = r#"
            {
                "id":379,
                "short_name":{"German":"SBB"},
                "long_name":{"German":"SBB"},
                "full_name":{"German":"Schweizerische Bundesbahnen SBB"},
                "administrations":[]
            }"#;

        let (company, reference) = get_json_values(company, reference).unwrap();
        assert_eq!(company, reference);
    }

    #[test]
    fn test_parse_transport_company_line_updates_existing() {
        let mut companies = FxHashMap::default();

        // Create company
        parse_transport_company_line(
            r#"00379 K "SBB" L "SBB" V "Schweizerische Bundesbahnen SBB""#,
            &mut companies,
            Language::German,
        )
        .unwrap();

        // Update with colon line
        parse_transport_company_line("00379 : 000011", &mut companies, Language::German).unwrap();

        assert_eq!(companies.len(), 1);
        let company = companies.get(&379).unwrap();
        let reference = r#"
            {
                "id":379,
                "short_name":{"German":"SBB"},
                "long_name":{"German":"SBB"},
                "full_name":{"German":"Schweizerische Bundesbahnen SBB"},
                "administrations":["000011"]
            }"#;

        let (company, reference) = get_json_values(company, reference).unwrap();
        assert_eq!(company, reference);
    }

    #[test]
    fn test_parse_transport_company_line_multiple_languages() {
        let mut companies = FxHashMap::default();

        parse_transport_company_line(
            r#"00379 K "SBB" L "SBB" V "Schweizerische Bundesbahnen SBB""#,
            &mut companies,
            Language::German,
        )
        .unwrap();

        parse_transport_company_line(
            r#"00379 K "CFF" L "CFF" V "Chemins de fer fédéraux CFF""#,
            &mut companies,
            Language::French,
        )
        .unwrap();

        assert_eq!(companies.len(), 1);
        let company = companies.get(&379).unwrap();
        let reference = r#"
            {
                "id":379,
                "short_name":{"German":"SBB", "French":"CFF"},
                "long_name":{"German":"SBB", "French":"CFF"},
                "full_name":{"German":"Schweizerische Bundesbahnen SBB", "French":"Chemins de fer fédéraux CFF"},
                "administrations":[]
            }"#;

        let (company, reference) = get_json_values(company, reference).unwrap();
        assert_eq!(company, reference);
    }

    #[test]
    fn test_colon_line_creates_company_if_not_exists() {
        let mut companies = FxHashMap::default();

        parse_transport_company_line("00379 : 000011", &mut companies, Language::German).unwrap();

        assert_eq!(companies.len(), 1);
        let company = companies.get(&379).unwrap();
        let reference = r#"
            {
                "id":379,
                "short_name":{},
                "long_name":{},
                "full_name":{},
                "administrations":["000011"]
            }"#;

        let (company, reference) = get_json_values(company, reference).unwrap();
        assert_eq!(company, reference);
    }

    #[test]
    fn test_nline_parsing_ignores_sboid() {
        let mut companies = FxHashMap::default();
        companies.insert(379, TransportCompany::new(379));

        let result = parse_transport_company_line(
            r#"00379 N "ch:1:sboid:379""#,
            &mut companies,
            Language::German,
        );

        assert!(result.is_ok());
        // SBOID is currently not used (TODO in code)
        let company = companies.get(&379).unwrap();
        let reference = r#"
            {
                "id":379,
                "short_name":{},
                "long_name":{},
                "full_name":{},
                "administrations":[]
            }"#;

        let (company, reference) = get_json_values(company, reference).unwrap();
        assert_eq!(company, reference);
    }
}