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
// -----------------------------------------------------------------------------------------------------
//                                      gs-rs - Graph SLAM in Rust
// -----------------------------------------------------------------------------------------------------
//
// SPDX-FileCopyrightText:      © 2020 Samuel Valenzuela (samuel.valenzuela@tngtech.com)
//                              © 2020 Florian Rohm (florian.rohm@tngtech.com)
//                              © 2020 Daniel Pape (daniel.pape@tngtech.com)
// SPDX-License-Identifier:     MIT OR Apache-2.0
//
// This product includes software developed at TNG Technology Consulting GmbH (https://www.tngtech.com/).
//

//! Conversion between factor graph structures and files.

use crate::factor_graph::FactorGraph;
use crate::parser::model::FactorGraphModel;
use std::fs;

pub mod g2o;
pub mod json;
pub mod model;

/// Trait to be used by all parsers with the basic file parsing and composition functionality.
pub trait Parser {
    /// Tries to parse a file at the given path to the internal factor graph representation.
    fn parse_file(file_path: &str) -> Result<FactorGraph, String> {
        match Self::parse_file_to_model(file_path) {
            Ok(model) => Ok(model.into()),
            Err(s) => Err(s),
        }
    }

    /// Tries to parse a file at the given path to the factor graph model used in the context with files.
    fn parse_file_to_model(file_path: &str) -> Result<FactorGraphModel, String> {
        let file_string = match fs::read_to_string(file_path) {
            Ok(s) => s,
            Err(_e) => return Err(format!("File could not be parsed: {}", file_path)),
        };
        Self::parse_string_to_model(&file_string)
    }

    /// Tries to parse a string to the factor graph model used in the context with files.
    fn parse_string_to_model(s: &str) -> Result<FactorGraphModel, String>;

    /// Tries to compose a file at the given path containing the serialized factor graph.
    fn compose_file(factor_graph: &FactorGraph, file_path: &str) -> Result<(), String> {
        Self::compose_model_to_file(factor_graph.into(), file_path)
    }

    /// Tries to compose a file at the given path containing the factor graph model's serialization.
    fn compose_model_to_file(model: FactorGraphModel, file_path: &str) -> Result<(), String> {
        let s = Self::compose_model_to_string(model)?;
        fs::write(file_path, s).map_err(|_| format!("File could not be written to: {}", file_path))
    }

    /// Tries to compose a string containing the factor graph model's serialization.
    fn compose_model_to_string(model: FactorGraphModel) -> Result<String, String>;
}