controlmap_parser/
controlmap.rs1use crate::parser::{control_map_parser, Line};
2use crate::scan_code::ScanCodeError;
3use core::fmt;
4use core::slice::Iter;
5use nom::error::convert_error;
6use std::vec::IntoIter;
7
8#[derive(Debug, Clone, PartialEq)]
10#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
11pub struct ControlMap {
12 lines: Vec<Line>,
13}
14
15impl fmt::Display for ControlMap {
16 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17 for line in &self.lines {
18 write!(f, "{}", line)?;
19 }
20 Ok(())
21 }
22}
23
24pub type Result<T, E = ControlMapError> = core::result::Result<T, E>;
25
26impl ControlMap {
27 pub fn from_txt(txt: &str) -> Result<Self> {
29 let (remain, lines) = control_map_parser(txt).map_err(|err| {
30 let err = match err {
31 nom::Err::Incomplete(_) => "Incomplete error".into(),
32 nom::Err::Error(err) => convert_error(txt, err),
33 nom::Err::Failure(err) => convert_error(txt, err),
34 };
35
36 ControlMapError::ParseError(err)
37 })?;
38
39 match remain.is_empty() {
40 true => Ok(Self { lines }),
41 false => Err(ControlMapError::Incomplete(remain.into())),
42 }
43 }
44
45 pub fn iter(&self) -> Iter<'_, Line> {
49 self.lines.iter()
50 }
51}
52
53impl IntoIterator for ControlMap {
54 type Item = Line;
55 type IntoIter = IntoIter<Self::Item>;
56
57 fn into_iter(self) -> Self::IntoIter {
58 self.lines.into_iter()
59 }
60}
61
62#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
63#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
64pub enum ControlMapError {
65 #[error("ParseError. Reason:\n{0}")]
66 ParseError(String),
67 #[error("Incomplete parse. Remain:\n{0}")]
68 Incomplete(String),
69 #[error(transparent)]
70 ScanCodeError(#[from] ScanCodeError),
71}