1#[allow(
29 unused_imports,
30 clippy::wildcard_imports,
31 reason = "Standard workspace module prelude"
32)]
33use crate::utilities::*;
34
35pub mod funnel;
37pub mod numeric;
39pub mod pattern;
41pub mod stringmod;
43
44pub fn cat(left: &str, right: &str) -> String {
46 let mut out = String::with_capacity(left.len().saturating_add(right.len()));
47 out.push_str(left);
48 out.push_str(right);
49 out
50}
51
52pub fn sandwich(prefix: &str, root: &str, suffix: &str) -> String {
55 if root.is_empty() {
56 return String::new();
57 }
58
59 let mut out = String::with_capacity(
60 prefix
61 .len()
62 .saturating_add(root.len())
63 .saturating_add(suffix.len()),
64 );
65 out.push_str(prefix);
66 out.push_str(root);
67 out.push_str(suffix);
68 out
69}
70
71pub fn rep(text: &str, count: usize) -> String {
73 let mut out = String::with_capacity(text.len().saturating_mul(count));
74 for _ in 0..count {
75 out.push_str(text);
76 }
77 out
78}
79
80fn byte_index_at_char(s: &str, char_pos: usize) -> usize {
81 let mut it = s.char_indices();
82 if let Some((idx, _)) = it.nth(char_pos) {
83 return idx;
84 }
85 s.len()
86}
87
88#[expect(
89 clippy::expect_used,
90 reason = "start_b and end_b are valid character boundary byte indices <= s.len()"
91)]
92fn slice_chars(s: &str, start_char: usize, len_chars: usize) -> String {
93 if len_chars == 0 {
94 return String::new();
95 }
96
97 let start_b = byte_index_at_char(s, start_char);
98 let end_b = byte_index_at_char(s, start_char.saturating_add(len_chars));
99 s.get(start_b..end_b)
100 .expect("start_b and end_b are valid char boundaries <= s.len()")
101 .to_string()
102}
103
104#[expect(
105 clippy::expect_used,
106 reason = "start_b is a valid character boundary byte index <= s.len()"
107)]
108fn slice_chars_from(s: &str, start_char: usize) -> String {
109 let start_b = byte_index_at_char(s, start_char);
110 s.get(start_b..)
111 .expect("start_b is a valid char boundary <= s.len()")
112 .to_string()
113}
114
115#[expect(
116 clippy::expect_used,
117 reason = "end_b is a valid character boundary byte index <= s.len()"
118)]
119fn slice_chars_to(s: &str, end_char: usize) -> String {
120 let end_b = byte_index_at_char(s, end_char);
121 s.get(..end_b)
122 .expect("end_b is a valid char boundary <= s.len()")
123 .to_string()
124}
125
126#[expect(
130 clippy::expect_used,
131 reason = "start = pos + tag.len() is a valid character boundary byte index <= text.len()"
132)]
133pub fn after(text: &str, tag: &str) -> String {
134 if tag.is_empty() {
135 return String::new();
136 }
137 let Some(pos) = text.find(tag) else {
138 return String::new();
139 };
140 let start = pos.saturating_add(tag.len());
141 text.get(start..)
142 .expect("start is a valid char boundary <= text.len()")
143 .to_string()
144}
145
146#[expect(
147 clippy::expect_used,
148 reason = "pos from text.find(tag) is a valid character boundary byte index <= text.len()"
149)]
150pub fn before(text: &str, tag: &str) -> String {
151 if tag.is_empty() {
152 return String::new();
153 }
154 let Some(pos) = text.find(tag) else {
155 return String::new();
156 };
157 text.get(..pos)
158 .expect("pos is a valid char boundary <= text.len()")
159 .to_string()
160}
161
162pub fn firstline(text: &str) -> String {
164 let mut it = text.split('\n');
165 if let Some(first) = it.next() {
166 return first.to_string();
167 }
168 String::new()
169}
170
171pub fn lastline(text: &str) -> String {
173 let mut it = text.rsplit('\n');
174 if let Some(last) = it.next() {
175 return last.to_string();
176 }
177 String::new()
178}
179
180pub fn lastword(text: &str) -> String {
182 let mut it = text.split_whitespace();
183 if let Some(last) = it.next_back() {
184 return last.to_string();
185 }
186 String::new()
187}
188
189pub fn left(text: &str, len: usize) -> String {
191 let total = text.chars().count();
192 slice_chars(text, 0, len.min(total))
193}
194
195pub fn mid(text: &str, start: usize, len: usize) -> String {
197 let Some(start0) = start.checked_sub(1) else {
198 return String::new();
199 };
200 let total = text.chars().count();
201 if start0 >= total {
202 return String::new();
203 }
204 slice_chars(text, start0, len.min(total.saturating_sub(start0)))
205}
206
207pub fn nthline(text: &str, num: usize) -> String {
209 if num == 0 {
210 return String::new();
211 }
212 let mut it = text.split('\n');
213 let idx = num.saturating_sub(1);
214 if let Some(line) = it.nth(idx) {
215 return line.to_string();
216 }
217 String::new()
218}
219
220pub fn nthword(text: &str, num: usize) -> String {
222 if num == 0 {
223 return String::new();
224 }
225 let mut it = text.split_whitespace();
226 let idx = num.saturating_sub(1);
227 if let Some(word) = it.nth(idx) {
228 return word.to_string();
229 }
230 String::new()
231}
232
233pub fn removeprefix(text: &str, prefix: &str) -> String {
235 if let Some(rest) = text.strip_prefix(prefix) {
236 return rest.to_string();
237 }
238 text.to_string()
239}
240
241pub fn removesuffix(text: &str, suffix: &str) -> String {
243 if let Some(rest) = text.strip_suffix(suffix) {
244 return rest.to_string();
245 }
246 text.to_string()
247}
248
249pub fn right(text: &str, len: usize) -> String {
251 let total = text.chars().count();
252 if len >= total {
253 return text.to_string();
254 }
255 let start = total.saturating_sub(len);
256 slice_chars_from(text, start)
257}
258
259pub fn snip(text: &str, startposition: usize, count: i64) -> String {
263 let total = text.chars().count();
264 if startposition >= total {
265 return text.to_string();
266 }
267
268 if count == -1 {
269 return slice_chars_to(text, startposition);
270 }
271 if count <= 0 {
272 return text.to_string();
273 }
274
275 let Ok(count_usize) = usize::try_from(count) else {
276 return text.to_string();
277 };
278
279 let prefix = slice_chars_to(text, startposition);
280 let suffix =
281 slice_chars_from(text, startposition.saturating_add(count_usize));
282 cat(&prefix, &suffix)
283}
284
285#[expect(
287 clippy::expect_used,
288 reason = "start = pos + tag.len() is a valid character boundary byte index <= text.len()"
289)]
290pub fn textafter(text: &str, tag: &str) -> String {
291 if tag.is_empty() {
292 return text.to_string();
293 }
294 let Some(pos) = text.find(tag) else {
295 return text.to_string();
296 };
297 let start = pos.saturating_add(tag.len());
298 text.get(start..)
299 .expect("start is a valid char boundary <= text.len()")
300 .to_string()
301}
302
303#[expect(
304 clippy::expect_used,
305 reason = "pos from text.find(tag) is a valid character boundary byte index <= text.len()"
306)]
307pub fn textbefore(text: &str, tag: &str) -> String {
308 if tag.is_empty() {
309 return text.to_string();
310 }
311 let Some(pos) = text.find(tag) else {
312 return text.to_string();
313 };
314 text.get(..pos)
315 .expect("pos is a valid char boundary <= text.len()")
316 .to_string()
317}
318
319pub fn trim(text: &str, len: usize) -> String {
321 let total = text.chars().count();
322 if len >= total {
323 return String::new();
324 }
325 slice_chars(text, 0, total.saturating_sub(len))
326}
327
328pub fn trimleft(text: &str, len: usize) -> String {
330 let total = text.chars().count();
331 if len >= total {
332 return String::new();
333 }
334 slice_chars_from(text, len)
335}
336
337pub fn length(text: &str) -> usize {
339 text.chars().count()
340}
341
342pub fn linecount(text: &str) -> usize {
344 if text.is_empty() {
345 return 0;
346 }
347 text.split('\n').count()
348}
349
350fn parse_ranges(therange: &str) -> Vec<(char, char)> {
351 let mut out = Vec::new();
352 let mut it = therange.chars();
353 loop {
354 let Some(a) = it.next() else { break };
355 let Some(b) = it.next() else { break };
356 if a <= b {
357 out.push((a, b));
358 } else {
359 out.push((b, a));
360 }
361 }
362 out
363}
364
365pub fn rangecontains(thetext: &str, therange: &str) -> bool {
368 let ranges = parse_ranges(therange);
369 for ch in thetext.chars() {
370 for (lo, hi) in ranges.iter().copied() {
371 if ch >= lo && ch <= hi {
372 return true;
373 }
374 }
375 }
376 false
377}
378
379pub fn rangematch(text: &str, therange: &str) -> bool {
382 let ranges = parse_ranges(therange);
383 for ch in text.chars() {
384 let mut ok = false;
385 for (lo, hi) in ranges.iter().copied() {
386 if ch >= lo && ch <= hi {
387 ok = true;
388 break;
389 }
390 }
391 if !ok {
392 return false;
393 }
394 }
395 true
396}
397
398#[expect(
400 clippy::expect_used,
401 reason = "byte_pos from text.find(phrase) is a valid character boundary byte index <= text.len()"
402)]
403pub fn search(text: &str, phrase: &str) -> usize {
404 if phrase.is_empty() {
405 return 0;
406 }
407 let Some(byte_pos) = text.find(phrase) else {
408 return 0;
409 };
410
411 let prefix = text
412 .get(..byte_pos)
413 .expect("byte_pos is a valid char boundary <= text.len()");
414 prefix.chars().count().saturating_add(1)
415}
416
417pub fn wordcount(text: &str) -> usize {
419 text.split_whitespace().count()
420}
421
422pub fn contains(text: &str, substring: &str) -> bool {
424 text.contains(substring)
425}
426
427#[cfg(test)]
428#[allow(
429 clippy::panic,
430 clippy::expect_used,
431 clippy::unwrap_used,
432 clippy::unwrap_in_result,
433 clippy::panic_in_result_fn,
434 clippy::indexing_slicing,
435 clippy::arithmetic_side_effects,
436 reason = "Standard repository test boilerplate"
437)]
438mod tests {
439 use super::*;
440
441 #[crate::ctb_test]
442 fn test_string_utils() {
443 let result = cat("Hello, ", "world!");
445 assert_eq!(result, "Hello, world!");
446 assert_eq!("*****", rep("*", 5));
447
448 assert_eq!(", foo", sandwich(", ", "foo", ""));
450 assert_eq!("", sandwich(", ", "", ""));
451 assert_eq!(" (foo)", sandwich(" (", "foo", ")"));
452 assert_eq!("", sandwich(" (", "", ")"));
453
454 assert_eq!("ef", after("abcdef", "cd"));
456 assert_eq!("", after("abcdef", "")); assert_eq!("ab", before("abcdef", "cd"));
458 assert_eq!("", before("abcdef", "")); assert_eq!("abc", firstline("abc\ndef\nghi"));
460 assert_eq!("ghi", lastline("abc\ndef\nghi"));
461 assert_eq!("ghi", lastword("abc\nde f\nghi"));
462
463 assert_eq!("аб", left("абвг", 2)); assert_eq!("fghi", mid("abcdefghijk", 6, 4));
466 assert_eq!("", mid("abc", 0, 2)); assert_eq!("def", nthline("abc\ndef\nghi", 2));
468 assert_eq!("def", nthword("abc def ghi", 2));
469 assert_eq!("c", removeprefix("abc", "ab"));
470 assert_eq!("abc", removeprefix("abc", "f"));
471 assert_eq!("ab", removesuffix("abc", "c"));
472 assert_eq!("abc", removesuffix("abc", "f"));
473 assert_eq!("bc", right("abc", 2));
474
475 assert_eq!("abef", snip("abcdef", 2, 2));
477 assert_eq!("ab", snip("abcdef", 2, -1)); assert_eq!("abcdef", snip("abcdef", 99, 2)); assert_eq!("abcdef", snip("abcdef", 2, 0)); assert_eq!("abcdef", textafter("abcdef", "xx"));
483 assert_eq!("abcdef", textbefore("abcdef", "xx"));
484 assert_eq!("ef", textafter("abcdef", "cd"));
485 assert_eq!("ab", textbefore("abcdef", "cd"));
486
487 assert_eq!("abcd", trim("abcdef", 2));
489 assert_eq!("cdef", trimleft("abcdef", 2));
490 assert_eq!(6, length("abcdef"));
491 assert_eq!(3, linecount("abc\ndef\nghi"));
492
493 assert!(rangecontains("AB1234CD", "AZaz"));
495 assert!(rangecontains("AB1234CD", "09"));
496 assert!(!rangematch("AB1234CD", "09"));
497 assert!(rangematch("1234", "09"));
498 assert!(rangecontains("a", "azb")); assert_eq!(3, search("ABCD", "C"));
503 assert_eq!(0, search("ABCD", "")); assert_eq!(3, wordcount("abc def ghi"));
505
506 assert!(contains("hello world", "world"));
508 assert!(!contains("hello", "bye"));
509
510 assert_eq!(byte_index_at_char("aβc", 0), 0);
512 assert!(byte_index_at_char("aβc", 99) >= "aβc".len().saturating_sub(1)); assert_eq!(slice_chars("aβcδ", 1, 2), "βc");
514 assert_eq!(slice_chars_from("abc", 1), "bc");
515 assert_eq!(slice_chars_to("abc", 2), "ab");
516 }
517}