use crate::highlight::{detect_language, Language};
use std::fmt::Write;
pub const MAX_VIEW_BYTES: usize = 256 * 1024;
pub const MAX_HEX_BYTES: usize = 64 * 1024;
const HEX_COLUMNS: usize = 16;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ViewerContent {
Text(String),
Binary(String),
}
impl ViewerContent {
pub fn body(&self) -> &str {
match self {
Self::Text(text) | Self::Binary(text) => text,
}
}
pub const fn kind(&self) -> &'static str {
match self {
Self::Text(_) => "text",
Self::Binary(_) => "binary",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileView {
pub content: ViewerContent,
pub truncated: bool,
pub language: Option<Language>,
}
impl FileView {
pub fn from_bytes(bytes: &[u8]) -> Self {
let mut truncated = bytes.len() > MAX_VIEW_BYTES;
let head = &bytes[..bytes.len().min(MAX_VIEW_BYTES)];
let content = match decode_text(head, truncated) {
Some(text) => ViewerContent::Text(text),
None => {
truncated |= head.len() > MAX_HEX_BYTES;
ViewerContent::Binary(hex_dump(&head[..head.len().min(MAX_HEX_BYTES)]))
}
};
Self {
content,
truncated,
language: None,
}
}
pub fn from_file(name: &str, bytes: &[u8]) -> Self {
let mut view = Self::from_bytes(bytes);
if let ViewerContent::Text(text) = &view.content {
view.language = detect_language(name, text.lines().next().unwrap_or(""));
}
view
}
pub const fn is_binary(&self) -> bool {
matches!(self.content, ViewerContent::Binary(_))
}
pub fn line_count(&self) -> usize {
self.content.body().lines().count()
}
}
fn decode_text(bytes: &[u8], truncated: bool) -> Option<String> {
let text = match std::str::from_utf8(bytes) {
Ok(text) => text,
Err(error) if truncated && error.error_len().is_none() => {
std::str::from_utf8(&bytes[..error.valid_up_to()]).ok()?
}
Err(_) => return None,
};
if text.chars().any(is_disallowed_control) {
return None;
}
Some(text.to_string())
}
fn is_disallowed_control(c: char) -> bool {
c.is_control() && !matches!(c, '\t' | '\n' | '\r')
}
fn hex_dump(bytes: &[u8]) -> String {
let mut out = String::new();
for (row, chunk) in bytes.chunks(HEX_COLUMNS).enumerate() {
let offset = row * HEX_COLUMNS;
let _ = write!(out, "{offset:08x} ");
for column in 0..HEX_COLUMNS {
match chunk.get(column) {
Some(byte) => {
let _ = write!(out, "{byte:02x} ");
}
None => out.push_str(" "),
}
if column == HEX_COLUMNS / 2 - 1 {
out.push(' ');
}
}
out.push_str(" |");
for byte in chunk {
let printable = byte.is_ascii_graphic() || *byte == b' ';
out.push(if printable { *byte as char } else { '.' });
}
out.push_str("|\n");
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_file_detects_the_language_of_text() {
let view = FileView::from_file("Cargo.toml", b"[package]\nname = \"x\"\n");
assert_eq!(view.language.as_ref().map(|l| l.name()), Some("TOML"));
let script = FileView::from_file("deploy", b"#!/usr/bin/env bash\necho hi\n");
assert!(script.language.is_some());
}
#[test]
fn binary_content_has_no_language() {
let view = FileView::from_file("main.rs", &[0, 1, 2, 3, 0xff]);
assert!(view.is_binary());
assert_eq!(view.language, None);
}
#[test]
fn utf8_content_is_text() {
let view = FileView::from_bytes("hello\nwörld\tagain\r\n".as_bytes());
assert_eq!(
view.content,
ViewerContent::Text("hello\nwörld\tagain\r\n".to_string())
);
assert!(!view.truncated);
}
#[test]
fn empty_file_is_empty_text() {
let view = FileView::from_bytes(&[]);
assert_eq!(view.content, ViewerContent::Text(String::new()));
assert!(!view.truncated);
}
#[test]
fn invalid_utf8_is_binary() {
let view = FileView::from_bytes(&[0xff, 0xfe, 0x41]);
assert!(view.is_binary());
}
#[test]
fn embedded_nul_is_binary_despite_valid_utf8() {
let view = FileView::from_bytes(b"ELF\0\x01\x02plain ascii");
assert!(view.is_binary());
}
#[test]
fn binary_content_renders_as_offset_hex_and_ascii() {
let view = FileView::from_bytes(b"\0AB");
assert_eq!(
view.content.body(),
"00000000 00 41 42 |.AB|\n"
);
}
#[test]
fn hex_dump_starts_a_new_line_every_sixteen_bytes() {
let mut bytes = vec![0u8; 20];
bytes[16] = b'x';
let view = FileView::from_bytes(&bytes);
let lines: Vec<&str> = view.content.body().lines().collect();
assert_eq!(lines.len(), 2);
assert!(lines[1].starts_with("00000010 78 00 00 00"));
}
#[test]
fn oversize_input_is_capped_and_flagged() {
let bytes = vec![b'a'; MAX_VIEW_BYTES + 1];
let view = FileView::from_bytes(&bytes);
assert!(view.truncated);
assert_eq!(view.content.body().len(), MAX_VIEW_BYTES);
}
#[test]
fn input_exactly_at_the_cap_is_not_flagged() {
let bytes = vec![b'a'; MAX_VIEW_BYTES];
let view = FileView::from_bytes(&bytes);
assert!(!view.truncated);
assert_eq!(view.content.body().len(), MAX_VIEW_BYTES);
}
#[test]
fn character_sliced_by_the_cap_still_reads_as_text() {
let mut bytes = vec![b'a'; MAX_VIEW_BYTES - 1];
bytes.extend_from_slice("é".as_bytes());
let view = FileView::from_bytes(&bytes);
assert!(view.truncated);
assert!(!view.is_binary());
assert_eq!(view.content.body().len(), MAX_VIEW_BYTES - 1);
}
#[test]
fn oversize_binary_is_capped_to_the_hex_window_and_flagged() {
let bytes = vec![0u8; MAX_HEX_BYTES + 1];
let view = FileView::from_bytes(&bytes);
assert!(view.is_binary());
assert!(view.truncated);
assert_eq!(view.line_count(), MAX_HEX_BYTES / HEX_COLUMNS);
}
#[test]
fn line_count_reflects_the_body() {
let view = FileView::from_bytes(b"one\ntwo\nthree\n");
assert_eq!(view.line_count(), 3);
}
}