Debian Codegraph @

src/utils/strings.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
•1 use std::num::NonZeroUsize;
2
3 use ratatui::text::Text;
•4 use unicode_segmentation::UnicodeSegmentation;
5 use unicode_width::UnicodeWidthStr;
6
7 /// Truncates text if it is too long, and adds an ellipsis at the end if needed.
8 ///
9 /// TODO: Maybe cache results from this function for some cases? e.g. columns
10 #[inline]
11 pub fn truncate_to_text<'a, U: Into<usize>>(content: &str, width: U) -> Text<'a> {
•12 Text::raw(truncate_str(content, width))
13 }
14
15 /// Returns the width of a str `s`. This takes into account some things like
16 /// joiners when calculating width.
17 #[inline]
18 pub fn str_width(s: &str) -> usize {
19 UnicodeSegmentation::graphemes(s, true)
20 .map(|g| {
21 if g.contains('\u{200d}') {
22 2
23 } else {
24 UnicodeWidthStr::width(g)
25 }
26 })
27 .sum()
28 }
29
30 /// Returns the "width" of grapheme `g`. This takes into account some things like
31 /// joiners when calculating width.
32 ///
33 /// Note that while you *can* pass in an entire string, the point is to check
34 /// individual graphemes (e.g. `"a"`, `"💎"`, `"大"`, `"🇨🇦"`).
35 #[inline]
36 fn grapheme_width(g: &str) -> usize {
37 if g.contains('\u{200d}') {
38 2
39 } else {
40 UnicodeWidthStr::width(g)
41 }
42 }
43
44 enum AsciiIterationResult {
45 Complete,
46 Remaining(usize),
47 }
48
49 /// Greedily add characters to the output until a non-ASCII grapheme is found, or
50 /// the output is `width` long.
51 #[inline]
52 fn greedy_ascii_add(content: &str, width: NonZeroUsize) -> (String, AsciiIterationResult) {
53 let width: usize = width.into();
54
55 const SIZE_OF_ELLIPSIS: usize = 3;
56 let mut text = Vec::with_capacity(width - 1 + SIZE_OF_ELLIPSIS);
57
58 let s = content.as_bytes();
59
60 let mut current_index = 0;
61
62 while current_index < width - 1 {
63 let current_byte = s[current_index];
64 if current_byte.is_ascii() {
65 text.push(current_byte);
66 current_index += 1;
67 } else {
68 debug_assert!(text.is_ascii());
69
70 let current_index = AsciiIterationResult::Remaining(current_index);
71
72 // SAFETY: This conversion is safe to do unchecked, we only push ASCII characters up to
73 // this point.
74 let current_text = unsafe { String::from_utf8_unchecked(text) };
75
76 return (current_text, current_index);
77 }
78 }
79
80 // If we made it all the way through, then we probably hit the width limit.
81 debug_assert!(text.is_ascii());
82
83 let current_index = if s[current_index].is_ascii() {
84 let mut ellipsis = [0; SIZE_OF_ELLIPSIS];
85 '…'.encode_utf8(&mut ellipsis);
86 text.extend_from_slice(&ellipsis);
87 AsciiIterationResult::Complete
88 } else {
89 AsciiIterationResult::Remaining(current_index)
90 };
91
92 // SAFETY: This conversion is safe to do unchecked, we only push ASCII characters up to
93 // this point.
94 let current_text = unsafe { String::from_utf8_unchecked(text) };
95
96 (current_text, current_index)
97 }
98
99 /// Truncates a string to the specified width with an ellipsis character.
100 ///
101 /// NB: This probably does not handle EVERY case, but I think it handles most cases
102 /// we will use this function for fine... hopefully.
103 ///
104 /// TODO: Maybe fuzz this function?
105 /// TODO: Maybe release this as a lib? Testing against Fish's script [here](https://github.com/ridiculousfish/widecharwidth) might be useful.
106 #[inline]
107 pub fn truncate_str<U: Into<usize>>(content: &str, width: U) -> String {
108 let width = width.into();
109
110 if content.len() <= width {
111 // If the entire string fits in the width, then we just
112 // need to copy the entire string over.
113
114 content.to_owned()
115 } else if let Some(nz_width) = NonZeroUsize::new(width) {
116 // What we are essentially doing is optimizing for the case that
117 // most, if not all of the string is ASCII. As such:
118 // - Step through each byte until (width - 1) is hit or we find a non-ascii
119 // byte.
120 // - If the byte is ascii, then add it.
121 //
122 // If we didn't get a complete truncated string, then continue on treating the rest as graphemes.
123
124 let (mut text, res) = greedy_ascii_add(content, nz_width);
125 match res {
126 AsciiIterationResult::Complete => text,
127 AsciiIterationResult::Remaining(current_index) => {
128 let mut curr_width = text.len();
129 let mut early_break = false;
130
131 // This tracks the length of the last added string - note this does NOT match the grapheme *width*.
132 // Since the previous characters are always ASCII, this is always initialized as 1, unless the string
133 // is empty.
134 let mut last_added_str_len = if text.is_empty() { 0 } else { 1 };
135
136 // Cases to handle:
137 // - Completes adding the entire string.
138 // - Adds a character up to the boundary, then fails.
139 // - Adds a character not up to the boundary, then fails.
140 // Inspired by https://tomdebruijn.com/posts/rust-string-length-width-calculations/
141 for g in UnicodeSegmentation::graphemes(&content[current_index..], true) {
142 let g_width = grapheme_width(g);
143
144 if curr_width + g_width <= width {
145 curr_width += g_width;
146 last_added_str_len = g.len();
147 text.push_str(g);
148 } else {
149 early_break = true;
150 break;
151 }
152 }
153
154 if early_break {
155 if curr_width == width {
156 // Remove the last grapheme cluster added.
157 text.truncate(text.len() - last_added_str_len);
158 }
159 text.push('…');
160 }
161 text
162 }
163 }
164 } else {
165 String::default()
166 }
167 }
168
169 /// Checks that the first string is equal to any of the other ones in a ASCII
170 /// case-insensitive match.
171 ///
172 /// The generated code is the same as writing:
173 /// `to_ascii_lowercase(a) == to_ascii_lowercase(b) || to_ascii_lowercase(a) ==
174 /// to_ascii_lowercase(c)`, but without allocating and copying temporaries.
175 ///
176 /// # Examples
177 ///
178 /// ```ignore
179 /// assert!(multi_eq_ignore_ascii_case!("test", "test"));
180 /// assert!(multi_eq_ignore_ascii_case!("test", "a" | "b" | "test"));
181 /// assert!(!multi_eq_ignore_ascii_case!("test", "a" | "b" | "c"));
182 /// ```
183 #[macro_export]
184 macro_rules! multi_eq_ignore_ascii_case {
185 ( $lhs:expr, $last:literal ) => {
186 $lhs.eq_ignore_ascii_case($last)
187 };
188 ( $lhs:expr, $head:literal | $($tail:tt)* ) => {
189 $lhs.eq_ignore_ascii_case($head) || multi_eq_ignore_ascii_case!($lhs, $($tail)*)
190 };
191 }
192
193 #[cfg(test)]
194 mod tests {
•195 use crate::utils::general::sort_partial_fn;
196
197 use super::*;
198
199 #[test]
200 fn test_sort_partial_fn() {
201 let mut x = vec![9, 5, 20, 15, 10, 5];
202 let mut y = vec![1.0, 15.0, -1.0, -100.0, -100.1, 16.15, -100.0];
203
204 x.sort_by(|a, b| sort_partial_fn(false)(a, b));
205 assert_eq!(x, vec![5, 5, 9, 10, 15, 20]);
206
207 x.sort_by(|a, b| sort_partial_fn(true)(a, b));
208 assert_eq!(x, vec![20, 15, 10, 9, 5, 5]);
209
210 y.sort_by(|a, b| sort_partial_fn(false)(a, b));
211 assert_eq!(y, vec![-100.1, -100.0, -100.0, -1.0, 1.0, 15.0, 16.15]);
212
213 y.sort_by(|a, b| sort_partial_fn(true)(a, b));
214 assert_eq!(y, vec![16.15, 15.0, 1.0, -1.0, -100.0, -100.0, -100.1]);
215 }
216
217 #[test]
218 fn test_truncate_str() {
219 let cpu_header = "CPU(c)▲";
220
221 assert_eq!(
222 truncate_str(cpu_header, 8_usize),
223 cpu_header,
224 "should match base string as there is extra room"
225 );
226
227 assert_eq!(
228 truncate_str(cpu_header, 7_usize),
229 cpu_header,
230 "should match base string as there is enough room"
231 );
232
233 assert_eq!(truncate_str(cpu_header, 6_usize), "CPU(c…");
234 assert_eq!(truncate_str(cpu_header, 5_usize), "CPU(…");
235 assert_eq!(truncate_str(cpu_header, 4_usize), "CPU…");
236 assert_eq!(truncate_str(cpu_header, 1_usize), "…");
237 assert_eq!(truncate_str(cpu_header, 0_usize), "");
238 }
239
240 #[test]
241 fn test_truncate_ascii() {
242 let content = "0123456";
243
244 assert_eq!(
245 truncate_str(content, 8_usize),
246 content,
247 "should match base string as there is extra room"
248 );
249
250 assert_eq!(
251 truncate_str(content, 7_usize),
252 content,
253 "should match base string as there is enough room"
254 );
255
256 assert_eq!(truncate_str(content, 6_usize), "01234…");
257 assert_eq!(truncate_str(content, 5_usize), "0123…");
258 assert_eq!(truncate_str(content, 4_usize), "012…");
259 assert_eq!(truncate_str(content, 1_usize), "…");
260 assert_eq!(truncate_str(content, 0_usize), "");
261 }
262
263 #[test]
264 fn test_truncate_cjk() {
265 let cjk = "施氏食獅史";
266
267 assert_eq!(
268 truncate_str(cjk, 11_usize),
269 cjk,
270 "should match base string as there is extra room"
271 );
272
273 assert_eq!(
274 truncate_str(cjk, 10_usize),
275 cjk,
276 "should match base string as there is enough room"
277 );
278
279 assert_eq!(truncate_str(cjk, 9_usize), "施氏食獅…");
280 assert_eq!(truncate_str(cjk, 8_usize), "施氏食…");
281 assert_eq!(truncate_str(cjk, 2_usize), "…");
282 assert_eq!(truncate_str(cjk, 1_usize), "…");
283 assert_eq!(truncate_str(cjk, 0_usize), "");
284
285 let cjk_2 = "你好嗎";
286 assert_eq!(truncate_str(cjk_2, 5_usize), "你好…");
287 assert_eq!(truncate_str(cjk_2, 4_usize), "你…");
288 assert_eq!(truncate_str(cjk_2, 3_usize), "你…");
289 assert_eq!(truncate_str(cjk_2, 2_usize), "…");
290 assert_eq!(truncate_str(cjk_2, 1_usize), "…");
291 assert_eq!(truncate_str(cjk_2, 0_usize), "");
292 }
293
294 #[test]
295 fn test_truncate_mixed_one() {
296 let test = "Test (施氏食獅史) Test";
297
298 assert_eq!(
299 truncate_str(test, 30_usize),
300 test,
301 "should match base string as there is extra room"
302 );
303
304 assert_eq!(
305 truncate_str(test, 22_usize),
306 test,
307 "should match base string as there is just enough room"
308 );
309
310 assert_eq!(
311 truncate_str(test, 21_usize),
312 "Test (施氏食獅史) Te…",
313 "should truncate the t and replace the s with ellipsis"
314 );
315
316 assert_eq!(truncate_str(test, 20_usize), "Test (施氏食獅史) T…");
317 assert_eq!(truncate_str(test, 19_usize), "Test (施氏食獅史) …");
318 assert_eq!(truncate_str(test, 18_usize), "Test (施氏食獅史)…");
319 assert_eq!(truncate_str(test, 17_usize), "Test (施氏食獅史…");
320 assert_eq!(truncate_str(test, 16_usize), "Test (施氏食獅…");
321 assert_eq!(truncate_str(test, 15_usize), "Test (施氏食獅…");
322 assert_eq!(truncate_str(test, 14_usize), "Test (施氏食…");
323 assert_eq!(truncate_str(test, 13_usize), "Test (施氏食…");
324 assert_eq!(truncate_str(test, 8_usize), "Test (…");
325 assert_eq!(truncate_str(test, 7_usize), "Test (…");
326 assert_eq!(truncate_str(test, 6_usize), "Test …");
327 assert_eq!(truncate_str(test, 5_usize), "Test…");
328 assert_eq!(truncate_str(test, 4_usize), "Tes…");
329 }
330
331 #[test]
332 fn test_truncate_mixed_two() {
333 let test = "Test (施氏abc食abc獅史) Test";
334
335 assert_eq!(
336 truncate_str(test, 30_usize),
337 test,
338 "should match base string as there is extra room"
339 );
340
341 assert_eq!(
342 truncate_str(test, 28_usize),
343 test,
344 "should match base string as there is just enough room"
345 );
346
347 assert_eq!(truncate_str(test, 26_usize), "Test (施氏abc食abc獅史) T…");
348 assert_eq!(truncate_str(test, 21_usize), "Test (施氏abc食abc獅…");
349 assert_eq!(truncate_str(test, 20_usize), "Test (施氏abc食abc…");
350 assert_eq!(truncate_str(test, 16_usize), "Test (施氏abc食…");
351 assert_eq!(truncate_str(test, 15_usize), "Test (施氏abc…");
352 assert_eq!(truncate_str(test, 14_usize), "Test (施氏abc…");
353 assert_eq!(truncate_str(test, 11_usize), "Test (施氏…");
354 assert_eq!(truncate_str(test, 10_usize), "Test (施…");
355 }
356
357 #[test]
358 fn test_truncate_flags() {
359 let flag = "🇨🇦";
360 assert_eq!(truncate_str(flag, 3_usize), flag);
361 assert_eq!(truncate_str(flag, 2_usize), flag);
362 assert_eq!(truncate_str(flag, 1_usize), "…");
363 assert_eq!(truncate_str(flag, 0_usize), "");
364
365 let flag_text = "oh 🇨🇦";
366 assert_eq!(truncate_str(flag_text, 6_usize), flag_text);
367 assert_eq!(truncate_str(flag_text, 5_usize), flag_text);
368 assert_eq!(truncate_str(flag_text, 4_usize), "oh …");
369
370 let flag_text_wrap = "!🇨🇦!";
371 assert_eq!(truncate_str(flag_text_wrap, 6_usize), flag_text_wrap);
372 assert_eq!(truncate_str(flag_text_wrap, 4_usize), flag_text_wrap);
373 assert_eq!(truncate_str(flag_text_wrap, 3_usize), "!…");
374 assert_eq!(truncate_str(flag_text_wrap, 2_usize), "!…");
375 assert_eq!(truncate_str(flag_text_wrap, 1_usize), "…");
376
377 let flag_cjk = "加拿大🇨🇦";
378 assert_eq!(truncate_str(flag_cjk, 9_usize), flag_cjk);
379 assert_eq!(truncate_str(flag_cjk, 8_usize), flag_cjk);
380 assert_eq!(truncate_str(flag_cjk, 7_usize), "加拿大…");
381 assert_eq!(truncate_str(flag_cjk, 6_usize), "加拿…");
382 assert_eq!(truncate_str(flag_cjk, 5_usize), "加拿…");
383 assert_eq!(truncate_str(flag_cjk, 4_usize), "加…");
384
385 let flag_mix = "🇨🇦加gaa拿naa大daai🇨🇦";
386 assert_eq!(truncate_str(flag_mix, 20_usize), flag_mix);
387 assert_eq!(truncate_str(flag_mix, 19_usize), "🇨🇦加gaa拿naa大daai…");
388 assert_eq!(truncate_str(flag_mix, 18_usize), "🇨🇦加gaa拿naa大daa…");
389 assert_eq!(truncate_str(flag_mix, 17_usize), "🇨🇦加gaa拿naa大da…");
390 assert_eq!(truncate_str(flag_mix, 15_usize), "🇨🇦加gaa拿naa大…");
391 assert_eq!(truncate_str(flag_mix, 14_usize), "🇨🇦加gaa拿naa…");
392 assert_eq!(truncate_str(flag_mix, 13_usize), "🇨🇦加gaa拿naa…");
393 assert_eq!(truncate_str(flag_mix, 3_usize), "🇨🇦…");
394 assert_eq!(truncate_str(flag_mix, 2_usize), "…");
395 assert_eq!(truncate_str(flag_mix, 1_usize), "…");
396 assert_eq!(truncate_str(flag_mix, 0_usize), "");
397 }
398
399 /// This might not be the best way to handle it, but this at least tests that it doesn't crash...
400 #[test]
401 #[ignore]
402 fn test_truncate_hindi() {
403 // cSpell:disable
404 let test = "हिन्दी";
405 assert_eq!(truncate_str(test, 10_usize), test);
406 assert_eq!(truncate_str(test, 6_usize), "हिन्दी");
407 assert_eq!(truncate_str(test, 5_usize), "हिन्दी");
408 assert_eq!(truncate_str(test, 4_usize), "हिन्…");
409 assert_eq!(truncate_str(test, 3_usize), "हि…");
410 assert_eq!(truncate_str(test, 2_usize), "…");
411 assert_eq!(truncate_str(test, 1_usize), "…");
412 assert_eq!(truncate_str(test, 0_usize), "");
413 // cSpell:enable
414 }
415
416 #[test]
417 fn truncate_emoji() {
418 let heart_1 = "♥";
419 assert_eq!(truncate_str(heart_1, 2_usize), heart_1);
420 assert_eq!(truncate_str(heart_1, 1_usize), heart_1);
421 assert_eq!(truncate_str(heart_1, 0_usize), "");
422
423 let heart_2 = "❤";
424 assert_eq!(truncate_str(heart_2, 2_usize), heart_2);
425 assert_eq!(truncate_str(heart_2, 1_usize), heart_2);
426 assert_eq!(truncate_str(heart_2, 0_usize), "");
427
428 // This one has a U+FE0F modifier at the end, and is thus considered "emoji-presentation",
429 // see https://github.com/fish-shell/fish-shell/issues/10461#issuecomment-2079624670.
430 // This shouldn't really be a common issue in a terminal but eh.
431 let heart_emoji_pres = "❤️";
432 assert_eq!(truncate_str(heart_emoji_pres, 2_usize), heart_emoji_pres);
433 assert_eq!(truncate_str(heart_emoji_pres, 1_usize), "…");
434 assert_eq!(truncate_str(heart_emoji_pres, 0_usize), "");
435
436 let emote = "💎";
437 assert_eq!(truncate_str(emote, 2_usize), emote);
438 assert_eq!(truncate_str(emote, 1_usize), "…");
439 assert_eq!(truncate_str(emote, 0_usize), "");
440
441 let family = "👨‍👨‍👧‍👦";
442 assert_eq!(truncate_str(family, 2_usize), family);
443 assert_eq!(truncate_str(family, 1_usize), "…");
444 assert_eq!(truncate_str(family, 0_usize), "");
445
446 let scientist = "👩‍🔬";
447 assert_eq!(truncate_str(scientist, 2_usize), scientist);
448 assert_eq!(truncate_str(scientist, 1_usize), "…");
449 assert_eq!(truncate_str(scientist, 0_usize), "");
450 }
451
452 #[test]
453 fn test_multi_eq_ignore_ascii_case() {
454 assert!(
455 multi_eq_ignore_ascii_case!("test", "test"),
456 "single comparison should succeed"
457 );
458 assert!(
459 multi_eq_ignore_ascii_case!("test", "a" | "test"),
460 "double comparison should succeed"
461 );
462 assert!(
463 multi_eq_ignore_ascii_case!("test", "a" | "b" | "test"),
464 "multi comparison should succeed"
465 );
466
467 assert!(
468 !multi_eq_ignore_ascii_case!("test", "a"),
469 "single non-matching should fail"
470 );
471 assert!(
472 !multi_eq_ignore_ascii_case!("test", "a" | "b"),
473 "double non-matching should fail"
474 );
475 assert!(
476 !multi_eq_ignore_ascii_case!("test", "a" | "b" | "c"),
477 "multi non-matching should fail"
478 );
479 }
480 }