diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..84f5c4d --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +/target +Cargo.lock +tarpaulin-report.html +.idea +.vscode \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..4dc29fd --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "questdb-confstr" +version = "0.1.0" +edition = "2021" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 16f580d..f41784c 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,58 @@ # `questdb-confstr` +## Format + +Parser for a configuration string format used by QuestDB clients. + +The format is as follows: + +```plain +service::key1=value1;key2=value2;key3=value3; +``` + +A few rules: +* The last semicolon is mandatory. +* Service name and keys are case-insensitive. +* Values are case-sensitive. +* A semicolon can't appear as a key. +* If a semicolon `;` appears in a value, escaped it as a double semicolon `;;`. + +## Grammar + +```plain +conf_str ::= service "::" params | service +service ::= identifier +params ::= param (";" param)* ";" +param ::= key "=" value +key ::= identifier +value ::= { value_char } + +identifier ::= alpha { alphanumeric } +alpha ::= "a".."z" | "A".."Z" +alphanumeric ::= "a".."z" | "A".."Z" | "0".."9" +value_char ::= non_semicolon_char | escaped_semicolon +escaped_semicolon ::= ";;" +non_semicolon_char ::= ? any character except ';' ? +``` + +## Usage + +### Add dependency to `Cargo.toml` + +```shell +cargo add questdb-confstr +``` + +### Usage + +Use the `parse_conf_str` function to parse into a `ConfStr` struct. + +You can then access the service name as `&str` and parameters as a `&HashMap`. + +### Where we use it + +We use this config parsing format in our [Rust, C, C++](https://github.com/questdb/c-questdb-client) and +[Python](https://github.com/questdb/py-questdb-client) clients. + +We also use it to configure object stores for +[database replication](https://questdb.io/docs/operations/replication/#core-replication-settings). diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..f86adcb --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,291 @@ +/******************************************************************************* + * ___ _ ____ ____ + * / _ \ _ _ ___ ___| |_| _ \| __ ) + * | | | | | | |/ _ \/ __| __| | | | _ \ + * | |_| | |_| | __/\__ \ |_| |_| | |_) | + * \__\_\\__,_|\___||___/\__|____/|____/ + * + * Copyright (c) 2014-2019 Appsicle + * Copyright (c) 2019-2024 QuestDB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#![doc = include_str!("../README.md")] + +use crate::peekable2::{Peekable2, Peekable2Ext}; +use std::collections::HashMap; +use std::fmt; +use std::fmt::{Debug, Display, Formatter}; +use std::str::CharIndices; + +mod peekable2; + +/// Parameter keys are ascii lowercase strings. +pub type Key = String; + +/// Parameter values are strings. +pub type Value = String; + +/// Parameters are stored in a `Vec` of `(Key, Value)` pairs. +/// Keys are always lowercase. +pub type Params = HashMap; + +/// Parsed configuration string. +/// +/// The parameters are stored in a `Vec` of `(Key, Value)` pairs. +pub struct ConfStr { + service: String, + params: Params, +} + +impl Debug for ConfStr { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + // Params are hidden from debug output in case they contain sensitive information. + write!(f, "ConfStr {{ service: {:?}, .. }}", self.service) + } +} + +impl ConfStr { + /// Create a new configuration string object. + pub fn new(service: String, params: Params) -> Self { + ConfStr { service, params } + } + + /// Access the service name. + pub fn service(&self) -> &str { + &self.service + } + + /// Access the parameters. + pub fn params(&self) -> &Params { + &self.params + } + + /// Get a parameter by case-insensitive key. + pub fn get(&self, key: &str) -> Option<&str> { + self.params.get(key).map(|s| s.as_str()) + } +} + +/// Byte position in the input string where the parsing error occurred. +pub type Position = usize; + +/// The type of parsing error. +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum ErrorKind { + ExpectedIdentifierNot(char), + MustBeAlphanumeric(char), + ExpectedIdentifierNotEmpty, + BadSeparator((char, char)), + IncompleteKeyValue, + MissingTrailingSemicolon, + DuplicateKey(String), +} + +impl<'a> PartialEq<&'a ErrorKind> for ErrorKind { + fn eq(&self, other: &&'a ErrorKind) -> bool { + self == *other + } +} + +impl<'a> PartialEq for &'a ErrorKind { + fn eq(&self, other: &ErrorKind) -> bool { + *self == other + } +} + +impl Display for ErrorKind { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + // Ensure no values are leaked in error messages. + match self { + ErrorKind::ExpectedIdentifierNot(c) => { + write!( + f, + "expected identifier to start with ascii letter, not {:?}", + c + ) + } + ErrorKind::MustBeAlphanumeric(c) => write!(f, "must be alphanumeric, not {:?}", c), + ErrorKind::ExpectedIdentifierNotEmpty => { + write!(f, "expected identifier, not an empty string") + } + ErrorKind::BadSeparator((e, c)) => { + write!(f, "bad separator, expected {:?} got {:?}", e, c) + } + ErrorKind::IncompleteKeyValue => { + write!(f, "incomplete key-value pair before end of input") + } + ErrorKind::MissingTrailingSemicolon => write!(f, "missing trailing semicolon"), + ErrorKind::DuplicateKey(s) => write!(f, "duplicate key {:?}", s), + } + } +} + +/// The parsing error. +#[derive(Debug)] +pub struct ParsingError { + kind: ErrorKind, + position: usize, +} + +impl ParsingError { + /// Access the byte position in the input string where the parsing error occurred. + pub fn position(&self) -> usize { + self.position + } + + /// Access the type of parsing error. + pub fn kind(&self) -> &ErrorKind { + &self.kind + } +} + +fn parse_err(kind: ErrorKind, position: Position) -> ParsingError { + ParsingError { kind, position } +} + +impl Display for ParsingError { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "{} at position {}", self.kind, self.position) + } +} + +impl std::error::Error for ParsingError {} + +fn parse_ident( + iter: &mut Peekable2, + next_pos: &mut Position, +) -> Result { + let mut token = String::new(); + while let Some((pos, c)) = iter.peek0() { + *next_pos = *pos; + let take = if token.is_empty() { + c.is_ascii_alphabetic() + } else { + c.is_ascii_alphanumeric() + }; + if !take { + if token.is_empty() { + return Err(parse_err(ErrorKind::ExpectedIdentifierNot(*c), *next_pos)); + } else if !c.is_ascii() || matches!(c, '\0'..=' ') { + return Err(parse_err(ErrorKind::MustBeAlphanumeric(*c), *next_pos)); + } + break; + } + token.push(c.to_ascii_lowercase()); + iter.next(); + } + + if token.is_empty() { + return Err(parse_err(ErrorKind::ExpectedIdentifierNotEmpty, *next_pos)); + } + + Ok(token) +} + +fn parse_value( + iter: &mut Peekable2, + next_pos: &mut Position, + input_len: usize, +) -> Result { + let mut value = String::new(); + loop { + let c1 = iter.peek0().cloned(); + let c2 = iter.peek1().cloned(); + if let Some((p, _)) = c1 { + *next_pos = p; + } + match (c1, c2) { + (Some((_, ';')), Some((_, ';'))) => { + let _ = iter.next(); + let _ = iter.next(); + value.push(';'); + } + (Some((_, ';')), _) => break, + (Some((_, c)), _) => { + value.push(c); + let _ = iter.next(); + } + (None, _) => return Err(parse_err(ErrorKind::MissingTrailingSemicolon, input_len)), + } + } + Ok(value) +} + +fn parse_double_colon( + iter: &mut Peekable2, + next_pos: &mut Position, +) -> Result { + let c1 = iter.next(); + let c2 = iter.next(); + match (c1, c2) { + (Some((_, ':')), Some((_, ':'))) => { + *next_pos += 2; + Ok(true) + } + (None, None) => Ok(false), + (Some((_, ':')), Some((p, c))) => Err(parse_err(ErrorKind::BadSeparator((':', c)), p)), + (Some((p, c)), _) => Err(parse_err(ErrorKind::BadSeparator((':', c)), p)), + (None, _) => unreachable!("peekable2 guarantees that the second item is always None"), + } +} + +fn parse_params( + iter: &mut Peekable2, + next_pos: &mut Position, + input_len: usize, +) -> Result { + let mut params = Params::new(); + while let Some((p, _)) = iter.peek0() { + *next_pos = *p; + let key_pos = *next_pos; + let key = parse_ident(iter, next_pos)?; + if params.contains_key(&key) { + return Err(parse_err(ErrorKind::DuplicateKey(key.clone()), key_pos)); + } + match iter.next() { + Some((p, '=')) => *next_pos = p + 1, + Some((p, c)) => return Err(parse_err(ErrorKind::BadSeparator(('=', c)), p)), + None => return Err(parse_err(ErrorKind::IncompleteKeyValue, input_len)), + } + let value = parse_value(iter, next_pos, input_len)?; + iter.next().unwrap(); // skip ';' + params.insert(key, value); + } + Ok(params) +} + +/// Parse a config string. +/// +/// ``` +/// use questdb_confstr::parse_conf_str; +/// # use questdb_confstr::ParsingError; +/// let config = parse_conf_str("service::key1=value1;key2=value2;")?; +/// assert_eq!(config.service(), "service"); +/// assert_eq!(config.get("key1"), Some("value1")); +/// assert_eq!(config.get("key2"), Some("value2")); +/// # Ok::<(), ParsingError>(()) +/// ``` +pub fn parse_conf_str(input: &str) -> Result { + let mut iter = input.char_indices().peekable2(); + let mut next_pos = 0; + let service = parse_ident(&mut iter, &mut next_pos)?; + let has_separator = parse_double_colon(&mut iter, &mut next_pos)?; + if !has_separator { + return Ok(ConfStr::new(service, Params::new())); + } + let params = parse_params(&mut iter, &mut next_pos, input.len())?; + Ok(ConfStr::new(service, params)) +} diff --git a/src/peekable2.rs b/src/peekable2.rs new file mode 100644 index 0000000..362ddd4 --- /dev/null +++ b/src/peekable2.rs @@ -0,0 +1,98 @@ +use std::fmt::Debug; +use std::iter::Fuse; + +/// An iterator that allows peeking at the next two items. +#[derive(Clone, Debug)] +#[must_use = "iterator adaptors are lazy and do nothing unless consumed"] +pub(crate) struct Peekable2 +where + I: Iterator, +{ + iter: Fuse, + buf: [Option; 2], +} + +pub(crate) fn peekable2(iterable: I) -> Peekable2 +where + I: IntoIterator, +{ + let mut p2 = Peekable2 { + iter: iterable.into_iter().fuse(), + buf: [None, None], + }; + + p2.buf[0] = p2.iter.next(); + p2.buf[1] = p2.iter.next(); + + p2 +} + +impl Peekable2 { + pub(crate) fn peek0(&self) -> Option<&I::Item> { + self.buf[0].as_ref() + } + + pub(crate) fn peek1(&self) -> Option<&I::Item> { + self.buf[1].as_ref() + } +} + +impl Iterator for Peekable2 +where + I: Iterator, +{ + type Item = I::Item; + + fn next(&mut self) -> Option { + let popped_item = self.buf[0].take(); + self.buf[0] = self.buf[1].take(); + self.buf[1] = self.iter.next(); + popped_item + } +} + +pub(crate) trait Peekable2Ext: Iterator { + fn peekable2(self) -> Peekable2 + where + Self: Sized, + { + peekable2(self) + } +} + +impl Peekable2Ext for I {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_peekable2() { + let v = vec![1, 2, 3, 4, 5]; + let mut iter = v.into_iter().peekable2(); + assert_eq!(iter.peek0(), Some(&1)); + assert_eq!(iter.peek1(), Some(&2)); + assert_eq!(iter.next(), Some(1)); + assert_eq!(iter.peek0(), Some(&2)); + assert_eq!(iter.peek1(), Some(&3)); + assert_eq!(iter.next(), Some(2)); + assert_eq!(iter.peek0(), Some(&3)); + assert_eq!(iter.peek1(), Some(&4)); + assert_eq!(iter.next(), Some(3)); + assert_eq!(iter.peek0(), Some(&4)); + assert_eq!(iter.peek1(), Some(&5)); + assert_eq!(iter.next(), Some(4)); + assert_eq!(iter.peek0(), Some(&5)); + assert_eq!(iter.peek1(), None); + assert_eq!(iter.next(), Some(5)); + assert_eq!(iter.peek0(), None); + assert_eq!(iter.peek1(), None); + assert_eq!(iter.next(), None); + assert_eq!(iter.peek0(), None); + assert_eq!(iter.peek1(), None); + assert_eq!(iter.next(), None); + assert_eq!(iter.peek0(), None); + assert_eq!(iter.peek1(), None); + assert_eq!(iter.next(), None); + } +} diff --git a/tests/tests.rs b/tests/tests.rs new file mode 100644 index 0000000..f3988a8 --- /dev/null +++ b/tests/tests.rs @@ -0,0 +1,330 @@ +/******************************************************************************* + * ___ _ ____ ____ + * / _ \ _ _ ___ ___| |_| _ \| __ ) + * | | | | | | |/ _ \/ __| __| | | | _ \ + * | |_| | |_| | __/\__ \ |_| |_| | |_) | + * \__\_\\__,_|\___||___/\__|____/|____/ + * + * Copyright (c) 2014-2019 Appsicle + * Copyright (c) 2019-2024 QuestDB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +use questdb_confstr::{parse_conf_str, ErrorKind, ParsingError}; + +#[test] +fn empty() -> Result<(), ParsingError> { + let input = ""; + let config = parse_conf_str(input); + assert!(config.is_err()); + let err = config.unwrap_err(); + assert_eq!(err.kind().clone(), ErrorKind::ExpectedIdentifierNotEmpty); + assert_eq!(err.position(), 0); + assert_eq!( + err.to_string(), + "expected identifier, not an empty string at position 0" + ); + Ok(()) +} + +#[test] +fn basic() -> Result<(), ParsingError> { + let input = "http::host=127.0.0.1;port=9000;"; + let config = parse_conf_str(input)?; + assert_eq!(config.service(), "http"); + assert_eq!(config.get("host"), Some("127.0.0.1")); + assert_eq!(config.get("port"), Some("9000")); + assert_eq!(format!("{:?}", config), "ConfStr { service: \"http\", .. }"); + Ok(()) +} + +#[test] +fn case_sensitivity() -> Result<(), ParsingError> { + let input = "TcP::Host=LoCaLhOsT;Port=9000;"; + let config = parse_conf_str(input)?; + assert_eq!(config.service(), "tcp"); + assert_eq!(config.get("host"), Some("LoCaLhOsT")); + assert_eq!(config.get("port"), Some("9000")); + Ok(()) +} + +#[test] +fn duplicate_key() { + let input = "http::host=127.0.0.1;host=localhost;port=9000;"; + let config = parse_conf_str(input); + assert!(config.is_err()); + let err = config.unwrap_err(); + assert_eq!( + err.kind().clone(), + ErrorKind::DuplicateKey("host".to_string()) + ); + assert_eq!(err.position(), 21); + assert_eq!(err.to_string(), "duplicate key \"host\" at position 21"); +} + +#[test] +fn key_must_start_with_letter() { + let input = "https::123=456;"; + let config = parse_conf_str(input); + assert!(config.is_err()); + let err = config.unwrap_err(); + assert_eq!(err.kind().clone(), ErrorKind::ExpectedIdentifierNot('1')); + assert_eq!(err.position(), 7); + assert_eq!( + err.to_string(), + "expected identifier to start with ascii letter, not '1' at position 7" + ); +} + +#[test] +fn key_must_be_alphanumeric() { + let input = "https::ho st=localhost;"; + let config = parse_conf_str(input); + assert!(config.is_err()); + let err = config.unwrap_err(); + assert_eq!(err.kind().clone(), ErrorKind::MustBeAlphanumeric(' ')); + assert_eq!(err.position(), 9); + assert_eq!( + err.to_string(), + "must be alphanumeric, not ' ' at position 9" + ); +} + +#[test] +fn key_cannot_be_empty() { + let input = "https::=localhost;"; + let config = parse_conf_str(input); + assert!(config.is_err()); + let err = config.unwrap_err(); + assert_eq!(err.kind().clone(), ErrorKind::ExpectedIdentifierNot('=')); + assert_eq!(err.position(), 7); + assert_eq!( + err.to_string(), + "expected identifier to start with ascii letter, not '=' at position 7" + ); +} + +#[test] +fn no_params_with_semicolons() -> Result<(), ParsingError> { + let input = "https::"; + let config = parse_conf_str(input)?; + assert_eq!(config.service(), "https"); + assert!(config.params().is_empty()); + Ok(()) +} + +#[test] +fn no_params_no_semicolons() -> Result<(), ParsingError> { + let input = "https"; + let config = parse_conf_str(input)?; + assert_eq!(config.service(), "https"); + assert!(config.params().is_empty()); + Ok(()) +} + +#[test] +fn bad_service_name_separator1() { + let input = "x;/host=localhost;"; + let config = parse_conf_str(input); + assert!(config.is_err()); + let err = config.unwrap_err(); + assert_eq!(err.kind(), ErrorKind::BadSeparator((':', ';'))); + assert_eq!(err.position(), 1); + assert_eq!( + err.to_string(), + "bad separator, expected ':' got ';' at position 1" + ); +} + +#[test] +fn bad_service_name_separator2() { + let input = "x:;host=localhost;"; + let config = parse_conf_str(input); + assert!(config.is_err()); + let err = config.unwrap_err(); + assert_eq!(err.kind(), ErrorKind::BadSeparator((':', ';'))); + assert_eq!(err.position(), 2); + assert_eq!( + err.to_string(), + "bad separator, expected ':' got ';' at position 2" + ); +} + +#[test] +fn url_as_service_separator() { + let input = "http://localhost:9000;host=localhost;"; + let config = parse_conf_str(input); + assert!(config.is_err()); + let err = config.unwrap_err(); + assert_eq!(err.kind(), ErrorKind::BadSeparator((':', '/'))); + assert_eq!(err.position(), 5); + assert_eq!( + err.to_string(), + "bad separator, expected ':' got '/' at position 5" + ); +} + +#[test] +fn no_service_name_with_semicolons() { + let input = "::host=localhost;"; + let config = parse_conf_str(input); + assert!(config.is_err()); + let err = config.unwrap_err(); + assert_eq!(err.kind(), ErrorKind::ExpectedIdentifierNot(':')); + assert_eq!(err.position(), 0); + assert_eq!( + err.to_string(), + "expected identifier to start with ascii letter, not ':' at position 0" + ); +} + +#[test] +fn no_service_name_no_semicolons() { + let input = "host=localhost;"; + let config = parse_conf_str(input); + assert!(config.is_err()); + let err = config.unwrap_err(); + assert_eq!(err.kind(), ErrorKind::BadSeparator((':', '='))); + assert_eq!(err.position(), 4); + assert_eq!( + err.to_string(), + "bad separator, expected ':' got '=' at position 4" + ); +} + +#[test] +fn bad_key_value_separator_semicolon() { + let input = "http::host=localhost;port9000;"; + let config = parse_conf_str(input); + assert!(config.is_err()); + let err = config.unwrap_err(); + assert_eq!(err.kind(), ErrorKind::BadSeparator(('=', ';'))); + assert_eq!(err.position(), 29); + assert_eq!( + err.to_string(), + "bad separator, expected '=' got ';' at position 29" + ); +} + +#[test] +fn bad_key_value_separator_colon() { + let input = "s3::host:localhost;port=9000;"; + let config = parse_conf_str(input); + assert!(config.is_err()); + let err = config.unwrap_err(); + assert_eq!(err.kind(), ErrorKind::BadSeparator(('=', ':'))); + assert_eq!(err.position(), 8); + assert_eq!( + err.to_string(), + "bad separator, expected '=' got ':' at position 8" + ); +} + +#[test] +fn test_incomplete_key_no_value() { + let input = "http::host"; + let config = parse_conf_str(input); + assert!(config.is_err()); + let err = config.unwrap_err(); + assert_eq!(err.kind(), ErrorKind::IncompleteKeyValue); + assert_eq!(err.position(), 10); + assert_eq!( + err.to_string(), + "incomplete key-value pair before end of input at position 10" + ); +} + +#[test] +fn missing_trailing_semicolon() { + let input = "http::host=localhost;port=9000"; + let config = parse_conf_str(input); + assert!(config.is_err()); + let err = config.unwrap_err(); + assert_eq!(ErrorKind::MissingTrailingSemicolon, err.kind()); + assert_eq!(err.position(), 30); + assert_eq!(err.to_string(), "missing trailing semicolon at position 30"); +} + +#[test] +fn escaped_semicolon_missing_trailing() { + let input = "http::host=localhost;port=9000;;"; + let config = parse_conf_str(input); + assert!(config.is_err()); + let err = config.unwrap_err(); + assert_eq!(err.kind(), ErrorKind::MissingTrailingSemicolon); + assert_eq!(err.position(), 32); + assert_eq!(err.to_string(), "missing trailing semicolon at position 32"); +} + +#[test] +fn escaped_semicolon() -> Result<(), ParsingError> { + let input = "FTP::HOSTS=abc.com;;def.com;;ghi.net;PORTS=9000;;8000;;7000;;;"; + let config = parse_conf_str(input)?; + assert_eq!(config.service(), "ftp"); + assert_eq!(config.get("hosts"), Some("abc.com;def.com;ghi.net")); + assert_eq!(config.get("ports"), Some("9000;8000;7000;")); + Ok(()) +} + +#[test] +fn byte_not_char_position() { + let input = "p::n=静;:=42;"; + let config = parse_conf_str(input); + assert!(config.is_err()); + let err = config.unwrap_err(); + assert_eq!(err.kind(), ErrorKind::ExpectedIdentifierNot(':')); + assert_eq!(err.position(), 9); + assert_eq!( + err.to_string(), + "expected identifier to start with ascii letter, not ':' at position 9" + ); +} + +#[test] +fn unicode_service_name() { + let input = "協定"; + let config = parse_conf_str(input); + assert!(config.is_err()); + let err = config.unwrap_err(); + assert_eq!(err.kind(), ErrorKind::ExpectedIdentifierNot('協')); + assert_eq!(err.position(), 0); + assert_eq!( + err.to_string(), + "expected identifier to start with ascii letter, not '協' at position 0" + ); +} + +#[test] +fn unicode_second_key_letter() { + let input = "http::x協定=42;"; + let config = parse_conf_str(input); + assert!(config.is_err()); + let err = config.unwrap_err(); + assert_eq!(err.kind(), ErrorKind::MustBeAlphanumeric('協')); + assert_eq!(err.position(), 7); + assert_eq!( + err.to_string(), + "must be alphanumeric, not '協' at position 7" + ); +} + +#[test] +fn unicode_value() -> Result<(), ParsingError> { + let input = "http::x=協定;"; + let config = parse_conf_str(input)?; + assert_eq!(config.service(), "http"); + assert_eq!(config.get("x"), Some("協定")); + Ok(()) +}