ctb_formats_eite/
kv.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Key-value pair array and delimited string serialization for EITE.
21
22// =====================
23// KV ARRAY / KV STRING
24// =====================
25// Original JS KV array format: [ key, value, key, value, ... ]
26// KV string format: "key:value,key2:value2," with (escaped) separators.
27// Full escaping rules depend on strSplitEscaped / strJoinEsc / strJoinEscNoTrailing,
28// which are not yet provided in the snippet. We therefore implement the
29// array-level logic now and leave the string-level split/join until the
30// escape utilities arrive.
31
32use crate::utilities::*;
33
34use anyhow::{Result, anyhow};
35
36/// Check whether a slice of strings has even length.
37fn is_kv_array(data: &[String]) -> bool {
38    data.len().is_multiple_of(2)
39}
40
41pub fn kv_has_value(data: &[String], key: &str) -> bool {
42    // Mimic original assertKvArray (would throw). We choose panic for now;
43    // can be converted to Result once global error model decided.
44    assert!(is_kv_array(data), "kv_has_value: invalid kv array length");
45    // Walk even indices only
46    let mut i: usize = 0;
47    while i < data.len() {
48        if data.get(i).is_some_and(|k| k == key) {
49            return true;
50        }
51        i = i.saturating_add(2);
52    }
53    false
54}
55
56/// Returns value or empty string if not found (matching original forgiving behavior).
57#[expect(
58    clippy::expect_used,
59    reason = "Loop condition ensures index i + 1 exists"
60)]
61pub fn kv_get_value(data: &[String], key: &str) -> String {
62    assert!(is_kv_array(data), "kv_get_value: invalid kv array length");
63    let mut i: usize = 0;
64    while i.saturating_add(1) < data.len() {
65        if data.get(i).is_some_and(|k| k == key) {
66            return data
67                .get(i.saturating_add(1))
68                .cloned()
69                .expect("i + 1 < data.len() guaranteed by loop condition");
70        }
71        i = i.saturating_add(2);
72    }
73    String::new()
74}
75
76/// Like `kv_get_value` but asserts key exists (mirrors assertKvHasValue + retrieval).
77pub fn kv_get_defined_value(data: &[String], key: &str) -> Result<String> {
78    if kv_has_value(data, key) {
79        Ok(kv_get_value(data, key))
80    } else {
81        Err(anyhow!("Key '{key}' not found"))
82    }
83}
84
85/// Set (insert or replace) a key/value pair, returning a new `Vec<String>`.
86pub fn kv_set_value(
87    mut data: Vec<String>,
88    key: &str,
89    val: &str,
90) -> Vec<String> {
91    assert!(is_kv_array(&data), "kv_set_value: invalid kv array length");
92    let mut i: usize = 0;
93    while i.saturating_add(1) < data.len() {
94        if data.get(i).is_some_and(|k| k == key) {
95            if let Some(item) = data.get_mut(i.saturating_add(1)) {
96                *item = val.to_string();
97            }
98            return data;
99        }
100        i = i.saturating_add(2);
101    }
102    data.push(key.to_string());
103    data.push(val.to_string());
104    data
105}
106
107#[cfg(test)]
108#[allow(
109    clippy::panic,
110    clippy::expect_used,
111    clippy::unwrap_used,
112    clippy::unwrap_in_result,
113    clippy::panic_in_result_fn,
114    clippy::indexing_slicing,
115    clippy::arithmetic_side_effects,
116    reason = "Standard repository test boilerplate"
117)]
118pub mod tests {
119    use super::*;
120
121    #[crate::ctb_test]
122    fn test_kv_basic() {
123        let data: Vec<String> = vec![];
124        let data = kv_set_value(data, "a", "1");
125        let data = kv_set_value(data, "b", "2");
126        assert!(kv_has_value(&data, "a"));
127        assert_eq!(kv_get_value(&data, "a"), "1");
128        assert_eq!(kv_get_value(&data, "c"), "");
129        let data = kv_set_value(data, "a", "3");
130        assert_eq!(kv_get_value(&data, "a"), "3");
131    }
132
133    #[crate::ctb_test]
134    fn test_kv_has_value_empty_and_odd_length() {
135        let data: Vec<String> = vec![];
136        assert!(!kv_has_value(&data, "x"));
137        let data = vec!["a".to_string()];
138        let result = std::panic::catch_unwind(|| kv_has_value(&data, "a"));
139        assert!(result.is_err());
140    }
141
142    #[crate::ctb_test]
143    fn test_kv_get_value_empty_and_odd_length() {
144        let data: Vec<String> = vec![];
145        assert_eq!(kv_get_value(&data, "x"), "");
146        let data = vec!["a".to_string()];
147        let result = std::panic::catch_unwind(|| kv_get_value(&data, "a"));
148        assert!(result.is_err());
149    }
150
151    #[crate::ctb_test]
152    fn test_kv_get_defined_value_found_and_not_found() {
153        let mut data: Vec<String> = vec![];
154        data = kv_set_value(data, "foo", "bar");
155        assert_eq!(kv_get_defined_value(&data, "foo").unwrap(), "bar");
156        let err = kv_get_defined_value(&data, "baz");
157        assert!(err.is_err());
158    }
159
160    #[crate::ctb_test]
161    fn test_kv_set_value_insert_and_replace() {
162        let mut data: Vec<String> = vec![];
163        data = kv_set_value(data, "x", "1");
164        assert_eq!(data, vec!["x", "1"]);
165        assert_eq!(kv_get_value(&data, "x"), "1");
166        data = kv_set_value(data, "x", "2");
167        assert_eq!(data, vec!["x", "2"]);
168        assert_eq!(kv_get_value(&data, "x"), "2");
169    }
170
171    #[crate::ctb_test]
172    fn test_kv_set_value_odd_length_panics() {
173        let data = vec!["a".to_string()];
174        let result = std::panic::catch_unwind(|| kv_set_value(data, "b", "2"));
175        assert!(result.is_err());
176    }
177
178    #[crate::ctb_test]
179    fn test_kv_array_get_set_mid_elements() {
180        let mut data = vec![
181            "k1".to_string(),
182            "v1".to_string(),
183            "k2".to_string(),
184            "v2".to_string(),
185            "k3".to_string(),
186            "v3".to_string(),
187            "k4".to_string(),
188            "v4".to_string(),
189        ];
190        // Get value for k2 and k3
191        assert_eq!(kv_get_value(&data, "k2"), "v2");
192        assert_eq!(kv_get_value(&data, "k3"), "v3");
193        // Replace value for k2
194        data = kv_set_value(data, "k2", "v2x");
195        assert_eq!(kv_get_value(&data, "k2"), "v2x");
196        // Insert new key-value pair
197        data = kv_set_value(data, "k5", "v5");
198        assert_eq!(kv_get_value(&data, "k5"), "v5");
199        // Check full array
200        assert_eq!(
201            data,
202            vec!["k1", "v1", "k2", "v2x", "k3", "v3", "k4", "v4", "k5", "v5"]
203        );
204    }
205
206    #[crate::ctb_test]
207    fn test_kv_array_get_set_first_and_last() {
208        let mut data = vec![
209            "a".to_string(),
210            "1".to_string(),
211            "b".to_string(),
212            "2".to_string(),
213            "c".to_string(),
214            "3".to_string(),
215            "d".to_string(),
216            "4".to_string(),
217        ];
218        // Get first and last
219        assert_eq!(kv_get_value(&data, "a"), "1");
220        assert_eq!(kv_get_value(&data, "d"), "4");
221        // Replace last
222        data = kv_set_value(data, "d", "44");
223        assert_eq!(kv_get_value(&data, "d"), "44");
224        // Replace first
225        data = kv_set_value(data, "a", "11");
226        assert_eq!(kv_get_value(&data, "a"), "11");
227        // Check full array
228        assert_eq!(data, vec!["a", "11", "b", "2", "c", "3", "d", "44"]);
229    }
230}