1pub fn format_size(size: u64) -> String {
5 const KB: u64 = 1024;
6 const MB: u64 = KB * 1024;
7 const GB: u64 = MB * 1024;
8
9 if size >= GB {
10 format!("{:.1}GB", size as f64 / GB as f64)
11 } else if size >= MB {
12 format!("{:.1}MB", size as f64 / MB as f64)
13 } else if size >= KB {
14 format!("{:.1}KB", size as f64 / KB as f64)
15 } else {
16 format!("{size}B")
17 }
18}
19
20pub fn indent_block(text: &str, indent: &str) -> String {
22 if indent.is_empty() || text.is_empty() {
23 return text.to_string();
24 }
25 let mut indented = String::with_capacity(text.len() + indent.len() * text.lines().count());
26 for (idx, line) in text.split('\n').enumerate() {
27 if idx > 0 {
28 indented.push('\n');
29 }
30 if !line.is_empty() {
31 indented.push_str(indent);
32 }
33 indented.push_str(line);
34 }
35 indented
36}
37
38pub fn truncate_text(text: &str, max_len: usize, ellipsis: &str) -> String {
40 if text.chars().count() <= max_len {
41 return text.to_string();
42 }
43
44 let mut truncated = text.chars().take(max_len).collect::<String>();
45 truncated.push_str(ellipsis);
46 truncated
47}
48
49pub fn truncate_within(text: &str, max_len: usize, ellipsis: &str) -> String {
63 if text.chars().count() <= max_len {
64 return text.to_string();
65 }
66 let keep = max_len.saturating_sub(ellipsis.chars().count());
67 let mut truncated = text.chars().take(keep).collect::<String>();
68 truncated.push_str(ellipsis);
69 truncated
70}
71
72pub fn truncate_middle(text: &str, max_len: usize) -> String {
82 if max_len == 0 {
83 return String::new();
84 }
85 let sanitized: String = text
86 .chars()
87 .map(|c| if matches!(c, '\n' | '\r' | '\t') { ' ' } else { c })
88 .collect();
89 let char_count = sanitized.chars().count();
90 if char_count <= max_len {
91 return sanitized;
92 }
93 if max_len <= 1 {
94 return "…".to_string();
95 }
96 let head_len = max_len / 2;
97 let tail_len = max_len.saturating_sub(head_len + 1);
98
99 let head: String = sanitized.chars().take(head_len).collect();
100 let mut result = String::with_capacity(head.len() + tail_len + 1);
101 result.push_str(&head);
102 result.push('…');
103 if tail_len > 0 {
104 let mut tail_rev: Vec<char> = sanitized.chars().rev().take(tail_len).collect();
105 tail_rev.reverse();
106 let tail: String = tail_rev.into_iter().collect();
107 result.push_str(&tail);
108 }
109 result
110}
111
112pub fn truncate_path_middle(path: &str, max_len: usize) -> String {
119 if max_len == 0 {
120 return String::new();
121 }
122 let char_count = path.chars().count();
123 if char_count <= max_len {
124 return path.to_string();
125 }
126 if max_len <= 1 {
127 return "…".to_string();
128 }
129
130 let head_budget = max_len / 2;
132 let tail_budget = max_len.saturating_sub(head_budget + 1);
133
134 let head_str: String = path.chars().take(head_budget).collect();
138 let head_break = head_str.rfind('/').unwrap_or(head_budget);
139
140 let tail_chars: Vec<char> = path.chars().rev().take(tail_budget).collect();
142 let tail_str: String = tail_chars.iter().rev().collect();
143 let tail_break_from_end = tail_str.find('/').map(|pos| tail_str.len() - pos).unwrap_or(tail_budget);
144
145 let head: String = path.chars().take(head_break).collect();
146 let tail: String = path
147 .chars()
148 .rev()
149 .take(tail_break_from_end)
150 .collect::<Vec<_>>()
151 .into_iter()
152 .rev()
153 .collect();
154
155 format!("{head}…{tail}")
156}
157
158pub fn head_tail_truncate(value: &str, max_chars: usize, marker: &str) -> (String, bool) {
172 const SUFFIX: &str = " [truncated]";
173
174 let total_chars = value.chars().count();
175 if total_chars <= max_chars {
176 return (value.to_string(), false);
177 }
178
179 let marker_chars = marker.chars().count();
180 if max_chars <= marker_chars + 16 {
181 let suffix_len = SUFFIX.chars().count();
182 let truncated = if max_chars > suffix_len {
183 let available = max_chars - suffix_len;
184 let mut result = value.chars().take(available).collect::<String>();
185 result.push_str(SUFFIX);
186 result
187 } else {
188 value.chars().take(max_chars).collect::<String>()
189 };
190 return (truncated, true);
191 }
192
193 let available = max_chars.saturating_sub(marker_chars);
194 let head_chars = (available * 2) / 3;
195 let tail_chars = available.saturating_sub(head_chars);
196 let head = value.chars().take(head_chars).collect::<String>();
197 let tail = value.chars().skip(total_chars.saturating_sub(tail_chars)).collect::<String>();
198 let mut truncated = String::with_capacity(max_chars + 20);
199 truncated.push_str(&head);
200 truncated.push_str(marker);
201 truncated.push_str(&tail);
202 (truncated, true)
203}
204
205pub fn wrap_text_words(text: &str, first_width: usize, continuation_width: usize) -> Vec<String> {
219 let trimmed = text.trim();
220 if trimmed.is_empty() {
221 return Vec::new();
222 }
223
224 let mut result = Vec::new();
225 let mut remaining = trimmed;
226 let mut width = first_width.max(1);
227
228 while remaining.chars().count() > width {
229 let split = split_at_word_boundary(remaining, width);
230 let (head, tail) = remaining.split_at(split);
231 let head = head.trim();
232 if head.is_empty() {
233 break;
234 }
235 result.push(head.to_string());
236 remaining = tail.trim_start();
237 if remaining.is_empty() {
238 break;
239 }
240 width = continuation_width.max(1);
241 }
242
243 if !remaining.is_empty() {
244 result.push(remaining.to_string());
245 }
246 result
247}
248
249fn split_at_word_boundary(input: &str, width: usize) -> usize {
250 let mut last_space: Option<usize> = None;
251 for (seen, (idx, ch)) in input.char_indices().enumerate() {
252 if seen > width {
253 break;
254 }
255 if ch.is_whitespace() {
256 last_space = Some(idx);
257 }
258 }
259 match last_space {
260 Some(pos) => pos,
261 None => byte_index_for_char_count(input, width),
262 }
263}
264
265fn byte_index_for_char_count(input: &str, chars: usize) -> usize {
266 if chars == 0 {
267 return 0;
268 }
269 let mut seen = 0usize;
270 for (idx, ch) in input.char_indices() {
271 seen += 1;
272 if seen == chars {
273 return idx + ch.len_utf8();
274 }
275 }
276 input.len()
277}
278
279pub fn truncate_byte_budget(text: &str, max_bytes: usize, suffix: &str) -> String {
283 if text.len() <= max_bytes {
284 return text.to_string();
285 }
286 let mut end = max_bytes.min(text.len());
287 while end > 0 && !text.is_char_boundary(end) {
288 end -= 1;
289 }
290 format!("{}{suffix}", &text[..end])
291}
292
293#[inline]
301pub fn collapse_whitespace(text: &str) -> String {
302 let mut result = String::with_capacity(text.len());
303 let mut pending_space = false;
304 for ch in text.chars() {
305 if ch.is_whitespace() {
306 pending_space = true;
307 } else {
308 if pending_space && !result.is_empty() {
309 result.push(' ');
310 }
311 result.push(ch);
312 pending_space = false;
313 }
314 }
315 result
316}
317
318pub fn clean_reasoning_text(text: &str) -> String {
327 text.lines()
328 .map(str::trim_end)
329 .filter(|line| !line.trim().is_empty())
330 .collect::<Vec<_>>()
331 .join("\n")
332}
333
334pub fn compact_reasoning_text(text: &str) -> String {
350 let mut out: Vec<&str> = Vec::with_capacity(text.lines().count());
351 let mut prev_blank = false;
352 for line in text.lines() {
353 let trimmed = line.trim();
354 let is_blank = trimmed.is_empty();
355 if is_blank {
356 if prev_blank {
357 continue;
358 }
359 out.push("");
360 prev_blank = true;
361 } else {
362 out.push(trimmed);
363 prev_blank = false;
364 }
365 }
366 while out.first().is_some_and(|l| l.trim().is_empty()) {
367 out.remove(0);
368 }
369 while out.last().is_some_and(|l| l.trim().is_empty()) {
370 out.pop();
371 }
372 out.join("\n")
373}
374
375#[cfg(test)]
376mod tests {
377 use super::*;
378
379 #[test]
380 fn truncate_byte_budget_ascii() {
381 assert_eq!(truncate_byte_budget("hello world", 5, "..."), "hello...");
382 assert_eq!(truncate_byte_budget("hi", 10, "..."), "hi");
383 }
384
385 #[test]
386 fn truncate_byte_budget_cjk_no_panic() {
387 let jp = "こんにちは";
389 assert_eq!(truncate_byte_budget(jp, 5, "…"), "こ…");
391 assert_eq!(truncate_byte_budget(jp, 6, "…"), "こん…");
393 }
394
395 #[test]
396 fn truncate_byte_budget_mixed_ascii_cjk() {
397 let mixed = "AB日本語CD";
398 assert_eq!(truncate_byte_budget(mixed, 4, ".."), "AB.."); assert_eq!(truncate_byte_budget(mixed, 5, ".."), "AB日.."); }
402
403 #[test]
404 fn truncate_byte_budget_emoji() {
405 let emoji = "👋🌍"; assert_eq!(truncate_byte_budget(emoji, 5, "!"), "👋!");
407 }
408
409 #[test]
410 fn truncate_byte_budget_zero() {
411 assert_eq!(truncate_byte_budget("abc", 0, "..."), "...");
412 }
413
414 #[test]
415 fn compact_reasoning_text_collapses_blank_runs() {
416 assert_eq!(compact_reasoning_text("line1\n\n\n\nline2\n"), "line1\n\nline2");
417 assert_eq!(compact_reasoning_text("a\n\n\n\n\n\nb"), "a\n\nb");
418 }
419
420 #[test]
421 fn compact_reasoning_text_preserves_single_paragraph_breaks() {
422 assert_eq!(compact_reasoning_text("para one\n\npara two\n"), "para one\n\npara two");
423 }
424
425 #[test]
426 fn compact_reasoning_text_trims_trailing_whitespace() {
427 assert_eq!(compact_reasoning_text(" a \n\n\n b \n"), "a\n\nb");
428 }
429
430 #[test]
431 fn compact_reasoning_text_strips_leading_trailing_blanks() {
432 assert_eq!(compact_reasoning_text("\n\n\nmid\n\n\n"), "mid");
433 assert_eq!(compact_reasoning_text("\n\n\n"), "");
434 assert_eq!(compact_reasoning_text(""), "");
435 }
436
437 #[test]
438 fn wrap_text_words_basic_and_continuation_width() {
439 assert_eq!(wrap_text_words("the quick brown fox", 9, 9), vec!["the quick", "brown fox"]);
440 assert_eq!(wrap_text_words("alpha beta gamma delta", 11, 5), vec!["alpha beta", "gamma", "delta"]);
442 }
443
444 #[test]
445 fn wrap_text_words_blank_and_unicode() {
446 assert!(wrap_text_words(" ", 5, 5).is_empty());
447 let wrapped = wrap_text_words("あいう えお かきく", 3, 3);
449 assert_eq!(wrapped, vec!["あいう", "えお", "かきく"]);
450 }
451
452 #[test]
453 fn truncate_within_reserves_ellipsis_budget() {
454 assert_eq!(truncate_within("hello world", 8, "..."), "hello...");
456 assert_eq!(truncate_within("hi", 8, "..."), "hi");
457 assert_eq!(truncate_within("abcdef", 4, "…"), "abc…");
460 }
461
462 #[test]
463 fn truncate_within_counts_chars() {
464 let jp = "あいうえお"; assert_eq!(truncate_within(jp, 5, "…"), jp);
466 assert_eq!(truncate_within(jp, 3, "…"), "あい…");
467 }
468
469 #[test]
470 fn head_tail_truncate_keeps_both_ends() {
471 let value = "0123456789".repeat(10); let (out, truncated) = head_tail_truncate(&value, 40, " ... [truncated] ... ");
473 assert!(truncated);
474 assert!(out.chars().count() <= 40);
475 assert!(out.starts_with("012"));
476 assert!(out.contains("[truncated]"));
477 assert!(out.ends_with('9'));
478 }
479
480 #[test]
481 fn head_tail_truncate_passes_through_when_short() {
482 let (out, truncated) = head_tail_truncate("short", 64, " ... ");
483 assert_eq!(out, "short");
484 assert!(!truncated);
485 }
486
487 #[test]
488 fn head_tail_truncate_small_budget_falls_back_to_prefix() {
489 let marker = " ... [truncated] ... ";
490 let (out, truncated) = head_tail_truncate("abcdefghij", 5, marker);
493 assert!(truncated);
494 assert_eq!(out, "abcde");
495
496 let long_text = "abcdefghijklmnopqrstuvwxyz";
499 let (out2, truncated2) = head_tail_truncate(long_text, 17, marker);
500 assert!(truncated2);
501 assert_eq!(out2, "abcde [truncated]");
502 assert_eq!(out2.chars().count(), 17);
503 }
504
505 #[test]
506 fn truncate_text_counts_chars_not_bytes() {
507 let jp = "あいうえお"; assert_eq!(truncate_text(jp, 3, "…"), "あいう…");
509 assert_eq!(truncate_text(jp, 5, "…"), "あいうえお");
510 }
511
512 #[test]
513 fn truncate_middle_keeps_both_ends() {
514 assert_eq!(truncate_middle("short", 80), "short");
515 assert_eq!(truncate_middle("abcdefghij", 5), "ab…ij");
516 assert_eq!(truncate_middle("a b c", 80), "a b c");
517 assert_eq!(truncate_middle("abc", 0), "");
519 assert_eq!(truncate_middle("abc", 1), "…");
520 assert_eq!(truncate_middle("a\nb\tc", 80), "a b c");
522 }
523
524 #[test]
525 fn truncate_path_middle_breaks_at_separator() {
526 assert_eq!(truncate_path_middle("src/lib.rs", 80), "src/lib.rs");
527 assert_eq!(truncate_path_middle("foo/bar/baz/qux", 12), "foo…/qux");
528 assert_eq!(truncate_path_middle("abc", 0), "");
529 }
530}