ctb_formats_text_extraction/
text_extraction.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Text extraction utilities for arbitrary files and document formats.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29use std::fs::File;
30use std::io::Read;
31
32use ctb_formats_dcstring::DcString;
33
34/// Extracts text from a file up to an optional byte limit.
35///
36/// Reads up to `byte_limit` bytes from `file`. If the extracted bytes form valid
37/// UTF-8 text, the string is returned directly. If the buffer is truncated at
38/// a valid UTF-8 boundary before the byte limit, only the valid prefix is used.
39/// Otherwise, the bytes are passed to `wfscan` for scanning and tokenizing.
40pub fn to_text(file: &mut File, byte_limit: Option<usize>) -> Result<String> {
41    let mut buf = Vec::new();
42    if let Some(limit) = byte_limit {
43        let limit_u64 =
44            u64::try_from(limit).context("Byte limit exceeds u64")?;
45        let mut handle = file.take(limit_u64);
46        handle.read_to_end(&mut buf)?;
47    } else {
48        file.read_to_end(&mut buf)?;
49    }
50
51    match std::str::from_utf8(&buf) {
52        Ok(s) => Ok(s.to_string()),
53        Err(e)
54            if byte_limit.is_some()
55                && e.error_len().is_none()
56                && e.valid_up_to() > 0 =>
57        {
58            let valid_slice = buf
59                .get(..e.valid_up_to())
60                .context("Index out of bounds for valid UTF-8 prefix")?;
61            let s = std::str::from_utf8(valid_slice)?;
62            Ok(s.to_string())
63        }
64        Err(_) => {
65            let scanned = ctb_formats_wfscan::wfscan(&buf)?;
66            Ok(String::from_utf8_lossy(&scanned).into_owned())
67        }
68    }
69}
70
71/// Extracts text from a file in Dc format up to an optional byte limit.
72///
73/// Currently a passthrough wrapper around [`to_text`].
74pub fn to_dcstring(
75    file: &mut File,
76    byte_limit: Option<usize>,
77) -> Result<DcString> {
78    let text = to_text(file, byte_limit)?;
79    Ok(DcString::from(text))
80}
81
82#[cfg(test)]
83#[allow(
84    clippy::panic,
85    clippy::expect_used,
86    clippy::unwrap_used,
87    clippy::unwrap_in_result,
88    clippy::panic_in_result_fn,
89    clippy::indexing_slicing,
90    clippy::arithmetic_side_effects,
91    reason = "Standard repository test boilerplate"
92)]
93mod tests {
94    use super::*;
95    use std::io::{Seek, SeekFrom, Write};
96    use tempfile::tempfile;
97
98    #[crate::ctb_test]
99    fn test_to_text_valid_utf8() {
100        let mut f = tempfile().expect("tempfile");
101        f.write_all(b"Hello world, this is UTF-8 text.")
102            .expect("write");
103        f.seek(SeekFrom::Start(0)).expect("seek");
104
105        let text = to_text(&mut f, None).expect("to_text");
106        assert_eq!(text, "Hello world, this is UTF-8 text.");
107    }
108
109    #[crate::ctb_test]
110    fn test_to_text_with_byte_limit() {
111        let mut f = tempfile().expect("tempfile");
112        f.write_all(b"1234567890abcdef").expect("write");
113        f.seek(SeekFrom::Start(0)).expect("seek");
114
115        let text = to_text(&mut f, Some(5)).expect("to_text");
116        assert_eq!(text, "12345");
117    }
118
119    #[crate::ctb_test]
120    fn test_to_text_binary_fallback_wfscan() {
121        let mut f = tempfile().expect("tempfile");
122        // Non-UTF-8 bytes with embedded words
123        let data = b"abc\xFF\xFEdef<tag>ghi";
124        f.write_all(data).expect("write");
125        f.seek(SeekFrom::Start(0)).expect("seek");
126
127        let text = to_text(&mut f, None).expect("to_text");
128        assert!(text.contains("abc"));
129        assert!(text.contains("def"));
130    }
131
132    #[crate::ctb_test]
133    fn test_to_dcstring_passthrough() {
134        let mut f = tempfile().expect("tempfile");
135        f.write_all(b"Sample content").expect("write");
136        f.seek(SeekFrom::Start(0)).expect("seek");
137
138        let t1 = to_text(&mut f, None).expect("to_text");
139        f.seek(SeekFrom::Start(0)).expect("seek");
140        let t2 = to_dcstring(&mut f, None).expect("to_dcstring");
141        assert_eq!(t2, DcString::from(t1));
142    }
143}