use crate::core::OCRError;
use std::path::Path;
pub fn read_character_dict(path: &Path) -> Result<Vec<String>, OCRError> {
let content = std::fs::read_to_string(path).map_err(|e| OCRError::InvalidInput {
message: format!(
"Failed to read character dictionary from '{}': {}",
path.display(),
e
),
})?;
Ok(content.lines().map(|s| s.to_string()).collect())
}
pub fn read_dict_content(path: &Path) -> Result<String, OCRError> {
std::fs::read_to_string(path).map_err(|e| OCRError::InvalidInput {
message: format!("Failed to read dictionary from '{}': {}", path.display(), e),
})
}
pub fn require_path<P: AsRef<Path> + Clone>(
path: Option<P>,
component: &str,
description: &str,
) -> Result<P, OCRError> {
path.ok_or_else(|| {
OCRError::config_error_detailed(
component,
format!("{} is required for {}", description, component),
)
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use tempfile::NamedTempFile;
#[test]
fn test_read_character_dict() -> Result<(), Box<dyn std::error::Error>> {
let mut file = NamedTempFile::new()?;
writeln!(file, "a")?;
writeln!(file, "b")?;
writeln!(file, "c")?;
let dict = read_character_dict(file.path())?;
assert_eq!(dict, vec!["a", "b", "c"]);
Ok(())
}
#[test]
fn test_read_dict_content() -> Result<(), Box<dyn std::error::Error>> {
let mut file = NamedTempFile::new()?;
write!(file, "hello\nworld")?;
let content = read_dict_content(file.path())?;
assert_eq!(content, "hello\nworld");
Ok(())
}
#[test]
fn test_read_nonexistent_file() {
let result = read_character_dict(Path::new("/nonexistent/path/dict.txt"));
assert!(result.is_err());
}
#[test]
fn test_require_path_some() {
let path = Some(std::path::PathBuf::from("/some/path"));
let result = require_path(path, "test", "test path");
assert!(result.is_ok());
}
#[test]
fn test_require_path_none() {
let path: Option<std::path::PathBuf> = None;
let result = require_path(path, "test_component", "test path");
assert!(result.is_err());
let err = result.unwrap_err();
assert!(err.to_string().contains("test_component"));
}
}