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
/// # Line Exchange Time parser
///
/// For more information see
/// [https://opentransportdata.swiss/en/cookbook/hafas-rohdaten-format-hrdf/#Technical_description_What_is_in_the_HRDF_files_contents](the HRDF documentation).
///
/// Transfer time per category of service and/or line. The file contains:
///
/// - Stop number
/// - Administration 1 (see BETRIEB / OPERATION file)
/// - Type (offer category) 1
/// - Line 1 (* = quasi-interchange times)
/// - Direction 1 (* = all directions)
/// - Administration 2 (see BETRIEB / OPERATION file),
/// - Type (offer category) 2,
/// - Line 2 (* = quasi-interchange times),
/// - Direction 2 (* = all directions),
/// - Transfer time in min.
/// - “!” for guaranteed changeover
/// - Name of stop
///
/// ## Remarks
///
/// The name of the stop is ignored here
///
/// Example (excerpt):
///
/// `
/// 1111145 sbg034 B   7322 H sbg034 TX  7322 H 000! Waldkirch (WT), Rathaus % HS-Nr 1111145, TU-Code sbg034, Angebotskategorie B, Linie 1, Richtung Hin, ...
/// 8500010 000011 EXT *    * 000011 TER *    * 010  Basel SBB               % HS-Nr 8500010, TU-Code 11, Angebotskategorie EXT, alle Linien, alle Richtungen, ...
/// `
///
/// 1 file(s).
/// File(s) read by the parser:
/// UMSTEIGL
use std::{path::Path, str::FromStr};

use nom::{IResult, Parser, character::char, combinator::map, sequence::preceded};
use rustc_hash::FxHashMap;

use crate::{
    error::{HResult, HrdfError},
    models::{DirectionType, ExchangeTimeLine, LineInfo},
    parsing::{
        error::PResult,
        helpers::{
            i16_from_n_digits_parser, optional_i32_from_n_digits_parser, read_lines,
            string_from_n_chars_parser,
        },
    },
    storage::ResourceStorage,
    utils::AutoIncrement,
};

type ExchangeTimeLineRow = (
    Option<i32>,
    String,
    String,
    String,
    String,
    String,
    String,
    String,
    String,
    i16,
    bool,
);

fn parse_exchange_line_row(input: &str) -> IResult<&str, ExchangeTimeLineRow> {
    // TODO: I haven't seen an is_guaranteed field in the doc. Check if this makes sense.
    // It is present in UMSTEIGL. Maybe a copy/paste leftover
    //
    // TODO: There is still a String after all the parsing is done that remains (a name)
    let (
        res,
        (
            stop_id,
            administration_1,
            transport_type_1,
            line_id_1,
            direction_1,
            administration_2,
            transport_type_2,
            line_id_2,
            direction_2,
            duration,
            is_guaranteed,
        ),
    ) = (
        optional_i32_from_n_digits_parser(7),
        preceded(char(' '), string_from_n_chars_parser(6)),
        preceded(char(' '), string_from_n_chars_parser(3)),
        preceded(char(' '), string_from_n_chars_parser(8)),
        preceded(char(' '), string_from_n_chars_parser(1)),
        preceded(char(' '), string_from_n_chars_parser(6)),
        preceded(char(' '), string_from_n_chars_parser(3)),
        preceded(char(' '), string_from_n_chars_parser(8)),
        preceded(char(' '), string_from_n_chars_parser(1)),
        preceded(char(' '), i16_from_n_digits_parser(3)),
        map(string_from_n_chars_parser(1), |s| s == "!"),
    )
        .parse(input)?;
    Ok((
        res,
        (
            stop_id,
            administration_1,
            transport_type_1,
            line_id_1,
            direction_1,
            administration_2,
            transport_type_2,
            line_id_2,
            direction_2,
            duration,
            is_guaranteed,
        ),
    ))
}

fn parse_line(
    line: &str,
    auto_increment: &AutoIncrement,
    transport_types_pk_type_converter: &FxHashMap<String, i32>,
) -> PResult<(i32, ExchangeTimeLine)> {
    let (
        _res,
        (
            stop_id,
            administration_1,
            transport_type_id_1,
            line_id_1,
            direction_1,
            administration_2,
            transport_type_id_2,
            line_id_2,
            direction_2,
            duration,
            is_guaranteed,
        ),
    ) = parse_exchange_line_row(line)?;

    let transport_type_id_1 = *transport_types_pk_type_converter
        .get(&transport_type_id_1)
        .ok_or("Unknown legacy ID for transport_type_1 {transport_type_id_1}")?;

    let line_id_1 = if line_id_1 == "*" {
        None
    } else {
        Some(line_id_1)
    };

    let direction_1 = if direction_1 == "*" {
        None
    } else {
        Some(DirectionType::from_str(&direction_1)?)
    };

    let transport_type_id_2 = *transport_types_pk_type_converter
        .get(&transport_type_id_2)
        .ok_or("Unknown legacy ID for transport_type_id_2 {transport_type_id_2}")?;

    let line_id_2 = if line_id_2 == "*" {
        None
    } else {
        Some(line_id_2)
    };

    let direction_2 = if direction_2 == "*" {
        None
    } else {
        Some(DirectionType::from_str(&direction_2)?)
    };

    let line_1 = LineInfo::new(
        administration_1,
        transport_type_id_1,
        line_id_1,
        direction_1,
    );
    let line_2 = LineInfo::new(
        administration_2,
        transport_type_id_2,
        line_id_2,
        direction_2,
    );

    let id = auto_increment.next();

    Ok((
        id,
        ExchangeTimeLine::new(id, stop_id, line_1, line_2, duration, is_guaranteed),
    ))
}

pub fn parse(
    path: &Path,
    transport_types_pk_type_converter: &FxHashMap<String, i32>,
) -> HResult<ResourceStorage<ExchangeTimeLine>> {
    log::info!("Parsing UMSTEIGL...");
    let file = path.join("UMSTEIGL");
    let lines = read_lines(&file, 0)?;
    let auto_increment = AutoIncrement::new();
    let exchanges = lines
        .into_iter()
        .enumerate()
        .filter(|(_, line)| !line.trim().is_empty())
        .map(|(line_number, line)| {
            parse_line(&line, &auto_increment, transport_types_pk_type_converter).map_err(|e| {
                HrdfError::Parsing {
                    error: e,
                    file: String::from(file.to_string_lossy()),
                    line,
                    line_number,
                }
            })
        })
        .collect::<HResult<FxHashMap<_, _>>>()?;

    Ok(ResourceStorage::new(exchanges))
}

#[cfg(test)]
mod tests {
    // Note this useful idiom: importing names from outer (for mod tests) scope.
    use super::*;
    use crate::parsing::tests::get_json_values;
    use pretty_assertions::assert_eq;

    #[test]
    fn row_parser() {
        let line = "8301113 000011 S   *        * 007000 B   *        * 003  Luino (I)";
        let (
            _res,
            (
                stop_id,
                administration_1,
                transport_type_id_1,
                line_id_1,
                direction_1,
                administration_2,
                transport_type_id_2,
                line_id_2,
                direction_2,
                duration,
                is_guaranteed,
            ),
        ) = parse_exchange_line_row(line).unwrap();

        // "8301113 000011 S   *        * 007000 B   *        * 003  Luino (I)",
        assert_eq!(Some(8301113), stop_id);
        assert_eq!("000011", &administration_1);
        assert_eq!("S", &transport_type_id_1);
        assert_eq!("*", &line_id_1);
        assert_eq!("*", &direction_1);
        assert_eq!("007000", &administration_2);
        assert_eq!("B", &transport_type_id_2);
        assert_eq!("*", &line_id_2);
        assert_eq!("*", &direction_2);
        assert_eq!(3, duration);
        assert!(!is_guaranteed);

        let line = "1111135 sbg034 B   7339     H sbg034 TX  7341     H 000! Waldshut, Busbahnhof";
        let (
            _res,
            (
                stop_id,
                administration_1,
                transport_type_id_1,
                line_id_1,
                direction_1,
                administration_2,
                transport_type_id_2,
                line_id_2,
                direction_2,
                duration,
                is_guaranteed,
            ),
        ) = parse_exchange_line_row(line).unwrap();
        // Second row
        // "1111135 sbg034 B   7339     H sbg034 TX  7341     H 000! Waldshut, Busbahnhof"
        assert_eq!(Some(1111135), stop_id);
        assert_eq!("sbg034", &administration_1);
        assert_eq!("B", &transport_type_id_1);
        assert_eq!("7339", &line_id_1);
        assert_eq!("H", &direction_1);
        assert_eq!("sbg034", &administration_2);
        assert_eq!("TX", &transport_type_id_2);
        assert_eq!("7341", &line_id_2);
        assert_eq!("H", &direction_2);
        assert_eq!(0, duration);
        assert!(is_guaranteed);

        let line = "8509002 000011 RE  *        * 000065 S   12       * 008  Landquart";
        let (
            _res,
            (
                stop_id,
                administration_1,
                transport_type_id_1,
                line_id_1,
                direction_1,
                administration_2,
                transport_type_id_2,
                line_id_2,
                direction_2,
                duration,
                is_guaranteed,
            ),
        ) = parse_exchange_line_row(line).unwrap();
        // Third row
        // "8509002 000011 RE  *        * 000065 S   12       * 008  Landquart".to_string(),
        assert_eq!(Some(8509002), stop_id);
        assert_eq!("000011", &administration_1);
        assert_eq!("RE", &transport_type_id_1);
        assert_eq!("*", &line_id_1);
        assert_eq!("*", &direction_1);
        assert_eq!("000065", &administration_2);
        assert_eq!("S", &transport_type_id_2);
        assert_eq!("12", &line_id_2);
        assert_eq!("*", &direction_2);
        assert_eq!(8, duration);
        assert!(!is_guaranteed);

        let line =
            "8580522 003849 T   #0000482 * 003849 T   #0000488 * 003  Zürich, Escher-Wyss-Platz";
        let (
            _res,
            (
                stop_id,
                administration_1,
                transport_type_id_1,
                line_id_1,
                direction_1,
                administration_2,
                transport_type_id_2,
                line_id_2,
                direction_2,
                duration,
                is_guaranteed,
            ),
        ) = parse_exchange_line_row(line).unwrap();
        // Fourth row
        // "8580522 003849 T   #0000482 * 003849 T   #0000488 * 003  Zürich, Escher-Wyss-Platz"
        assert_eq!(Some(8580522), stop_id);
        assert_eq!("003849", &administration_1);
        assert_eq!("T", &transport_type_id_1);
        assert_eq!("#0000482", &line_id_1);
        assert_eq!("*", &direction_1);
        assert_eq!("003849", &administration_2);
        assert_eq!("T", &transport_type_id_2);
        assert_eq!("#0000488", &line_id_2);
        assert_eq!("*", &direction_2);
        assert_eq!(3, duration);
        assert!(!is_guaranteed);
    }

    #[test]
    fn multiline_parser() {
        let rows = vec![
            "8301113 000011 S   *        * 007000 B   *        * 003  Luino (I)".to_string(),
            "1111135 sbg034 B   7339     H sbg034 TX  7341     H 000! Waldshut, Busbahnhof"
                .to_string(),
            "8509002 000011 RE  *        * 000065 S   12       * 008  Landquart".to_string(),
            "8580522 003849 T   #0000482 * 003849 T   #0000488 * 003  Zürich, Escher-Wyss-Platz"
                .to_string(),
        ];

        // The transport_types_pk_type_converter is dummy and created just for testing purposes
        let mut transport_types_pk_type_converter: FxHashMap<String, i32> = FxHashMap::default();
        transport_types_pk_type_converter.insert("S".to_string(), 1);
        transport_types_pk_type_converter.insert("B".to_string(), 2);
        transport_types_pk_type_converter.insert("TX".to_string(), 3);
        transport_types_pk_type_converter.insert("RE".to_string(), 4);
        transport_types_pk_type_converter.insert("T".to_string(), 5);
        let auto_increment = AutoIncrement::new();
        let exchanges = rows
            .into_iter()
            .enumerate()
            .filter(|(_, line)| !line.trim().is_empty())
            .map(|(line_number, line)| {
                parse_line(&line, &auto_increment, &transport_types_pk_type_converter).map_err(
                    |e| HrdfError::Parsing {
                        error: e,
                        file: String::default(),
                        line,
                        line_number,
                    },
                )
            })
            .collect::<HResult<FxHashMap<_, _>>>()
            .unwrap();

        // Id 1
        let attribute = exchanges.get(&1).unwrap();
        let reference = r#"
             {
                 "id": 1,
                 "stop_id": 8301113,
                 "line_1": {
                    "administration": "000011",
                    "transport_type_id": 1,
                    "line_id": null,
                    "direction": null
                 },
                 "line_2": {
                    "administration": "007000",
                    "transport_type_id": 2,
                    "line_id": null,
                    "direction": null
                 },
                 "duration": 3,
                 "is_guaranteed": false
             }"#;
        let (attribute, reference) = get_json_values(attribute, reference).unwrap();
        assert_eq!(attribute, reference);
        // Id 2
        let attribute = exchanges.get(&2).unwrap();
        let reference = r#"
             {
                 "id": 2,
                 "stop_id": 1111135,
                 "line_1": {
                    "administration": "sbg034",
                    "transport_type_id": 2,
                    "line_id": "7339",
                    "direction": "Return"
                 },
                 "line_2": {
                    "administration": "sbg034",
                    "transport_type_id": 3,
                    "line_id": "7341",
                    "direction": "Return"
                 },
                 "duration": 0,
                 "is_guaranteed": true
             }"#;
        let (attribute, reference) = get_json_values(attribute, reference).unwrap();
        assert_eq!(attribute, reference);
        // Id 3
        let attribute = exchanges.get(&3).unwrap();
        let reference = r#"
             {
                 "id": 3,
                 "stop_id": 8509002,
                 "line_1": {
                    "administration": "000011",
                    "transport_type_id": 4,
                    "line_id": null,
                    "direction": null
                 },
                 "line_2": {
                    "administration": "000065",
                    "transport_type_id": 1,
                    "line_id": "12",
                    "direction": null
                 },
                 "duration": 8,
                 "is_guaranteed": false
             }"#;
        let (attribute, reference) = get_json_values(attribute, reference).unwrap();
        assert_eq!(attribute, reference);
        // Id 4
        let attribute = exchanges.get(&4).unwrap();
        let reference = r###"
             {
                 "id": 4,
                 "stop_id": 8580522,
                 "line_1": {
                    "administration": "003849",
                    "transport_type_id": 5,
                    "line_id": "#0000482",
                    "direction": null
                 },
                 "line_2": {
                    "administration": "003849",
                    "transport_type_id": 5,
                    "line_id": "#0000488",
                    "direction": null
                 },
                 "duration": 3,
                 "is_guaranteed": false
             }"###;
        let (attribute, reference) = get_json_values(attribute, reference).unwrap();
        assert_eq!(attribute, reference);
    }
}