forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

preview.rs39 lines, 1.3 KiBHistoryRawDownload
1//! Previews of files that are read as text: the first part of a text file, escaped by the page. Nothing
2//! here decides whether a file may be shown; the caller has checked the viewer kind and the caller's
3//! right to read the file.
4
5use std::io::Read;
6use std::path::Path;
7
8use crate::error::Result;
9
10/// Reads at most `cap` bytes of `path` as text. Returns the text (invalid UTF-8 replaced) and whether the file
11/// was longer than the cap.
12pub fn read_text_head(path: &Path, cap: u64) -> Result<(String, bool)> {
13 let file = std::fs::File::open(path)?;
14 let mut bytes = Vec::new();
15 file.take(cap + 1).read_to_end(&mut bytes)?;
16 let truncated = bytes.len() as u64 > cap;
17 bytes.truncate(usize::try_from(cap).unwrap_or(usize::MAX));
18 Ok((String::from_utf8_lossy(&bytes).into_owned(), truncated))
19}
20
21#[cfg(test)]
22mod tests {
23 use super::*;
24
25 #[test]
26 fn a_long_text_is_cut_and_says_so() {
27 let dir = tempfile::tempdir().expect("dir");
28 let path = dir.path().join("long.txt");
29 std::fs::write(&path, "abcdef").expect("write");
30 assert_eq!(
31 read_text_head(&path, 4).expect("head"),
32 ("abcd".into(), true)
33 );
34 assert_eq!(
35 read_text_head(&path, 6).expect("head"),
36 ("abcdef".into(), false)
37 );
38 }
39}