keymaps/key_repr/parsing/
mod.rs

1// keymaps - A rust crate which provides a standardized encoding for key codes
2//
3// Copyright (C) 2025 Benedikt Peetz <benedikt.peetz@b-peetz.de>
4// SPDX-License-Identifier: LGPL-3.0-or-later
5//
6// This file is part of the keymaps crate.
7//
8// You should have received a copy of the License along with this program.
9// If not, see <https://www.gnu.org/licenses/lgpl-3.0.txt>.
10
11use std::str::FromStr;
12
13use crate::error;
14
15use super::{Key, Keys};
16
17pub(crate) mod parser;
18
19impl FromStr for Key {
20    type Err = error::KeyParse;
21
22    fn from_str(s: &str) -> Result<Self, Self::Err> {
23        let mut parser = parser::Parser::new(s);
24        let first = parser.next_key()?;
25
26        if parser.is_empty() {
27            Ok(first)
28        } else {
29            Err(error::KeyParse::TooManyKeys(s.to_owned()))
30        }
31    }
32}
33
34impl Key {
35    /// Parse multiple keys from a string.
36    /// The string should be a concatenation of [`Key::to_string_repr`].
37    ///
38    /// This is comparable to [`Keys::from_str`], but avoids the construction of a [`Keys`] wrapper
39    /// struct.
40    ///
41    /// # Errors
42    /// This will return the underlying key parse error when parsing on of the keys fails.
43    pub fn parse_multiple(input: &str) -> Result<Vec<Self>, <Self as FromStr>::Err> {
44        let mut parser = parser::Parser::new(input);
45        let mut output = vec![];
46
47        while !parser.is_empty() {
48            output.push(parser.next_key()?);
49        }
50
51        Ok(output)
52    }
53}
54
55impl FromStr for Keys {
56    type Err = error::KeyParse;
57
58    fn from_str(s: &str) -> Result<Self, Self::Err> {
59        let mut parser = parser::Parser::new(s);
60        let mut output = vec![];
61
62        while !parser.is_empty() {
63            output.push(parser.next_key()?);
64        }
65
66        Ok(Keys(output))
67    }
68}