keymaps/key_repr/parsing/
mod.rs

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
// keymaps - A rust crate which provides a standardized encoding for key codes
//
// Copyright (C) 2025 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// This file is part of the keymaps crate.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/lgpl-3.0.txt>.

use std::str::FromStr;

use crate::error;

use super::{Key, Keys};

pub(crate) mod parser;

impl FromStr for Key {
    type Err = error::KeyParse;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut parser = parser::Parser::new(s);
        let first = parser.next_key()?;

        if parser.is_empty() {
            Ok(first)
        } else {
            Err(error::KeyParse::TooManyKeys(s.to_owned()))
        }
    }
}

impl Key {
    /// Parse multiple keys from a string.
    /// The string should be a concatenation of [`Key::to_string_repr`].
    ///
    /// This is comparable to [`Keys::from_str`], but avoids the construction of a [`Keys`] wrapper
    /// struct.
    ///
    /// # Errors
    /// This will return the underlying key parse error when parsing on of the keys fails.
    pub fn parse_multiple(input: &str) -> Result<Vec<Self>, <Self as FromStr>::Err> {
        let mut parser = parser::Parser::new(input);
        let mut output = vec![];

        while !parser.is_empty() {
            output.push(parser.next_key()?);
        }

        Ok(output)
    }
}

impl FromStr for Keys {
    type Err = error::KeyParse;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut parser = parser::Parser::new(s);
        let mut output = vec![];

        while !parser.is_empty() {
            output.push(parser.next_key()?);
        }

        Ok(Keys(output))
    }
}