properties_file_parser/
lib.rs1use crate::PropertyParseError::ParsingInputError;
2use pest::Parser;
3use pest_derive::Parser;
4use thiserror::Error;
5
6#[derive(Parser)]
7#[grammar = "./grammar.pest"]
8pub struct Grammar;
9
10#[derive(Debug)]
11pub struct Property {
12 pub key: String,
13 pub value: String,
14}
15
16impl PartialEq for Property {
17 fn eq(&self, other: &Self) -> bool {
18 self.key == other.key && self.value == other.value
19 }
20}
21
22#[derive(Error, Debug)]
23pub enum PropertyParseError{
24 #[error("Input is incorrect")]
25 ParsingInputError
26}
27
28pub fn parse_properties(unparsed: &str) -> Result<Vec<Property>, PropertyParseError>{
29 let parsed = Grammar::parse(Rule::file, unparsed);
30 let parsed_unwrapped;
31 match parsed {
32 Ok(_) => { parsed_unwrapped = parsed.unwrap().next()}
33 Err(_) => {return Err(ParsingInputError)}
34 }
35
36 let mut properties = vec![];
37
38 for property_pair in parsed_unwrapped.unwrap().into_inner() {
39 let mut inner = property_pair.into_inner();
40 properties.push(Property {key: inner.next().unwrap().as_str().to_string(),
41 value: inner.next().unwrap().as_str().to_string()});
42 }
43 Ok(properties)
44}
45
46pub fn parse_properties_as_string(unparsed: &str) -> Result<String, PropertyParseError>{
47 let parsed = parse_properties(unparsed);
48 let parsed_unwrapped;
49 match parsed {
50 Ok(_) => { parsed_unwrapped = parsed?}
51 Err(_) => {return Err(ParsingInputError)}
52 }
53 let mut res = String::new();
54 for i in 0..parsed_unwrapped.len(){
55 res += "key: ";
56 res += parsed_unwrapped[i].key.as_str();
57 res += ", value: ";
58 res += parsed_unwrapped[i].value.as_str();
59 if i < parsed_unwrapped.len() - 1 {
60 res += "\n";
61 }
62 }
63 Ok(res)
64}