ctb_formats_json/
jsonc.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//! JSON with Comments (JSONC) stripping and preprocessing utilities.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29pub fn strip_jsonc_comments(json: &str) -> String {
30    let mut result = String::new();
31    let mut in_string = false;
32    let mut in_single_line_comment = false;
33    let mut in_multi_line_comment = false;
34    let mut chars = json.chars().peekable();
35
36    while let Some(c) = chars.next() {
37        if in_single_line_comment {
38            if c == '\n' || c == '\r' {
39                in_single_line_comment = false;
40                result.push(c);
41            }
42        } else if in_multi_line_comment {
43            if c == '*' && chars.peek() == Some(&'/') {
44                chars.next();
45                in_multi_line_comment = false;
46            }
47        } else if in_string {
48            result.push(c);
49            if c == '"' {
50                in_string = false;
51            } else if c == '\\' {
52                if let Some(&next_c) = chars.peek() {
53                    result.push(next_c);
54                    chars.next();
55                }
56            }
57        } else if c == '"' {
58            in_string = true;
59            result.push(c);
60        } else if c == '/' && chars.peek() == Some(&'/') {
61            in_single_line_comment = true;
62            chars.next();
63        } else if c == '/' && chars.peek() == Some(&'*') {
64            in_multi_line_comment = true;
65            chars.next();
66        } else {
67            result.push(c);
68        }
69    }
70    result
71}
72
73#[cfg(test)]
74#[allow(
75    clippy::panic,
76    clippy::expect_used,
77    clippy::unwrap_used,
78    clippy::unwrap_in_result,
79    clippy::panic_in_result_fn,
80    clippy::indexing_slicing,
81    clippy::arithmetic_side_effects,
82    reason = "Standard repository test boilerplate"
83)]
84mod tests {}