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_chars: Vec<char> = path.chars().take(head_budget).collect();
136 let head_str: String = head_chars.iter().collect();
137 let head_break = head_str.rfind('/').unwrap_or(head_budget);
138
139 let tail_chars: Vec<char> = path.chars().rev().take(tail_budget).collect();
141 let tail_str: String = tail_chars.iter().rev().collect();
142 let tail_break_from_end = tail_str.find('/').map(|pos| tail_str.len() - pos).unwrap_or(tail_budget);
143
144 let head: String = path.chars().take(head_break).collect();
145 let tail: String = path
146 .chars()
147 .rev()
148 .take(tail_break_from_end)
149 .collect::<Vec<_>>()
150 .into_iter()
151 .rev()
152 .collect();
153
154 format!("{head}…{tail}")
155}
156
157pub fn head_tail_truncate(value: &str, max_chars: usize, marker: &str) -> (String, bool) {
171 const SUFFIX: &str = " [truncated]";
172
173 let total_chars = value.chars().count();
174 if total_chars <= max_chars {
175 return (value.to_string(), false);
176 }
177
178 let marker_chars = marker.chars().count();
179 if max_chars <= marker_chars + 16 {
180 let suffix_len = SUFFIX.chars().count();
181 let truncated = if max_chars > suffix_len {
182 let available = max_chars - suffix_len;
183 let mut result = value.chars().take(available).collect::<String>();
184 result.push_str(SUFFIX);
185 result
186 } else {
187 value.chars().take(max_chars).collect::<String>()
188 };
189 return (truncated, true);
190 }
191
192 let available = max_chars.saturating_sub(marker_chars);
193 let head_chars = (available * 2) / 3;
194 let tail_chars = available.saturating_sub(head_chars);
195 let head = value.chars().take(head_chars).collect::<String>();
196 let tail = value.chars().skip(total_chars.saturating_sub(tail_chars)).collect::<String>();
197 let mut truncated = String::with_capacity(max_chars + 20);
198 truncated.push_str(&head);
199 truncated.push_str(marker);
200 truncated.push_str(&tail);
201 (truncated, true)
202}
203
204pub fn wrap_text_words(text: &str, first_width: usize, continuation_width: usize) -> Vec<String> {
218 let trimmed = text.trim();
219 if trimmed.is_empty() {
220 return Vec::new();
221 }
222
223 let mut result = Vec::new();
224 let mut remaining = trimmed;
225 let mut width = first_width.max(1);
226
227 while remaining.chars().count() > width {
228 let split = split_at_word_boundary(remaining, width);
229 let (head, tail) = remaining.split_at(split);
230 let head = head.trim();
231 if head.is_empty() {
232 break;
233 }
234 result.push(head.to_string());
235 remaining = tail.trim_start();
236 if remaining.is_empty() {
237 break;
238 }
239 width = continuation_width.max(1);
240 }
241
242 if !remaining.is_empty() {
243 result.push(remaining.to_string());
244 }
245 result
246}
247
248fn split_at_word_boundary(input: &str, width: usize) -> usize {
249 let mut last_space: Option<usize> = None;
250 for (seen, (idx, ch)) in input.char_indices().enumerate() {
251 if seen > width {
252 break;
253 }
254 if ch.is_whitespace() {
255 last_space = Some(idx);
256 }
257 }
258 match last_space {
259 Some(pos) => pos,
260 None => byte_index_for_char_count(input, width),
261 }
262}
263
264fn byte_index_for_char_count(input: &str, chars: usize) -> usize {
265 if chars == 0 {
266 return 0;
267 }
268 let mut seen = 0usize;
269 for (idx, ch) in input.char_indices() {
270 seen += 1;
271 if seen == chars {
272 return idx + ch.len_utf8();
273 }
274 }
275 input.len()
276}
277
278pub fn truncate_byte_budget(text: &str, max_bytes: usize, suffix: &str) -> String {
282 if text.len() <= max_bytes {
283 return text.to_string();
284 }
285 let mut end = max_bytes.min(text.len());
286 while end > 0 && !text.is_char_boundary(end) {
287 end -= 1;
288 }
289 format!("{}{suffix}", &text[..end])
290}
291
292#[inline]
300pub fn collapse_whitespace(text: &str) -> String {
301 let mut result = String::with_capacity(text.len());
302 let mut pending_space = false;
303 for ch in text.chars() {
304 if ch.is_whitespace() {
305 pending_space = true;
306 } else {
307 if pending_space && !result.is_empty() {
308 result.push(' ');
309 }
310 result.push(ch);
311 pending_space = false;
312 }
313 }
314 result
315}
316
317pub fn clean_reasoning_text(text: &str) -> String {
326 text.lines()
327 .map(str::trim_end)
328 .filter(|line| !line.trim().is_empty())
329 .collect::<Vec<_>>()
330 .join("\n")
331}
332
333pub fn compact_reasoning_text(text: &str) -> String {
349 let mut out: Vec<&str> = Vec::with_capacity(text.lines().count());
350 let mut prev_blank = false;
351 for line in text.lines() {
352 let trimmed = line.trim();
353 let is_blank = trimmed.is_empty();
354 if is_blank {
355 if prev_blank {
356 continue;
357 }
358 out.push("");
359 prev_blank = true;
360 } else {
361 out.push(trimmed);
362 prev_blank = false;
363 }
364 }
365 while out.first().is_some_and(|l| l.trim().is_empty()) {
366 out.remove(0);
367 }
368 while out.last().is_some_and(|l| l.trim().is_empty()) {
369 out.pop();
370 }
371 out.join("\n")
372}
373
374#[cfg(test)]
375mod tests {
376 use super::*;
377
378 #[test]
379 fn truncate_byte_budget_ascii() {
380 assert_eq!(truncate_byte_budget("hello world", 5, "..."), "hello...");
381 assert_eq!(truncate_byte_budget("hi", 10, "..."), "hi");
382 }
383
384 #[test]
385 fn truncate_byte_budget_cjk_no_panic() {
386 let jp = "こんにちは";
388 assert_eq!(truncate_byte_budget(jp, 5, "…"), "こ…");
390 assert_eq!(truncate_byte_budget(jp, 6, "…"), "こん…");
392 }
393
394 #[test]
395 fn truncate_byte_budget_mixed_ascii_cjk() {
396 let mixed = "AB日本語CD";
397 assert_eq!(truncate_byte_budget(mixed, 4, ".."), "AB.."); assert_eq!(truncate_byte_budget(mixed, 5, ".."), "AB日.."); }
401
402 #[test]
403 fn truncate_byte_budget_emoji() {
404 let emoji = "👋🌍"; assert_eq!(truncate_byte_budget(emoji, 5, "!"), "👋!");
406 }
407
408 #[test]
409 fn truncate_byte_budget_zero() {
410 assert_eq!(truncate_byte_budget("abc", 0, "..."), "...");
411 }
412
413 #[test]
414 fn compact_reasoning_text_collapses_blank_runs() {
415 assert_eq!(compact_reasoning_text("line1\n\n\n\nline2\n"), "line1\n\nline2");
416 assert_eq!(compact_reasoning_text("a\n\n\n\n\n\nb"), "a\n\nb");
417 }
418
419 #[test]
420 fn compact_reasoning_text_preserves_single_paragraph_breaks() {
421 assert_eq!(compact_reasoning_text("para one\n\npara two\n"), "para one\n\npara two");
422 }
423
424 #[test]
425 fn compact_reasoning_text_trims_trailing_whitespace() {
426 assert_eq!(compact_reasoning_text(" a \n\n\n b \n"), "a\n\nb");
427 }
428
429 #[test]
430 fn compact_reasoning_text_strips_leading_trailing_blanks() {
431 assert_eq!(compact_reasoning_text("\n\n\nmid\n\n\n"), "mid");
432 assert_eq!(compact_reasoning_text("\n\n\n"), "");
433 assert_eq!(compact_reasoning_text(""), "");
434 }
435
436 #[test]
437 fn wrap_text_words_basic_and_continuation_width() {
438 assert_eq!(wrap_text_words("the quick brown fox", 9, 9), vec!["the quick", "brown fox"]);
439 assert_eq!(wrap_text_words("alpha beta gamma delta", 11, 5), vec!["alpha beta", "gamma", "delta"]);
441 }
442
443 #[test]
444 fn wrap_text_words_blank_and_unicode() {
445 assert!(wrap_text_words(" ", 5, 5).is_empty());
446 let wrapped = wrap_text_words("あいう えお かきく", 3, 3);
448 assert_eq!(wrapped, vec!["あいう", "えお", "かきく"]);
449 }
450
451 #[test]
452 fn truncate_within_reserves_ellipsis_budget() {
453 assert_eq!(truncate_within("hello world", 8, "..."), "hello...");
455 assert_eq!(truncate_within("hi", 8, "..."), "hi");
456 assert_eq!(truncate_within("abcdef", 4, "…"), "abc…");
459 }
460
461 #[test]
462 fn truncate_within_counts_chars() {
463 let jp = "あいうえお"; assert_eq!(truncate_within(jp, 5, "…"), jp);
465 assert_eq!(truncate_within(jp, 3, "…"), "あい…");
466 }
467
468 #[test]
469 fn head_tail_truncate_keeps_both_ends() {
470 let value = "0123456789".repeat(10); let (out, truncated) = head_tail_truncate(&value, 40, " ... [truncated] ... ");
472 assert!(truncated);
473 assert!(out.chars().count() <= 40);
474 assert!(out.starts_with("012"));
475 assert!(out.contains("[truncated]"));
476 assert!(out.ends_with('9'));
477 }
478
479 #[test]
480 fn head_tail_truncate_passes_through_when_short() {
481 let (out, truncated) = head_tail_truncate("short", 64, " ... ");
482 assert_eq!(out, "short");
483 assert!(!truncated);
484 }
485
486 #[test]
487 fn head_tail_truncate_small_budget_falls_back_to_prefix() {
488 let marker = " ... [truncated] ... ";
489 let (out, truncated) = head_tail_truncate("abcdefghij", 5, marker);
492 assert!(truncated);
493 assert_eq!(out, "abcde");
494
495 let long_text = "abcdefghijklmnopqrstuvwxyz";
498 let (out2, truncated2) = head_tail_truncate(long_text, 17, marker);
499 assert!(truncated2);
500 assert_eq!(out2, "abcde [truncated]");
501 assert_eq!(out2.chars().count(), 17);
502 }
503
504 #[test]
505 fn truncate_text_counts_chars_not_bytes() {
506 let jp = "あいうえお"; assert_eq!(truncate_text(jp, 3, "…"), "あいう…");
508 assert_eq!(truncate_text(jp, 5, "…"), "あいうえお");
509 }
510
511 #[test]
512 fn truncate_middle_keeps_both_ends() {
513 assert_eq!(truncate_middle("short", 80), "short");
514 assert_eq!(truncate_middle("abcdefghij", 5), "ab…ij");
515 assert_eq!(truncate_middle("a b c", 80), "a b c");
516 assert_eq!(truncate_middle("abc", 0), "");
518 assert_eq!(truncate_middle("abc", 1), "…");
519 assert_eq!(truncate_middle("a\nb\tc", 80), "a b c");
521 }
522
523 #[test]
524 fn truncate_path_middle_breaks_at_separator() {
525 assert_eq!(truncate_path_middle("src/lib.rs", 80), "src/lib.rs");
526 assert_eq!(truncate_path_middle("foo/bar/baz/qux", 12), "foo…/qux");
527 assert_eq!(truncate_path_middle("abc", 0), "");
528 }
529}