kconfig_parser/string.rs
1/*
2 Cargo KConfig - KConfig parser
3 Copyright (C) 2022  Sjoerd van Leent
4
5--------------------------------------------------------------------------------
6
7Copyright Notice: Apache
8
9Licensed under the Apache License, Version 2.0 (the "License"); you may not use
10this file except in compliance with the License. You may obtain a copy of the
11License at
12
13   https://www.apache.org/licenses/LICENSE-2.0
14
15Unless required by applicable law or agreed to in writing, software distributed
16under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
17CONDITIONS OF ANY KIND, either express or implied. See the License for the
18specific language governing permissions and limitations under the License.
19
20--------------------------------------------------------------------------------
21
22Copyright Notice: GPLv2
23
24This program is free software: you can redistribute it and/or modify
25it under the terms of the GNU General Public License as published by
26the Free Software Foundation, either version 2 of the License, or
27(at your option) any later version.
28
29This program is distributed in the hope that it will be useful,
30but WITHOUT ANY WARRANTY; without even the implied warranty of
31MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
32GNU General Public License for more details.
33
34You should have received a copy of the GNU General Public License
35along with this program.  If not, see <https://www.gnu.org/licenses/>.
36
37--------------------------------------------------------------------------------
38
39Copyright Notice: MIT
40
41Permission is hereby granted, free of charge, to any person obtaining a copy of
42this software and associated documentation files (the “Software”), to deal in
43the Software without restriction, including without limitation the rights to
44use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
45the Software, and to permit persons to whom the Software is furnished to do so,
46subject to the following conditions:
47
48The above copyright notice and this permission notice shall be included in all
49copies or substantial portions of the Software.
50
51THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
52IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
53FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
54COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
55IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
56CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
57*/
58
59//! Additional String helper functions
60
61/// Escapes a given value into an escaped string
62pub fn escape(value: &str) -> String {
63    format!(
64        "\"{}\"",
65        value
66            .chars()
67            .flat_map(|c| match c {
68                '"' => vec!['\\', '"'],
69                '\n' => vec!['\\', 'n'],
70                '\r' => vec!['\\', 'r'],
71                '\t' => vec!['\\', 't'],
72                '\\' => vec!['\\', '\\'],
73                _ => vec![c],
74            })
75            .collect::<String>()
76    )
77}
78
79/// Parses a string value and removes escapes
80pub fn parse(value: &str) -> Result<String, String> {
81    let mut chars = value.chars();
82    // Trim the left and right double quotes
83    if value.len() < 2 || chars.next() != Some('\"') || chars.last() != Some('\"') {
84        return Err(format!(
85            "Could not find starting or ending double quote in: {}",
86            value
87        ));
88    }
89    let basic = value[1..value.len() - 1].chars();
90
91    // Build the string into result
92    let mut result: String = "".to_string();
93
94    // If the state is Normal, then it is a normal character, which is appended
95    // into result, if the state is Escape, then an escape character (\) has been
96    // found prior to the current character, and the character needs unescaping.
97    enum State {
98        Normal,
99        Escaped,
100    }
101    let mut state = State::Normal;
102    for c in basic {
103        match state {
104            State::Normal => match c {
105                '\\' => state = State::Escaped,
106                _ => result += &format!("{}", c),
107            },
108            State::Escaped => {
109                match c {
110                    '"' => result += "\"",
111                    'n' => result += "\n",
112                    'r' => result += "\r",
113                    't' => result += "\t",
114                    '\\' => result += "\\",
115                    _ => return Err(format!("Expected escape symbol, found: {}", c)),
116                };
117                state = State::Normal;
118            }
119        }
120    }
121    // If the state remained into escaped, it means that the last character has not
122    // been properly closed.
123    if let State::Escaped = state {
124        return Err("Expected input to be closed, found escape token: \\".to_string());
125    }
126    Ok(result)
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    #[test]
134    fn test_escape_and_parse_string() {
135        let escaped = escape("foo\"\n\r\t\\bar");
136        let parsed = parse(&escaped).unwrap();
137
138        assert_eq!("foo\"\n\r\t\\bar", parsed);
139        assert_eq!("\"foo\\\"\\n\\r\\t\\\\bar\"", escaped);
140    }
141
142    #[test]
143    fn test_wrong_escape() {
144        assert_eq!(true, parse("\"\\w\"").is_err());
145    }
146
147    #[test]
148    fn test_attempt_parse_without_opening_quote() {
149        assert_eq!(true, parse("a\"").is_err());
150    }
151
152    #[test]
153    fn test_attempt_parse_without_closing_quote() {
154        assert_eq!(true, parse("\"a").is_err());
155    }
156
157    #[test]
158    fn test_did_not_end_escape() {
159        assert_eq!(true, parse("\"\\\"").is_err());
160    }
161}