Skip to content

Commit

Permalink
Remove duplicate code in toml parser and add tests from toml.io
Browse files Browse the repository at this point in the history
  • Loading branch information
hoangdt84 authored Jul 19, 2023
1 parent 9968e9e commit adeff06
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 17 deletions.
20 changes: 3 additions & 17 deletions src/toml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,16 +187,7 @@ impl TomlParser {
// we should expect an ident or a string
let tok = self.next_tok(i)?;
match tok {
TomlTok::Str(key) => {
// a key
*local_scope = key;
let tok = self.next_tok(i)?;
if tok != TomlTok::BlockClose {
return Err(self.err_token(tok));
}
}
TomlTok::Ident(key) => {
// also a key
TomlTok::Str(key) | TomlTok::Ident(key) => {
*local_scope = key;
let tok = self.next_tok(i)?;
if tok != TomlTok::BlockClose {
Expand All @@ -222,13 +213,8 @@ impl TomlParser {
_ => return Err(self.err_token(tok)),
}
}
TomlTok::Str(key) => {
// a key
self.parse_key_value(&local_scope, key, i, out.out())?;
}
TomlTok::Ident(key) => {
// also a key
self.parse_key_value(&local_scope, key, i, out.out())?;
TomlTok::Str(key) | TomlTok::Ident(key) => {
self.parse_key_value(&local_scope, key, i, out.out())?
}
_ => return Err(self.err_token(tok)),
}
Expand Down
22 changes: 22 additions & 0 deletions tests/toml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,25 @@ hmm = "b"
assert_eq!(toml["other_array"].arr()[0]["hmm"].str(), "a");
assert_eq!(toml["other_array"].arr()[1]["hmm"].str(), "b");
}

#[test]
fn comment() {
let data = r#"
# This is a full-line comment
key = "value" # This is a comment at the end of a line
another = " # This is not a comment"
"#;

let toml = TomlParser::parse(data).unwrap();
assert_eq!(toml["key"].str(), "value");
assert_eq!(toml["another"].str(), " # This is not a comment");
}

#[test]
fn key_without_value() {
let data = r#"
key = # INVALID
"#;

assert!(TomlParser::parse(data).is_err());
}

0 comments on commit adeff06

Please sign in to comment.