naviz_import/
lib.rs

1use std::str::Utf8Error;
2
3use naviz_parser::input::concrete::Instructions;
4
5pub mod mqt;
6pub mod separated_display;
7
8/// The available import formats
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
11pub enum ImportFormat {
12    /// [mqt::na]
13    MqtNa,
14}
15
16/// List of all import-formats (all entries of [ImportFormat]).
17pub static IMPORT_FORMATS: [ImportFormat; 1] = [ImportFormat::MqtNa];
18
19/// The options for the different import formats
20#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
21pub enum ImportOptions {
22    /// [mqt::na]
23    MqtNa(mqt::na::convert::ConvertOptions<'static>),
24}
25
26/// An error that can occur during import
27#[derive(Debug, Clone, PartialEq)]
28pub enum ImportError {
29    /// Something was not valid UTF-8
30    InvalidUtf8(Utf8Error),
31    /// An error occurred while parsing [mqt::na]
32    MqtNqParse(mqt::na::format::ParseErrorInner),
33    /// An error occurred while converting [mqt::na]
34    MqtNqConvert(mqt::na::convert::OperationConversionError),
35}
36
37impl ImportFormat {
38    /// A human-readable name of this [ImportFormat]
39    pub fn name(&self) -> &'static str {
40        match self {
41            Self::MqtNa => "mqt na",
42        }
43    }
44
45    /// A list of file-extensions commonly used by this [ImportFormat]
46    pub fn file_extensions(&self) -> &'static [&'static str] {
47        match self {
48            Self::MqtNa => &["na"],
49        }
50    }
51}
52
53impl From<ImportFormat> for ImportOptions {
54    fn from(value: ImportFormat) -> Self {
55        match value {
56            ImportFormat::MqtNa => ImportOptions::MqtNa(Default::default()),
57        }
58    }
59}
60
61impl From<&ImportOptions> for ImportFormat {
62    fn from(value: &ImportOptions) -> Self {
63        match value {
64            &ImportOptions::MqtNa(_) => ImportFormat::MqtNa,
65        }
66    }
67}
68
69impl ImportOptions {
70    /// Imports the `data` using the options in `self`
71    pub fn import(self, data: &[u8]) -> Result<Instructions, ImportError> {
72        match self {
73            Self::MqtNa(options) => mqt::na::convert::convert(
74                &mqt::na::format::parse(
75                    std::str::from_utf8(data).map_err(ImportError::InvalidUtf8)?,
76                )
77                .map_err(|e| e.into_inner())
78                .map_err(ImportError::MqtNqParse)?,
79                options,
80            )
81            .map_err(ImportError::MqtNqConvert),
82        }
83    }
84}