1use crate::utilities::*;
27
28use anyhow::{Result, anyhow, bail};
29
30use crate::{
31 encoding::ascii::stagel_char_from_byte, util::ascii::ascii_is_digit,
32};
33
34pub fn str_char(s: &str, index: usize) -> String {
35 s.chars()
37 .nth(index)
38 .map(|c| c.to_string())
39 .unwrap_or_default()
40}
41pub fn str_char_at_pos(s: &str, index: usize) -> String {
42 str_char(s, index)
43}
44pub fn char_at_pos(s: &str, index: usize) -> String {
45 str_char(s, index)
46}
47pub fn char_at(s: &str, index: usize) -> String {
48 str_char(s, index)
49}
50
51pub fn set_char_at(s: &str, index: usize, ch: &str) -> String {
52 assert!(ch.chars().count() == 1, "Replacement must be single char");
53 let Some(replacement) = ch.chars().next() else {
54 return s.to_string();
55 };
56 s.chars()
57 .enumerate()
58 .map(|(i, c)| if i == index { replacement } else { c })
59 .collect()
60}
61
62pub fn reverse_str(s: &str) -> String {
63 s.chars().rev().collect()
64}
65
66pub fn char_to_upper(ch: &str) -> String {
67 assert!(ch.chars().count() == 1);
68 ch.to_ascii_uppercase()
69}
70
71pub fn str_to_upper(s: &str) -> String {
72 s.chars().map(|c| c.to_ascii_uppercase()).collect()
73}
74
75pub fn char_to_lower(ch: &str) -> String {
76 assert!(ch.chars().count() == 1);
77 ch.to_ascii_lowercase()
78}
79
80pub fn str_to_lower(s: &str) -> String {
81 s.chars().map(|c| c.to_ascii_lowercase()).collect()
82}
83
84pub fn str_empty(s: &str) -> bool {
85 s.is_empty()
86}
87pub fn str_nonempty(s: &str) -> bool {
88 !s.is_empty()
89}
90
91pub fn str_contains_only_int(s: &str) -> bool {
92 if s.is_empty() {
93 return true;
94 }
95 s.chars().all(|c| c.is_ascii_digit())
96}
97
98pub fn substring_bug_compatible(
103 s: &str,
104 start: usize,
105 length: isize,
106) -> Result<String> {
107 if length < 0 {
108 let len_isize = isize::try_from(s.len())
111 .context("String length exceeds isize::MAX")?;
112 let adj = usize::try_from(
113 len_isize.saturating_add(1).saturating_add(length).max(0),
114 )
115 .context("Adjusted length failed conversion to usize")?;
116 Ok(s.chars().skip(start).take(adj).collect())
117 } else {
118 let take_len = usize::try_from(length)
119 .context("Length failed conversion to usize")?;
120 Ok(s.chars().skip(start).take(take_len).collect())
121 }
122}
123
124pub fn len_str(s: &str) -> usize {
125 s.len()
126}
127
128pub fn str_replace_once(haystack: &str, find: &str, replace: &str) -> String {
131 if find.is_empty() {
132 format!("{replace}{haystack}")
134 } else if let Some(pos) = haystack.find(find) {
135 let mut out = String::with_capacity(
136 haystack
137 .len()
138 .saturating_sub(find.len())
139 .saturating_add(replace.len()),
140 );
141 out.push_str(haystack.get(..pos).unwrap_or(""));
143 out.push_str(replace);
144 out.push_str(
146 haystack.get(pos.saturating_add(find.len())..).unwrap_or(""),
147 );
148 out
149 } else {
150 haystack.to_string()
151 }
152}
153
154pub fn format_percentage(a: i32, b: i32) -> Result<String> {
159 if b == 0 {
160 bail!("Division by zero in percentage");
161 }
162 if a == 0 {
163 return Ok("0.000".into());
164 }
165 let pct = (f64::from(a) / f64::from(b)) * 100.0;
166 Ok(format!("{pct:.3}"))
167}
168
169pub fn str_split(input: &str, separator: &str) -> Vec<String> {
174 if separator.is_empty() {
175 return input.chars().map(|c| c.to_string()).collect();
177 }
178
179 let mut out = Vec::new();
180 let mut remaining = input;
181 let sep_len = separator.len();
182
183 while !remaining.is_empty() {
184 if remaining.starts_with(separator) {
185 out.push(String::new());
187 remaining = remaining.get(sep_len..).unwrap_or("");
189 } else {
190 let mut char_indices = remaining.char_indices();
192 let Some((_, _first_char)) = char_indices.next() else {
193 unreachable!();
195 };
196 let next_index =
198 char_indices.next().map_or(remaining.len(), |(i, _)| i);
199 let ch_str = remaining.get(..next_index).unwrap_or("");
201 if let Some(last_token) = out.last_mut() {
203 last_token.push_str(ch_str);
204 } else {
205 out.push(ch_str.to_string());
206 }
207 remaining = remaining.get(next_index..).unwrap_or("");
209 }
210 }
211
212 if input.starts_with(separator) {
214 out.insert(0, String::new());
215 }
216
217 out
218}
219
220pub fn str_split_escaped(input: &str, separator: &str) -> Vec<String> {
230 ctb_utilities::string::split_escaped(input, separator)
231}
232
233pub fn str_split_esc(input: &str, separator: &str) -> Vec<String> {
235 str_split_escaped(input, separator)
236}
237
238pub fn explode_esc(input: &str, separator: &str) -> Vec<String> {
239 str_split_escaped(input, separator)
240}
241pub fn explode_escaped(input: &str, separator: &str) -> Vec<String> {
242 str_split_escaped(input, separator)
243}
244
245pub fn str_join_escaped(parts: &[String], separator: &str) -> String {
248 if parts.is_empty() {
249 return String::new();
250 }
251 let mut out = String::new();
252 for p in parts {
253 let escaped = p.replace(separator, &format!("\\{separator}"));
254 out.push_str(&escaped);
255 out.push_str(separator);
256 }
257 out
258}
259
260pub fn str_join_esc(parts: &[String], separator: &str) -> String {
262 str_join_escaped(parts, separator)
263}
264
265pub fn str_join_esc_no_trailing(parts: &[String], separator: &str) -> String {
267 let joined = str_join_escaped(parts, separator);
268 if joined.ends_with(separator) {
269 let cut = joined.len().saturating_sub(separator.len());
270 joined.get(..cut).unwrap_or("").to_string()
272 } else {
273 joined
274 }
275}
276
277pub fn int_arr_from_str_printed_arr(s: &str) -> Result<Vec<u32>> {
280 let mut current = String::new();
281 let mut out = Vec::new();
282
283 for b in s.bytes() {
284 if b == b' ' {
285 if !current.is_empty() {
286 out.push(
287 current
288 .parse::<u32>()
289 .map_err(|e| anyhow!("parse int: {e}"))?,
290 );
291 current.clear();
292 }
293 } else if ascii_is_digit(b) {
294 let char = stagel_char_from_byte(b)?;
295 current.push_str(&char.clone());
296 } else {
297 return Err(anyhow!(
298 "Unexpected character (byte {b}) in int_arr_from_str_printed_arr"
299 ));
300 }
301 }
302 if !current.is_empty() {
303 out.push(
304 current
305 .parse::<u32>()
306 .map_err(|e| anyhow!("parse int: {e}"))?,
307 );
308 }
309 Ok(out)
310}
311
312pub fn str_to_byte_array(s: &str) -> Result<Vec<u8>> {
315 s.chars()
316 .map(|c| {
317 u8::try_from(u32::from(c) & 0xFF)
318 .context("Failed to convert character codepoint to u8")
319 })
320 .collect()
321}
322
323pub fn str_from_byte_array(bytes: &[u8]) -> String {
325 bytes.iter().map(|b| char::from(*b)).collect()
326}
327
328#[cfg(test)]
329#[allow(
330 clippy::panic,
331 clippy::expect_used,
332 clippy::unwrap_used,
333 clippy::unwrap_in_result,
334 clippy::panic_in_result_fn,
335 clippy::indexing_slicing,
336 clippy::arithmetic_side_effects,
337 reason = "Standard repository test boilerplate"
338)]
339mod tests {
340 use super::*;
341
342 #[crate::ctb_test]
343 fn test_substring_bug_compatible_behavior() -> Result<()> {
344 let s = "abcdef";
345 assert_eq!(substring_bug_compatible(s, 0, 3)?, "abc");
346 assert_eq!(substring_bug_compatible(s, 2, 2)?, "cd");
347 assert_eq!(substring_bug_compatible(s, 0, -1)?, "abcdef");
349 assert_eq!(substring_bug_compatible(s, 0, -2)?, "abcde");
350 Ok(())
351 }
352
353 #[crate::ctb_test]
354 fn test_char_mutation() {
355 let s = "hello";
356 let s2 = set_char_at(s, 1, "A");
357 assert_eq!(s2, "hAllo");
358 assert_eq!(reverse_str("abc"), "cba");
359 }
360
361 #[crate::ctb_test]
362 fn test_case_conversion() {
363 assert_eq!(char_to_upper("a"), "A");
364 assert_eq!(str_to_upper("Abc!"), "ABC!");
365 assert_eq!(char_to_lower("Q"), "q");
366 assert_eq!(str_to_lower("AbC"), "abc");
367 }
368
369 #[crate::ctb_test]
370 fn test_str_contains_only_int() {
371 assert!(str_contains_only_int("12345"));
372 assert!(!str_contains_only_int("12a45"));
373 }
374
375 #[crate::ctb_test]
376 fn test_format_percentage() {
377 let p = format_percentage(1, 2).unwrap();
378 assert_eq!(p, "50.000"); let p = format_percentage(1, 3).unwrap();
380 assert_eq!(p, "33.333"); let p = format_percentage(2, 3).unwrap();
382 assert_eq!(p, "66.667"); }
384
385 #[crate::ctb_test]
386 fn test_str_split_basic() {
387 assert_eq!(
388 str_split("a,b,c", ","),
389 Vec::<String>::from(vec!["a".into(), "b".into(), "c".into()])
390 );
391 assert_eq!(
392 str_split("a,b,c,", ","),
393 Vec::<String>::from(vec![
394 "a".into(),
395 "b".into(),
396 "c".into(),
397 "".into()
398 ])
399 );
400 assert_eq!(str_split("", ","), Vec::<String>::new());
401
402 assert_eq!(
403 str_split("aabbabc", "ab"),
404 Vec::<String>::from(vec!["a".into(), "b".into(), "c".into()])
405 );
406 assert_eq!(
407 str_split("aabbabcab", "ab"),
408 Vec::<String>::from(vec![
409 "a".into(),
410 "b".into(),
411 "c".into(),
412 "".into()
413 ])
414 );
415 assert_eq!(
416 str_split("abc", "ab"),
417 Vec::<String>::from(vec!["".into(), "c".into()])
418 );
419 assert_eq!(
420 str_split("ababbaa", "ab"),
421 Vec::<String>::from(vec!["".into(), "".into(), "baa".into()])
422 );
423 assert_eq!(
424 str_split("aab", "ab"),
425 Vec::<String>::from(vec!["a".into(), "".into()])
426 );
427 assert_eq!(
428 str_split("abaab", "ab"),
429 Vec::<String>::from(vec!["".into(), "a".into(), "".into()])
430 );
431 assert_eq!(
432 str_split("abaabab", "ab"),
433 Vec::<String>::from(vec![
434 "".into(),
435 "a".into(),
436 "".into(),
437 "".into()
438 ])
439 );
440 assert_eq!(
441 str_split("abab", "ab"),
442 Vec::<String>::from(vec!["".into(), "".into(), "".into()])
443 );
444 assert_eq!(
445 str_split("ab", "ab"),
446 Vec::<String>::from(vec!["".into(), "".into()])
447 );
448 assert_eq!(
449 str_split(str_split("abab", "ab").join("ab").as_str(), "ab"),
450 Vec::<String>::from(vec!["".into(), "".into(), "".into()])
451 );
452 }
453
454 #[crate::ctb_test]
455 fn test_str_split_escaped() {
456 let v = str_split_escaped(r"a\,b", ",");
458 assert_eq!(v, vec!["a,b".to_string()]);
459 let v2 = str_split_escaped(r"a\,b,c", ",");
461 assert_eq!(v2, vec!["a,b".to_string(), "c".to_string()]);
462 let v3 = str_split_escaped(r"a\,b\,c,d", ",");
464 assert_eq!(v3, vec!["a,b,c".to_string(), "d".to_string()]);
465 }
466
467 #[crate::ctb_test]
468 fn test_str_join_escaped() {
469 let joined = str_join_escaped(&["a,b".into(), "c".into()], ",");
470 assert_eq!(joined, r"a\,b,c,");
472
473 let no_trailing =
474 str_join_esc_no_trailing(&["a,b".into(), "c".into()], ",");
475 assert_eq!(no_trailing, r"a\,b,c");
476 }
477
478 #[crate::ctb_test]
479 fn test_int_arr_from_str_printed_arr() {
480 let v = int_arr_from_str_printed_arr("1 2 3 ").unwrap();
481 assert_eq!(v, vec![1, 2, 3]);
482
483 let v2 = int_arr_from_str_printed_arr("10 20 30").unwrap();
484 assert_eq!(v2, vec![10, 20, 30]);
485
486 assert!(int_arr_from_str_printed_arr("1 a 3").is_err());
488 }
489
490 #[crate::ctb_test]
491 fn test_str_to_from_byte_array_roundtrip() -> Result<()> {
492 let s = "ABC";
493 let bytes = str_to_byte_array(s)?;
494 assert_eq!(bytes, vec![65, 66, 67]);
495 let s2 = str_from_byte_array(&bytes);
496 assert_eq!(s2, s);
497 Ok(())
498 }
499}