1use std::fmt::Write;
9
10pub const MAX_VIEW_BYTES: usize = 256 * 1024;
17
18pub const MAX_HEX_BYTES: usize = 64 * 1024;
24
25const HEX_COLUMNS: usize = 16;
27
28#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum ViewerContent {
31 Text(String),
33 Binary(String),
35}
36
37impl ViewerContent {
38 pub fn body(&self) -> &str {
40 match self {
41 Self::Text(text) | Self::Binary(text) => text,
42 }
43 }
44
45 pub const fn kind(&self) -> &'static str {
47 match self {
48 Self::Text(_) => "text",
49 Self::Binary(_) => "binary",
50 }
51 }
52}
53
54#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct FileView {
57 pub content: ViewerContent,
58 pub truncated: bool,
60}
61
62impl FileView {
63 pub fn from_bytes(bytes: &[u8]) -> Self {
70 let mut truncated = bytes.len() > MAX_VIEW_BYTES;
71 let head = &bytes[..bytes.len().min(MAX_VIEW_BYTES)];
72
73 let content = match decode_text(head, truncated) {
74 Some(text) => ViewerContent::Text(text),
75 None => {
76 truncated |= head.len() > MAX_HEX_BYTES;
79 ViewerContent::Binary(hex_dump(&head[..head.len().min(MAX_HEX_BYTES)]))
80 }
81 };
82
83 Self { content, truncated }
84 }
85
86 pub const fn is_binary(&self) -> bool {
87 matches!(self.content, ViewerContent::Binary(_))
88 }
89
90 pub fn line_count(&self) -> usize {
92 self.content.body().lines().count()
93 }
94}
95
96fn decode_text(bytes: &[u8], truncated: bool) -> Option<String> {
101 let text = match std::str::from_utf8(bytes) {
102 Ok(text) => text,
103 Err(error) if truncated && error.error_len().is_none() => {
108 std::str::from_utf8(&bytes[..error.valid_up_to()]).ok()?
109 }
110 Err(_) => return None,
111 };
112
113 if text.chars().any(is_disallowed_control) {
114 return None;
115 }
116 Some(text.to_string())
117}
118
119fn is_disallowed_control(c: char) -> bool {
123 c.is_control() && !matches!(c, '\t' | '\n' | '\r')
124}
125
126fn hex_dump(bytes: &[u8]) -> String {
129 let mut out = String::new();
130
131 for (row, chunk) in bytes.chunks(HEX_COLUMNS).enumerate() {
132 let offset = row * HEX_COLUMNS;
133 let _ = write!(out, "{offset:08x} ");
134
135 for column in 0..HEX_COLUMNS {
136 match chunk.get(column) {
137 Some(byte) => {
138 let _ = write!(out, "{byte:02x} ");
139 }
140 None => out.push_str(" "),
142 }
143 if column == HEX_COLUMNS / 2 - 1 {
144 out.push(' ');
145 }
146 }
147
148 out.push_str(" |");
149 for byte in chunk {
150 let printable = byte.is_ascii_graphic() || *byte == b' ';
151 out.push(if printable { *byte as char } else { '.' });
152 }
153 out.push_str("|\n");
154 }
155
156 out
157}
158
159#[cfg(test)]
160mod tests {
161 use super::*;
162
163 #[test]
164 fn utf8_content_is_text() {
165 let view = FileView::from_bytes("hello\nwörld\tagain\r\n".as_bytes());
166
167 assert_eq!(
168 view.content,
169 ViewerContent::Text("hello\nwörld\tagain\r\n".to_string())
170 );
171 assert!(!view.truncated);
172 }
173
174 #[test]
175 fn empty_file_is_empty_text() {
176 let view = FileView::from_bytes(&[]);
177
178 assert_eq!(view.content, ViewerContent::Text(String::new()));
179 assert!(!view.truncated);
180 }
181
182 #[test]
183 fn invalid_utf8_is_binary() {
184 let view = FileView::from_bytes(&[0xff, 0xfe, 0x41]);
186
187 assert!(view.is_binary());
188 }
189
190 #[test]
191 fn embedded_nul_is_binary_despite_valid_utf8() {
192 let view = FileView::from_bytes(b"ELF\0\x01\x02plain ascii");
193
194 assert!(view.is_binary());
195 }
196
197 #[test]
198 fn binary_content_renders_as_offset_hex_and_ascii() {
199 let view = FileView::from_bytes(b"\0AB");
200
201 assert_eq!(
202 view.content.body(),
203 "00000000 00 41 42 |.AB|\n"
204 );
205 }
206
207 #[test]
208 fn hex_dump_starts_a_new_line_every_sixteen_bytes() {
209 let mut bytes = vec![0u8; 20];
210 bytes[16] = b'x';
211 let view = FileView::from_bytes(&bytes);
212
213 let lines: Vec<&str> = view.content.body().lines().collect();
214 assert_eq!(lines.len(), 2);
215 assert!(lines[1].starts_with("00000010 78 00 00 00"));
216 }
217
218 #[test]
219 fn oversize_input_is_capped_and_flagged() {
220 let bytes = vec![b'a'; MAX_VIEW_BYTES + 1];
221 let view = FileView::from_bytes(&bytes);
222
223 assert!(view.truncated);
224 assert_eq!(view.content.body().len(), MAX_VIEW_BYTES);
225 }
226
227 #[test]
228 fn input_exactly_at_the_cap_is_not_flagged() {
229 let bytes = vec![b'a'; MAX_VIEW_BYTES];
230 let view = FileView::from_bytes(&bytes);
231
232 assert!(!view.truncated);
233 assert_eq!(view.content.body().len(), MAX_VIEW_BYTES);
234 }
235
236 #[test]
237 fn character_sliced_by_the_cap_still_reads_as_text() {
238 let mut bytes = vec![b'a'; MAX_VIEW_BYTES - 1];
241 bytes.extend_from_slice("é".as_bytes());
242
243 let view = FileView::from_bytes(&bytes);
244
245 assert!(view.truncated);
246 assert!(!view.is_binary());
247 assert_eq!(view.content.body().len(), MAX_VIEW_BYTES - 1);
249 }
250
251 #[test]
252 fn oversize_binary_is_capped_to_the_hex_window_and_flagged() {
253 let bytes = vec![0u8; MAX_HEX_BYTES + 1];
255 let view = FileView::from_bytes(&bytes);
256
257 assert!(view.is_binary());
258 assert!(view.truncated);
259 assert_eq!(view.line_count(), MAX_HEX_BYTES / HEX_COLUMNS);
260 }
261
262 #[test]
263 fn line_count_reflects_the_body() {
264 let view = FileView::from_bytes(b"one\ntwo\nthree\n");
265
266 assert_eq!(view.line_count(), 3);
267 }
268}