From ecad660a05960155f208bfc701d06de92ff8a7b7 Mon Sep 17 00:00:00 2001 From: Rouven Hi! <3582050+RouHim@users.noreply.github.com> Date: Fri, 12 Apr 2024 09:38:01 +0200 Subject: [PATCH] #128 Add/Allow duplicate properties (#129) * feat(lib): Allow adding / appending duplicate entries * feat(tests): Add tests for duplicate properties * feat(tests): Add more unit tests * chore(tests): Rename test * fix: new feature tests on windows * Revert "fix: new feature tests on windows" This reverts commit a3984643debf72b01963f545f9689e32a0864cbc. * fix: broken test on windows * fix: broken test on windows (hopefully) --------- Co-authored-by: Rouven Himmelstein --- src/lib.rs | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 0f8cd08..4f11166 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -365,6 +365,20 @@ impl<'a> SectionSetter<'a> { self } + /// Add (append) key-value pair in this section + pub fn add(&'a mut self, key: K, value: V) -> &'a mut SectionSetter<'a> + where + K: Into, + V: Into, + { + self.ini + .entry(self.section_name.clone()) + .or_insert_with(Default::default) + .append(key, value); + + self + } + /// Delete the first entry in this section with `key` pub fn delete>(&'a mut self, key: &K) -> &'a mut SectionSetter<'a> { for prop in self.ini.section_all_mut(self.section_name.as_ref()) { @@ -2330,6 +2344,43 @@ bar = f assert_eq!(None, iter.next()); } + #[test] + fn add_properties_api() { + // Test duplicate properties in a section + let mut ini = Ini::new(); + ini.with_section(Some("foo")) + .add("a", "1") + .add("a", "2"); + + let sec = ini.section(Some("foo")).unwrap(); + assert_eq!(sec.get("a"), Some("1")); + assert_eq!(sec.get_all("a").collect::>(), vec!["1", "2"]); + + // Test add with unique keys + let mut ini = Ini::new(); + ini.with_section(Some("foo")) + .add("a", "1") + .add("b", "2"); + + let sec = ini.section(Some("foo")).unwrap(); + assert_eq!(sec.get("a"), Some("1")); + assert_eq!(sec.get("b"), Some("2")); + + // Test string representation + let mut ini = Ini::new(); + ini.with_section(Some("foo")) + .add("a", "1") + .add("a", "2"); + let mut buf = Vec::new(); + ini.write_to(&mut buf).unwrap(); + let ini_str = String::from_utf8(buf).unwrap(); + if cfg!(windows) { + assert_eq!(ini_str, "[foo]\r\na=1\r\na=2\r\n"); + } else { + assert_eq!(ini_str, "[foo]\na=1\na=2\n"); + } + } + #[test] fn new_has_empty_general_section() { let mut ini = Ini::new();