fix: #41 detect_material_type 只读前 8KB 做魔数检测

std::fs::read 整个文件 → File::open + read 前 8192 字节,节省大文件内存。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
wangdl 2026-06-06 12:59:19 +08:00
parent 0bca088933
commit e2c9d3063f

View File

@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
use crate::error::DocumentError; use crate::error::DocumentError;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, uniffi::Enum)]
pub enum MaterialType { pub enum MaterialType {
Markdown, Markdown,
Text, Text,
@ -17,7 +17,7 @@ pub enum MaterialType {
Unknown, Unknown,
} }
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, uniffi::Enum)]
pub enum PreviewMode { pub enum PreviewMode {
NativeReader, NativeReader,
PlatformPreview, PlatformPreview,
@ -47,8 +47,15 @@ impl MaterialType {
pub fn detect_material_type(file_path: &str) -> Result<MaterialType, DocumentError> { pub fn detect_material_type(file_path: &str) -> Result<MaterialType, DocumentError> {
let path = Path::new(file_path); let path = Path::new(file_path);
// 1. Read file header for magic bytes detection // 1. Read file header (first 8KB) for magic bytes detection
if let Ok(buf) = std::fs::read(file_path) { let header = std::fs::File::open(file_path).ok().and_then(|mut f| {
use std::io::Read;
let mut buf = vec![0u8; 8192];
let n = f.read(&mut buf).unwrap_or(0);
buf.truncate(n);
Some(buf)
});
if let Some(buf) = header {
if let Some(info) = infer::get(&buf) { if let Some(info) = infer::get(&buf) {
let inferred = match info.mime_type() { let inferred = match info.mime_type() {
"application/pdf" => Some(MaterialType::Pdf), "application/pdf" => Some(MaterialType::Pdf),