oxinav-core 0.3.0

Core logic for OxiNav: file operations, pane state, archives and viewing, with no UI dependency
Documentation
//! Read-only file viewing: turning raw bytes into something displayable.
//!
//! The app reads a capped prefix of a file through the `Filesystem`
//! abstraction and hands the bytes here. This module decides whether they are
//! text or binary and prepares the exact string the view layer renders, so
//! that the UI keeps no branching logic of its own.

use std::fmt::Write;

/// The most bytes the viewer will hold for a single file.
///
/// Capped both so a multi-GB file is never slurped whole and so the modal
/// stays responsive: everything read is laid out as one text widget, and a
/// much larger cap makes opening the viewer visibly slow. Nothing depends on
/// the exact value — it is safe to tune.
pub const MAX_VIEW_BYTES: usize = 256 * 1024;

/// The most bytes rendered as a hex dump.
///
/// A dump runs about five characters per byte, so [`MAX_VIEW_BYTES`] of
/// binary would still hand the view layer megabytes of text to lay out in one
/// widget. This smaller window is still far more than anyone reads by eye.
pub const MAX_HEX_BYTES: usize = 64 * 1024;

/// Bytes per line of the hex dump.
const HEX_COLUMNS: usize = 16;

/// What the viewer found in a file, already formatted for display.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ViewerContent {
    /// Readable text, ready to render as-is.
    Text(String),
    /// An offset/hex/ASCII dump of bytes that are not readable text.
    Binary(String),
}

impl ViewerContent {
    /// The text to render, whichever form the content took.
    pub fn body(&self) -> &str {
        match self {
            Self::Text(text) | Self::Binary(text) => text,
        }
    }

    /// A short word for the content's kind, for the viewer's status line.
    pub const fn kind(&self) -> &'static str {
        match self {
            Self::Text(_) => "text",
            Self::Binary(_) => "binary",
        }
    }
}

/// A file prepared for read-only viewing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileView {
    pub content: ViewerContent,
    /// Whether the file held more than what `content` shows.
    pub truncated: bool,
}

impl FileView {
    /// Classify up to [`MAX_VIEW_BYTES`] of `bytes` and prepare them for
    /// display, flagging truncation when more was supplied than that.
    ///
    /// Callers that read from a real file should hand over `MAX_VIEW_BYTES + 1`
    /// bytes: the one extra byte is what distinguishes a file that exactly
    /// fills the cap from one that overruns it.
    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 => {
                // Binary gets the tighter cap, and dropping bytes to honour it
                // is truncation just the same.
                truncated |= head.len() > MAX_HEX_BYTES;
                ViewerContent::Binary(hex_dump(&head[..head.len().min(MAX_HEX_BYTES)]))
            }
        };

        Self { content, truncated }
    }

    pub const fn is_binary(&self) -> bool {
        matches!(self.content, ViewerContent::Binary(_))
    }

    /// How many lines the body occupies, for sizing the viewer's scroll.
    pub fn line_count(&self) -> usize {
        self.content.body().lines().count()
    }
}

/// Decode `bytes` as text, or `None` when they are not text.
///
/// Text means valid UTF-8 carrying no control characters beyond the ones that
/// structure a document.
fn decode_text(bytes: &[u8], truncated: bool) -> Option<String> {
    let text = match std::str::from_utf8(bytes) {
        Ok(text) => text,
        // A multi-byte character sliced through by the read cap is an
        // artefact of truncating, not evidence of binary content: keep the
        // valid prefix and drop the partial character. Any other decode
        // failure means these bytes really are not 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())
}

/// Whether `c` is a control character that marks its content as binary. Tab,
/// line feed and carriage return structure real text; NUL and the rest of the
/// control range do not.
fn is_disallowed_control(c: char) -> bool {
    c.is_control() && !matches!(c, '\t' | '\n' | '\r')
}

/// Render `bytes` as `offset  hex bytes  |ascii|` lines, the classic dump
/// layout, so binary content is inspectable instead of garbled.
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} ");
                }
                // Pad the final short row so the ASCII gutter stays aligned.
                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 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() {
        // A lone continuation byte is not valid UTF-8 anywhere.
        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() {
        // Fill to one byte short of the cap, then straddle it with a
        // two-byte character so the cap cuts the character in half.
        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());
        // The partial character is dropped rather than shown as garbage.
        assert_eq!(view.content.body().len(), MAX_VIEW_BYTES - 1);
    }

    #[test]
    fn oversize_binary_is_capped_to_the_hex_window_and_flagged() {
        // NUL keeps this classified as binary at any length.
        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);
    }
}