1use std::borrow::Cow;
2
3pub const MAX_STORED_PREVIEW_RUNES: usize = 128;
4
5pub fn build_preview_data(buf: &[u8], chars: usize) -> String {
6 if buf.is_empty() {
7 return String::new();
8 }
9 let limit = if chars == 0 || chars > MAX_STORED_PREVIEW_RUNES {
10 MAX_STORED_PREVIEW_RUNES
11 } else {
12 chars
13 };
14 build_text_preview(buf, limit)
15}
16
17fn build_text_preview(buf: &[u8], chars: usize) -> String {
18 let decoded: Cow<'_, str> = String::from_utf8_lossy(buf);
19 let mut out = String::new();
20 let mut last = None;
21 let mut count = 0usize;
22
23 for mut ch in decoded.chars() {
24 if count >= chars {
25 break;
26 }
27 ch = match ch {
28 '\u{FFFD}' => '.',
29 '\n' | '\r' | '\t' => ' ',
30 c if !c.is_control() => c,
31 _ => '.',
32 };
33 if last == Some(' ') && ch == ' ' {
34 continue;
35 }
36 out.push(ch);
37 last = Some(ch);
38 count += 1;
39 }
40
41 out.trim().to_string()
42}