From adeff06686a7cfa061467b8aa82e11614786f6ec Mon Sep 17 00:00:00 2001 From: hoang Date: Wed, 19 Jul 2023 17:56:33 +0700 Subject: [PATCH] Remove duplicate code in `toml` parser and add tests from toml.io --- src/toml.rs | 20 +++----------------- tests/toml.rs | 22 ++++++++++++++++++++++ 2 files changed, 25 insertions(+), 17 deletions(-) diff --git a/src/toml.rs b/src/toml.rs index 96f04b5..7184900 100644 --- a/src/toml.rs +++ b/src/toml.rs @@ -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 { @@ -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)), } diff --git a/tests/toml.rs b/tests/toml.rs index 7e2fda1..ab153b6 100644 --- a/tests/toml.rs +++ b/tests/toml.rs @@ -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()); +}