1use crate::highlight::{detect_language, Language};
9use std::fmt::Write;
10
11pub const MAX_VIEW_BYTES: usize = 256 * 1024;
18
19pub const MAX_HEX_BYTES: usize = 64 * 1024;
25
26const HEX_COLUMNS: usize = 16;
28
29#[derive(Debug, Clone, PartialEq, Eq)]
31pub enum ViewerContent {
32 Text(String),
34 Binary(String),
36}
37
38impl ViewerContent {
39 pub fn body(&self) -> &str {
41 match self {
42 Self::Text(text) | Self::Binary(text) => text,
43 }
44 }
45
46 pub const fn kind(&self) -> &'static str {
48 match self {
49 Self::Text(_) => "text",
50 Self::Binary(_) => "binary",
51 }
52 }
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct FileView {
58 pub content: ViewerContent,
59 pub truncated: bool,
61 pub language: Option<Language>,
63}
64
65impl FileView {
66 pub fn from_bytes(bytes: &[u8]) -> Self {
73 let mut truncated = bytes.len() > MAX_VIEW_BYTES;
74 let head = &bytes[..bytes.len().min(MAX_VIEW_BYTES)];
75
76 let content = match decode_text(head, truncated) {
77 Some(text) => ViewerContent::Text(text),
78 None => {
79 truncated |= head.len() > MAX_HEX_BYTES;
82 ViewerContent::Binary(hex_dump(&head[..head.len().min(MAX_HEX_BYTES)]))
83 }
84 };
85
86 Self {
87 content,
88 truncated,
89 language: None,
90 }
91 }
92
93 pub fn from_file(name: &str, bytes: &[u8]) -> Self {
96 let mut view = Self::from_bytes(bytes);
97 if let ViewerContent::Text(text) = &view.content {
98 view.language = detect_language(name, text.lines().next().unwrap_or(""));
99 }
100 view
101 }
102
103 pub const fn is_binary(&self) -> bool {
104 matches!(self.content, ViewerContent::Binary(_))
105 }
106
107 pub fn line_count(&self) -> usize {
109 self.content.body().lines().count()
110 }
111}
112
113fn decode_text(bytes: &[u8], truncated: bool) -> Option<String> {
118 let text = match std::str::from_utf8(bytes) {
119 Ok(text) => text,
120 Err(error) if truncated && error.error_len().is_none() => {
125 std::str::from_utf8(&bytes[..error.valid_up_to()]).ok()?
126 }
127 Err(_) => return None,
128 };
129
130 if text.chars().any(is_disallowed_control) {
131 return None;
132 }
133 Some(text.to_string())
134}
135
136fn is_disallowed_control(c: char) -> bool {
140 c.is_control() && !matches!(c, '\t' | '\n' | '\r')
141}
142
143fn hex_dump(bytes: &[u8]) -> String {
146 let mut out = String::new();
147
148 for (row, chunk) in bytes.chunks(HEX_COLUMNS).enumerate() {
149 let offset = row * HEX_COLUMNS;
150 let _ = write!(out, "{offset:08x} ");
151
152 for column in 0..HEX_COLUMNS {
153 match chunk.get(column) {
154 Some(byte) => {
155 let _ = write!(out, "{byte:02x} ");
156 }
157 None => out.push_str(" "),
159 }
160 if column == HEX_COLUMNS / 2 - 1 {
161 out.push(' ');
162 }
163 }
164
165 out.push_str(" |");
166 for byte in chunk {
167 let printable = byte.is_ascii_graphic() || *byte == b' ';
168 out.push(if printable { *byte as char } else { '.' });
169 }
170 out.push_str("|\n");
171 }
172
173 out
174}
175
176#[cfg(test)]
177mod tests {
178 use super::*;
179
180 #[test]
181 fn from_file_detects_the_language_of_text() {
182 let view = FileView::from_file("Cargo.toml", b"[package]\nname = \"x\"\n");
183 assert_eq!(view.language.as_ref().map(|l| l.name()), Some("TOML"));
184
185 let script = FileView::from_file("deploy", b"#!/usr/bin/env bash\necho hi\n");
186 assert!(script.language.is_some());
187 }
188
189 #[test]
190 fn binary_content_has_no_language() {
191 let view = FileView::from_file("main.rs", &[0, 1, 2, 3, 0xff]);
192 assert!(view.is_binary());
193 assert_eq!(view.language, None);
194 }
195
196 #[test]
197 fn utf8_content_is_text() {
198 let view = FileView::from_bytes("hello\nwörld\tagain\r\n".as_bytes());
199
200 assert_eq!(
201 view.content,
202 ViewerContent::Text("hello\nwörld\tagain\r\n".to_string())
203 );
204 assert!(!view.truncated);
205 }
206
207 #[test]
208 fn empty_file_is_empty_text() {
209 let view = FileView::from_bytes(&[]);
210
211 assert_eq!(view.content, ViewerContent::Text(String::new()));
212 assert!(!view.truncated);
213 }
214
215 #[test]
216 fn invalid_utf8_is_binary() {
217 let view = FileView::from_bytes(&[0xff, 0xfe, 0x41]);
219
220 assert!(view.is_binary());
221 }
222
223 #[test]
224 fn embedded_nul_is_binary_despite_valid_utf8() {
225 let view = FileView::from_bytes(b"ELF\0\x01\x02plain ascii");
226
227 assert!(view.is_binary());
228 }
229
230 #[test]
231 fn binary_content_renders_as_offset_hex_and_ascii() {
232 let view = FileView::from_bytes(b"\0AB");
233
234 assert_eq!(
235 view.content.body(),
236 "00000000 00 41 42 |.AB|\n"
237 );
238 }
239
240 #[test]
241 fn hex_dump_starts_a_new_line_every_sixteen_bytes() {
242 let mut bytes = vec![0u8; 20];
243 bytes[16] = b'x';
244 let view = FileView::from_bytes(&bytes);
245
246 let lines: Vec<&str> = view.content.body().lines().collect();
247 assert_eq!(lines.len(), 2);
248 assert!(lines[1].starts_with("00000010 78 00 00 00"));
249 }
250
251 #[test]
252 fn oversize_input_is_capped_and_flagged() {
253 let bytes = vec![b'a'; MAX_VIEW_BYTES + 1];
254 let view = FileView::from_bytes(&bytes);
255
256 assert!(view.truncated);
257 assert_eq!(view.content.body().len(), MAX_VIEW_BYTES);
258 }
259
260 #[test]
261 fn input_exactly_at_the_cap_is_not_flagged() {
262 let bytes = vec![b'a'; MAX_VIEW_BYTES];
263 let view = FileView::from_bytes(&bytes);
264
265 assert!(!view.truncated);
266 assert_eq!(view.content.body().len(), MAX_VIEW_BYTES);
267 }
268
269 #[test]
270 fn character_sliced_by_the_cap_still_reads_as_text() {
271 let mut bytes = vec![b'a'; MAX_VIEW_BYTES - 1];
274 bytes.extend_from_slice("é".as_bytes());
275
276 let view = FileView::from_bytes(&bytes);
277
278 assert!(view.truncated);
279 assert!(!view.is_binary());
280 assert_eq!(view.content.body().len(), MAX_VIEW_BYTES - 1);
282 }
283
284 #[test]
285 fn oversize_binary_is_capped_to_the_hex_window_and_flagged() {
286 let bytes = vec![0u8; MAX_HEX_BYTES + 1];
288 let view = FileView::from_bytes(&bytes);
289
290 assert!(view.is_binary());
291 assert!(view.truncated);
292 assert_eq!(view.line_count(), MAX_HEX_BYTES / HEX_COLUMNS);
293 }
294
295 #[test]
296 fn line_count_reflects_the_body() {
297 let view = FileView::from_bytes(b"one\ntwo\nthree\n");
298
299 assert_eq!(view.line_count(), 3);
300 }
301}