openscenario-rs 0.3.0

Rust library for parsing and manipulating OpenSCENARIO files
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
//! XML parsing implementation using quick-xml and serde
//!
//! This module provides efficient XML parsing and serialization for OpenSCENARIO documents
//! with comprehensive error handling and validation capabilities.
//!
//! # Features
//!
//! - **High-performance parsing** using quick-xml with zero-copy deserialization
//! - **Comprehensive validation** with detailed error reporting and suggestions
//! - **Catalog support** for reusable component libraries
//! - **UTF-8 BOM handling** for cross-platform compatibility
//! - **Pretty-printed output** with configurable formatting
//!
//! # Basic Usage
//!
//! ## Parsing Scenarios
//!
//! ```rust,no_run
//! use openscenario_rs::{parse_from_file, parse_from_str};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Parse from file with automatic error context
//! let scenario = parse_from_file("my_scenario.xosc")?;
//! println!("Scenario author: {}", scenario.file_header.author);
//!
//! // Parse from XML string
//! let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
//! <OpenSCENARIO>
//!   <FileHeader revMajor="1" revMinor="3" date="2024-01-01T00:00:00"
//!               author="Example" description="Test scenario"/>
//!   <ScenarioDefinition>
//!     <!-- scenario content -->
//!   </ScenarioDefinition>
//! </OpenSCENARIO>"#;
//! let scenario = parse_from_str(xml)?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Serialization
//!
//! ```rust,no_run
//! use openscenario_rs::{serialize_to_string, serialize_to_file};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let scenario = openscenario_rs::parse_from_file("scenario.xosc")?;
//! // Serialize to formatted XML string
//! let xml_output = serialize_to_string(&scenario)?;
//! println!("{}", xml_output);
//!
//! // Write directly to file
//! serialize_to_file(&scenario, "output.xosc")?;
//! # Ok(())
//! # }
//! ```
//!
//! # Catalog File Operations
//!
//! ```rust,no_run
//! use openscenario_rs::parser::xml::{
//!     parse_catalog_from_file, serialize_catalog_to_file,
//!     parse_catalog_from_str_validated
//! };
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Parse vehicle catalog
//! let catalog = parse_catalog_from_file("vehicles.xosc")?;
//!
//! // Validate catalog structure
//! let catalog_xml = openscenario_rs::serialize_catalog_to_string(&catalog)?;
//! let validated_catalog = parse_catalog_from_str_validated(&catalog_xml)?;
//!
//! // Export modified catalog
//! serialize_catalog_to_file(&catalog, "updated_vehicles.xosc")?;
//! # Ok(())
//! # }
//! ```
//!
//! # Error Handling
//!
//! All parsing functions return `Result<T>` with detailed error context:
//!
//! ```rust,no_run
//! # use openscenario_rs::parser::xml::parse_from_file;
//! match parse_from_file("scenario.xosc") {
//!     Ok(scenario) => {
//!         // Process valid scenario
//!         println!("Loaded scenario with {} entities",
//!                  scenario.entities.as_ref().map_or(0, |e| e.scenario_objects.len()));
//!     }
//!     Err(e) => {
//!         eprintln!("Parse error: {}", e);
//!         // Error includes file path and specific parsing context
//!     }
//! }
//! ```
//!
//! # Performance Notes
//!
//! - Use `parse_from_file` for fastest parsing without validation
//! - Use `parse_from_file_validated` when you need structure validation
//! - For very large files (>50MB), consider chunked processing
//! - Validation adds ~10-15% overhead but catches malformed XML early

use crate::error::{Error, Result};
use crate::types::catalogs::files::CatalogFile;
use crate::types::scenario::storyboard::OpenScenario;
use markup_fmt::{config::FormatOptions, format_text, Language};
use std::fs;
use std::path::Path;

/// Maximum file size for parsing (100 MB)
const MAX_FILE_SIZE: u64 = 100 * 1024 * 1024;

/// Remove BOM (Byte Order Mark) if present
fn remove_bom(content: &str) -> &str {
    // UTF-8 BOM: EF BB BF (represented as \u{FEFF} in decoded string)
    if content.starts_with('\u{FEFF}') {
        // The character is 3 bytes in UTF-8, but as a char it's 1 character
        &content['\u{FEFF}'.len_utf8()..]
    } else {
        content
    }
}

/// Internal helper to parse OpenSCENARIO from file
fn parse_from_file_internal<P: AsRef<Path>>(path: P, validate_xml: bool) -> Result<OpenScenario> {
    let metadata = fs::metadata(&path).map_err(Error::from).map_err(|e| {
        e.with_context(&format!(
            "Failed to read file metadata: {}",
            path.as_ref().display()
        ))
    })?;

    if metadata.len() > MAX_FILE_SIZE {
        return Err(Error::out_of_range(
            "file_size",
            &metadata.len().to_string(),
            "0",
            &MAX_FILE_SIZE.to_string(),
        ));
    }

    let xml_content = fs::read_to_string(&path)
        .map_err(Error::from)
        .map_err(|e| {
            e.with_context(&format!("Failed to read file: {}", path.as_ref().display()))
        })?;

    let cleaned_content = remove_bom(&xml_content);

    if validate_xml {
        validate_xml_structure(cleaned_content).map_err(|e| {
            e.with_context(&format!(
                "XML validation failed for file: {}",
                path.as_ref().display()
            ))
        })?;
    }

    parse_from_str(cleaned_content).map_err(|e| {
        e.with_context(&format!(
            "Failed to parse file: {}",
            path.as_ref().display()
        ))
    })
}

/// Internal helper to parse catalog from file
fn parse_catalog_from_file_internal<P: AsRef<Path>>(
    path: P,
    validate_xml: bool,
) -> Result<CatalogFile> {
    let metadata = fs::metadata(&path).map_err(Error::from).map_err(|e| {
        e.with_context(&format!(
            "Failed to read catalog file metadata: {}",
            path.as_ref().display()
        ))
    })?;

    if metadata.len() > MAX_FILE_SIZE {
        return Err(Error::out_of_range(
            "file_size",
            &metadata.len().to_string(),
            "0",
            &MAX_FILE_SIZE.to_string(),
        ));
    }

    let xml_content = fs::read_to_string(&path)
        .map_err(Error::from)
        .map_err(|e| {
            e.with_context(&format!(
                "Failed to read catalog file: {}",
                path.as_ref().display()
            ))
        })?;

    let cleaned_content = remove_bom(&xml_content);

    if validate_xml {
        validate_catalog_xml_structure(cleaned_content).map_err(|e| {
            e.with_context(&format!(
                "XML validation failed for catalog file: {}",
                path.as_ref().display()
            ))
        })?;
    }

    parse_catalog_from_str(cleaned_content).map_err(|e| {
        e.with_context(&format!(
            "Failed to parse catalog file: {}",
            path.as_ref().display()
        ))
    })
}

/// Parse an OpenSCENARIO document from a string
///
/// This function uses quick-xml's serde integration to deserialize
/// XML into our Rust type system.
#[must_use = "parsing result should be handled"]
pub fn parse_from_str(xml: &str) -> Result<OpenScenario> {
    quick_xml::de::from_str(xml)
        .map_err(Error::from)
        .map_err(|e| e.with_context("Failed to parse OpenSCENARIO XML"))
}

/// Parse an OpenSCENARIO document from a file
///
/// Reads file into memory and then parses it as a string.
#[must_use = "parsing result should be handled"]
pub fn parse_from_file<P: AsRef<Path>>(path: P) -> Result<OpenScenario> {
    parse_from_file_internal(path, false)
}

/// Serialize an OpenSCENARIO document to XML string
///
/// This function uses quick-xml's serde integration to serialize
/// our Rust types back to XML format.
#[must_use = "serialization result should be handled"]
pub fn serialize_to_string(scenario: &OpenScenario) -> Result<String> {
    let mut xml = String::from(r#"<?xml version="1.0" encoding="UTF-8"?>"#);
    xml.push('\n');

    let serialized = quick_xml::se::to_string(scenario)
        .map_err(Error::XmlSerializeError)
        .map_err(|e| e.with_context("Failed to serialize OpenSCENARIO to XML"))?;
    let s = format_text(
        &serialized,
        Language::Xml,
        &FormatOptions::default(),
        |serialized, _| Ok::<_, std::convert::Infallible>(serialized.into()),
    )
    .unwrap();
    xml.push_str(&s);
    Ok(xml)
}

/// Serialize an OpenSCENARIO document to a file
///
/// Serializes the scenario to XML and writes it to the specified file.
#[must_use = "serialization result should be handled"]
pub fn serialize_to_file<P: AsRef<Path>>(scenario: &OpenScenario, path: P) -> Result<()> {
    let xml = serialize_to_string(scenario)?;

    fs::write(&path, xml).map_err(Error::from).map_err(|e| {
        e.with_context(&format!(
            "Failed to write file: {}",
            path.as_ref().display()
        ))
    })
}

/// Validate XML structure before parsing
///
/// This function performs basic XML structure validation to provide
/// better error messages for malformed documents.
pub fn validate_xml_structure(xml: &str) -> Result<()> {
    // Basic validation - check for XML declaration and root element
    let trimmed = xml.trim();

    if trimmed.is_empty() {
        return Err(Error::invalid_xml("XML document is empty"));
    }

    if !trimmed.starts_with("<?xml") && !trimmed.starts_with('<') {
        return Err(Error::invalid_xml(
            "XML document must start with XML declaration or root element",
        ));
    }

    if !trimmed.contains("OpenSCENARIO") {
        return Err(Error::invalid_xml(
            "Document does not appear to contain OpenSCENARIO root element",
        ));
    }

    Ok(())
}

/// Parse with validation
///
/// Validates the XML structure before attempting to parse it.
#[must_use = "parsing result should be handled"]
pub fn parse_from_str_validated(xml: &str) -> Result<OpenScenario> {
    validate_xml_structure(xml)?;
    parse_from_str(xml)
}

/// Parse file with validation
///
/// Validates the XML structure before attempting to parse it.
#[must_use = "parsing result should be handled"]
pub fn parse_from_file_validated<P: AsRef<Path>>(path: P) -> Result<OpenScenario> {
    parse_from_file_internal(path, true)
}

// Catalog parsing functions

/// Parse a catalog file from XML string
///
/// This function uses quick-xml's serde integration to deserialize
/// catalog XML into our catalog file structure.
#[must_use = "parsing result should be handled"]
pub fn parse_catalog_from_str(xml: &str) -> Result<CatalogFile> {
    quick_xml::de::from_str(xml)
        .map_err(Error::from)
        .map_err(|e| e.with_context("Failed to parse catalog XML"))
}

/// Parse a catalog file from a file path
///
/// Reads the catalog file into memory and then parses it as a string.
#[must_use = "parsing result should be handled"]
pub fn parse_catalog_from_file<P: AsRef<Path>>(path: P) -> Result<CatalogFile> {
    parse_catalog_from_file_internal(path, false)
}

/// Validate catalog XML structure before parsing
///
/// This function performs basic XML structure validation specific to catalog files.
pub fn validate_catalog_xml_structure(xml: &str) -> Result<()> {
    let trimmed = xml.trim();

    if trimmed.is_empty() {
        return Err(Error::invalid_xml("Catalog XML document is empty"));
    }

    if !trimmed.starts_with("<?xml") && !trimmed.starts_with('<') {
        return Err(Error::invalid_xml(
            "Catalog XML document must start with XML declaration or root element",
        ));
    }

    if !trimmed.contains("OpenSCENARIO") {
        return Err(Error::invalid_xml(
            "Document does not appear to contain OpenSCENARIO root element",
        ));
    }

    if !trimmed.contains("Catalog") {
        return Err(Error::invalid_xml(
            "Document does not appear to contain Catalog element",
        ));
    }

    Ok(())
}

/// Parse catalog with validation
///
/// Validates the XML structure before attempting to parse it.
#[must_use = "parsing result should be handled"]
pub fn parse_catalog_from_str_validated(xml: &str) -> Result<CatalogFile> {
    validate_catalog_xml_structure(xml)?;
    parse_catalog_from_str(xml)
}

/// Parse catalog file with validation
///
/// Validates the XML structure before attempting to parse it.
#[must_use = "parsing result should be handled"]
pub fn parse_catalog_from_file_validated<P: AsRef<Path>>(path: P) -> Result<CatalogFile> {
    parse_catalog_from_file_internal(path, true)
}

/// Serialize a catalog file to XML string
///
/// This function uses quick-xml's serde integration to serialize
/// our catalog types back to XML format.
pub fn serialize_catalog_to_string(catalog: &CatalogFile) -> Result<String> {
    let mut xml = String::from(r#"<?xml version="1.0" encoding="UTF-8"?>"#);
    xml.push('\n');

    let serialized = quick_xml::se::to_string(catalog)
        .map_err(Error::XmlSerializeError)
        .map_err(|e| e.with_context("Failed to serialize catalog to XML"))?;

    xml.push_str(&serialized);
    Ok(xml)
}

/// Serialize a catalog file to a file path
///
/// Serializes the catalog to XML and writes it to the specified file.
pub fn serialize_catalog_to_file<P: AsRef<Path>>(catalog: &CatalogFile, path: P) -> Result<()> {
    let xml = serialize_catalog_to_string(catalog)?;

    fs::write(&path, xml).map_err(Error::from).map_err(|e| {
        e.with_context(&format!(
            "Failed to write catalog file: {}",
            path.as_ref().display()
        ))
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_validate_xml_structure() {
        // Valid XML
        assert!(
            validate_xml_structure(r#"<?xml version="1.0"?><OpenSCENARIO></OpenSCENARIO>"#).is_ok()
        );

        // Missing XML declaration is OK
        assert!(validate_xml_structure(r#"<OpenSCENARIO></OpenSCENARIO>"#).is_ok());

        // Empty XML should fail
        assert!(validate_xml_structure("").is_err());
        assert!(validate_xml_structure("   ").is_err());

        // Non-XML content should fail
        assert!(validate_xml_structure("This is not XML").is_err());

        // Missing OpenSCENARIO root should fail
        assert!(validate_xml_structure(r#"<SomeOtherRoot></SomeOtherRoot>"#).is_err());
    }

    #[test]
    fn test_validate_catalog_xml_structure() {
        // Valid catalog XML structure
        let valid_xml = r#"<?xml version="1.0"?>
        <OpenSCENARIO>
            <FileHeader revMajor="1" revMinor="3" date="2024-01-01T00:00:00" author="Test" description="Test"/>
            <Catalog name="test">
            </Catalog>
        </OpenSCENARIO>"#;

        assert!(validate_catalog_xml_structure(valid_xml).is_ok());

        // Invalid - no Catalog element
        let invalid_xml = r#"<?xml version="1.0"?><OpenSCENARIO><FileHeader/></OpenSCENARIO>"#;
        assert!(validate_catalog_xml_structure(invalid_xml).is_err());

        // Invalid - empty
        assert!(validate_catalog_xml_structure("").is_err());
    }

    #[test]
    fn test_catalog_serialization_roundtrip() {
        let catalog = CatalogFile::default();

        let xml = serialize_catalog_to_string(&catalog).unwrap();
        assert!(xml.contains("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
        assert!(xml.contains("OpenSCENARIO"));
        assert!(xml.contains("Catalog"));
    }
}