ctb_formats_javascript/
string.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//! JavaScript string manipulation, escaping, and regex helper functions.
21
22use boa_engine::Context as BoaContext;
23use boa_engine::property::PropertyKey;
24use ctb_utilities::Context;
25#[allow(
26    unused_imports,
27    clippy::wildcard_imports,
28    reason = "Standard workspace crate prelude"
29)]
30pub(crate) use ctb_utilities::*;
31
32use boa_engine::object::builtins::JsRegExp;
33use boa_string::{JsStr, JsString};
34
35pub fn js_string(s: &str) -> JsString {
36    JsString::from(s)
37}
38
39pub fn js_regex(regex: &str) -> Result<JsRegExp> {
40    let mut context = BoaContext::default();
41    JsRegExp::new(js_string(regex), "".into(), &mut context)
42        .map_err(|e| anyhow::anyhow!("Failed to create regex: {e}"))
43}
44
45/// Returns the UTF-16 code unit at `index`, matching JS `charCodeAt`.
46///
47/// In JavaScript, `String.prototype.charCodeAt()` returns `NaN` when the
48/// index is out of bounds. This helper returns `None` in that case.
49///
50/// `index` is interpreted as a UTF-16 code-unit index.
51pub fn char_code_at_j(s: &JsString, index: i64) -> Option<u16> {
52    let index = usize::try_from(index).ok()?;
53    s.code_unit_at(index)
54}
55
56/// Returns the UTF-16 code unit at `index`, matching JS `charCodeAt`.
57///
58/// `index` is interpreted as a UTF-16 code-unit index.
59pub fn char_code_at(s: &str, index: i64) -> Option<u16> {
60    char_code_at_j(&JsString::from(s), index)
61}
62
63/// Take a single β€œcharacter” at `index`, keeping surrogate pairs together.
64///
65/// This is the surrogate-pair-aware equivalent of the JS snippet in the
66/// prompt: if `index` points at a high surrogate and the next code unit is a
67/// low surrogate, returns both code units; otherwise returns one code unit.
68///
69/// Returns `None` if `index` is out of bounds.
70pub fn take_char_at_j(s: &JsString, index: i64) -> Option<JsString> {
71    let first = char_code_at_j(s, index)?;
72
73    if (first & 0xfc00) == 0xd800 {
74        let next = char_code_at_j(s, index.checked_add(1)?)?;
75        if (next & 0xfc00) == 0xdc00 {
76            let pair = [first, next];
77            return Some(JsString::from(&pair[..]));
78        }
79    }
80
81    let one = [first];
82    Some(JsString::from(&one[..]))
83}
84
85/// Take a single β€œcharacter” at `index`, keeping surrogate pairs together.
86///
87/// Returns `None` if `index` is out of bounds.
88pub fn take_char_at(s: &str, index: i64) -> Option<String> {
89    let taken = take_char_at_j(&JsString::from(s), index)?;
90    Some(taken.to_std_string_lossy().clone())
91}
92
93fn clamp_i64_to_range(value: i64, min: i64, max: i64) -> i64 {
94    // ...existing code... (none)
95    if value < min {
96        return min;
97    }
98    if value > max {
99        return max;
100    }
101    value
102}
103
104fn len_as_i64(s: &JsString) -> Result<i64> {
105    let len = s.len();
106    i64::try_from(len).context("JsString length does not fit in i64")
107}
108
109/// JavaScript-like `slice(start, end)` using UTF-16 code-unit indices.
110///
111/// Negative indices are relative to the end of the string. Indices are
112/// clamped into `[0, len]`. If `end` is `None`, it defaults to `len`.
113/// <https://tc39.es/ecma262/#sec-string.prototype.slice>
114pub fn slice_j(s: &JsString, start: i64, end: Option<i64>) -> Result<JsString> {
115    let len = len_as_i64(s)?;
116
117    let mut start = if start < 0 {
118        #[expect(
119            clippy::expect_used,
120            reason = "len >= 0 and start < 0, so adding them moves value towards 0 and cannot overflow i64"
121        )]
122        len.checked_add(start)
123            .expect("len >= 0 and start < 0, addition cannot overflow")
124    } else {
125        start
126    };
127    start = clamp_i64_to_range(start, 0, len);
128
129    let mut end = match end {
130        Some(end) => {
131            if end < 0 {
132                #[expect(
133                    clippy::expect_used,
134                    reason = "len >= 0 and end < 0, so adding them moves value towards 0 and cannot overflow i64"
135                )]
136                len.checked_add(end)
137                    .expect("len >= 0 and end < 0, addition cannot overflow")
138            } else {
139                end
140            }
141        }
142        None => len,
143    };
144    end = clamp_i64_to_range(end, 0, len);
145
146    if end <= start {
147        return Ok(JsString::default());
148    }
149
150    let start =
151        usize::try_from(start).context("slice start does not fit in usize")?;
152    let end =
153        usize::try_from(end).context("slice end does not fit in usize")?;
154
155    let Some(part) = s.get(start..end) else {
156        // Defensive: computed indices should always be in-bounds.
157        return Ok(JsString::default());
158    };
159
160    Ok(part)
161}
162
163/// JavaScript-like `slice(start, end)` using UTF-16 code-unit indices.
164///
165/// Negative indices are relative to the end of the string. Indices are
166/// clamped into `[0, len]`. If `end` is `None`, it defaults to `len`.
167pub fn slice(s: &str, start: i64, end: Option<i64>) -> Result<String> {
168    let out = slice_j(&JsString::from(s), start, end)?;
169    Ok(out.to_std_string_lossy().clone())
170}
171
172/// JavaScript-like `substr(start, length)` using UTF-16 code-unit indices.
173///
174/// `start` may be negative (relative to the end). `length` is clamped to
175/// `>= 0` and truncated to the remaining string length.
176pub fn substr_j(
177    s: &JsString,
178    start: i64,
179    length: Option<i64>,
180) -> Result<JsString> {
181    let len = len_as_i64(s)?;
182
183    let mut start = if start < 0 {
184        #[expect(
185            clippy::expect_used,
186            reason = "len >= 0 and start < 0, so adding them moves value towards 0 and cannot overflow i64"
187        )]
188        len.checked_add(start)
189            .expect("len >= 0 and start < 0, addition cannot overflow")
190    } else {
191        start
192    };
193    start = clamp_i64_to_range(start, 0, len);
194
195    let length = match length {
196        Some(length) if length > 0 => length,
197        Some(_) => 0,
198        None => len.saturating_sub(start),
199    };
200
201    let end = start
202        .checked_add(length)
203        // Reason for fallback: 0 <= start <= len and 0 <= length so checked_add is bounded by positive values; defaulting to len matches ECMAScript spec requiring length to be clamped to string end.
204        .map_or(len, |v| clamp_i64_to_range(v, 0, len));
205
206    slice_j(s, start, Some(end))
207}
208
209/// JavaScript-like `substr(start, length)` using UTF-16 code-unit indices.
210///
211/// `start` may be negative (relative to the end). `length` is clamped to
212/// `>= 0` and truncated to the remaining string length.
213pub fn substr(s: &str, start: i64, length: Option<i64>) -> Result<String> {
214    let out = substr_j(&JsString::from(s), start, length)?;
215    Ok(out.to_std_string_lossy().clone())
216}
217
218/// JavaScript-like `indexOf(search, fromIndex)` using UTF-16 code-unit indices.
219///
220/// Returns the first match index, or `-1` if not found.
221///
222/// Note: JS returns `min(fromIndex, len)` when `search` is the empty string.
223pub fn index_of_j(
224    haystack: &JsString,
225    needle: JsStr<'_>,
226    from_index: i64,
227) -> Result<i64> {
228    let len = len_as_i64(haystack)?;
229    let from_index = clamp_i64_to_range(from_index, 0, len);
230    let from_index_usize = usize::try_from(from_index)
231        .context("from_index does not fit in usize")?;
232
233    if needle.is_empty() {
234        return Ok(from_index);
235    }
236
237    let Some(pos) = haystack.index_of(needle, from_index_usize) else {
238        return Ok(-1);
239    };
240
241    i64::try_from(pos).context("match index does not fit in i64")
242}
243
244/// JavaScript-like `indexOf(search, fromIndex)` using UTF-16 code-unit indices.
245///
246/// Returns the first match index, or `-1` if not found.
247///
248/// Note: JS returns `min(fromIndex, len)` when `search` is the empty string.
249pub fn index_of(haystack: &str, needle: &str, from_index: i64) -> Result<i64> {
250    let j_haystack = JsString::from(haystack);
251    let j_needle = JsString::from(needle);
252    index_of_j(&j_haystack, j_needle.as_str(), from_index)
253}
254
255/// JavaScript-like `search(regex)` using UTF-16 code-unit indices.
256///
257/// Returns the first match index, or `-1` if not found.
258pub fn search_j(haystack: JsString, regex: &JsRegExp) -> Result<i64> {
259    let context = &mut BoaContext::default();
260
261    let exec_result = regex
262        .exec(haystack, context)
263        .map_err(|e| anyhow::anyhow!("Regex execution failed: {e}"))?;
264
265    let Some(exec_result) = exec_result else {
266        return Ok(-1);
267    };
268
269    let index_value = exec_result
270        .get(PropertyKey::String(js_string("index")), context)
271        .map_err(|e| anyhow::anyhow!("Regex result access failed: {e}"))?;
272    let index_i32 = index_value.to_i32(context).map_err(|e| {
273        anyhow::anyhow!("Regex match index conversion failed: {e}")
274    })?;
275
276    Ok(i64::from(index_i32))
277}
278
279/// JavaScript-like `search(regex)` using UTF-16 code-unit indices, given Rust
280/// string as input.
281///
282/// Returns the first match index, or `-1` if not found.
283pub fn search(haystack: String, regex: String) -> Result<i64> {
284    let js_haystack = JsString::from(haystack.as_str());
285    let js_regex = js_regex(&regex)?;
286
287    search_j(js_haystack, &js_regex)
288}
289
290#[cfg(test)]
291#[allow(
292    clippy::panic,
293    clippy::expect_used,
294    clippy::unwrap_used,
295    clippy::unwrap_in_result,
296    clippy::panic_in_result_fn,
297    clippy::indexing_slicing,
298    clippy::arithmetic_side_effects,
299    reason = "Standard repository test boilerplate"
300)]
301mod tests {
302    use super::*;
303
304    #[crate::ctb_test]
305    fn js_string_round_trips() -> Result<()> {
306        let s = js_string("abc");
307        assert_eq!(s.to_std_string_lossy(), "abc");
308        Ok(())
309    }
310
311    #[crate::ctb_test]
312    fn js_regex_compiles_simple_pattern() -> Result<()> {
313        let _ = js_regex(r"\d+")?;
314        Ok(())
315    }
316
317    #[crate::ctb_test]
318    fn char_code_at_out_of_bounds_is_none() -> Result<()> {
319        let s = JsString::from("abc");
320        assert_eq!(char_code_at_j(&s, -1), None);
321        assert_eq!(char_code_at_j(&s, 3), None);
322
323        assert_eq!(char_code_at("abc", -1), None);
324        assert_eq!(char_code_at("abc", 3), None);
325        Ok(())
326    }
327
328    #[crate::ctb_test]
329    fn take_char_at_keeps_surrogates_together() -> Result<()> {
330        // U+1F604 πŸ˜„ => UTF-16: D83D DE04
331        let s = JsString::from("πŸ˜„!");
332
333        let taken0 = take_char_at_j(&s, 0).unwrap();
334        assert_eq!(taken0.to_vec(), vec![0xd83d, 0xde04]);
335
336        let taken1 = take_char_at_j(&s, 1).unwrap();
337        assert_eq!(taken1.to_vec(), vec![0xde04]);
338
339        let taken2 = take_char_at_j(&s, 2).unwrap();
340        assert_eq!(taken2.to_std_string_lossy(), "!");
341
342        assert!(take_char_at_j(&s, 3).is_none());
343
344        assert_eq!(take_char_at("πŸ˜„!", 0).as_deref(), Some("πŸ˜„"));
345        assert_eq!(take_char_at("πŸ˜„!", 2).as_deref(), Some("!"));
346        assert_eq!(take_char_at("πŸ˜„!", 3), None);
347        Ok(())
348    }
349
350    #[crate::ctb_test]
351    fn slice_and_substr_use_utf16_indices() -> Result<()> {
352        let s = JsString::from("abcd");
353        assert_eq!(slice_j(&s, 1, Some(3))?.to_std_string_lossy(), "bc");
354        assert_eq!(slice_j(&s, -2, None)?.to_std_string_lossy(), "cd");
355
356        assert_eq!(substr_j(&s, 1, Some(2))?.to_std_string_lossy(), "bc");
357        assert_eq!(substr_j(&s, -2, Some(1))?.to_std_string_lossy(), "c");
358
359        assert_eq!(slice("abcd", 1, Some(3))?, "bc");
360        assert_eq!(slice("abcd", -2, None)?, "cd");
361
362        assert_eq!(substr("abcd", 1, Some(2))?, "bc");
363        assert_eq!(substr("abcd", -2, Some(1))?, "c");
364        Ok(())
365    }
366
367    #[crate::ctb_test]
368    fn slice_and_substr_handle_surrogate_pairs_via_utf16_units() -> Result<()> {
369        // "πŸ˜„!" => UTF-16 units: [D83D, DE04, 0021]
370        assert_eq!(slice("πŸ˜„!", 0, Some(2))?, "πŸ˜„");
371        assert_eq!(slice("πŸ˜„!", 2, None)?, "!");
372        assert_eq!(substr("πŸ˜„!", 0, Some(2))?, "πŸ˜„");
373        assert_eq!(substr("πŸ˜„!", 2, Some(1))?, "!");
374        Ok(())
375    }
376
377    #[crate::ctb_test]
378    fn index_of_matches_js_empty_search_behavior() -> Result<()> {
379        let s = JsString::from("abc");
380        let empty = JsString::from("");
381        assert_eq!(index_of_j(&s, empty.as_str(), 2)?, 2);
382        assert_eq!(index_of_j(&s, empty.as_str(), 99)?, 3);
383
384        assert_eq!(index_of("abc", "", 2)?, 2);
385        assert_eq!(index_of("abc", "", 99)?, 3);
386        Ok(())
387    }
388
389    #[crate::ctb_test]
390    fn search_returns_match_index_or_minus_one() -> Result<()> {
391        assert_eq!(search("abc123".to_string(), r"\d+".to_string())?, 3);
392        assert_eq!(search("abcdef".to_string(), r"\d+".to_string())?, -1);
393        Ok(())
394    }
395
396    #[crate::ctb_test]
397    fn search_j_returns_match_index_or_minus_one() -> Result<()> {
398        let js_haystack = JsString::from("abc123");
399        let re = js_regex(r"\d+")?;
400        assert_eq!(search_j(js_haystack, &re)?, 3);
401
402        let js_haystack = JsString::from("abcdef");
403        assert_eq!(search_j(js_haystack, &re)?, -1);
404        Ok(())
405    }
406}