//! Previews of files that are read as text: the first part of a text file, escaped by the page. Nothing //! here decides whether a file may be shown; the caller has checked the viewer kind and the caller's //! right to read the file. use std::io::Read; use std::path::Path; use crate::error::Result; /// Reads at most `cap` bytes of `path` as text. Returns the text (invalid UTF-8 replaced) and whether the file /// was longer than the cap. pub fn read_text_head(path: &Path, cap: u64) -> Result<(String, bool)> { let file = std::fs::File::open(path)?; let mut bytes = Vec::new(); file.take(cap + 1).read_to_end(&mut bytes)?; let truncated = bytes.len() as u64 > cap; bytes.truncate(usize::try_from(cap).unwrap_or(usize::MAX)); Ok((String::from_utf8_lossy(&bytes).into_owned(), truncated)) } #[cfg(test)] mod tests { use super::*; #[test] fn a_long_text_is_cut_and_says_so() { let dir = tempfile::tempdir().expect("dir"); let path = dir.path().join("long.txt"); std::fs::write(&path, "abcdef").expect("write"); assert_eq!( read_text_head(&path, 4).expect("head"), ("abcd".into(), true) ); assert_eq!( read_text_head(&path, 6).expect("head"), ("abcdef".into(), false) ); } }