Skip to main content

xtap_core_lib/
io.rs

1use crate::error::Result;
2use anyhow::Context;
3use std::fs;
4use std::path::Path;
5
6/// 写入文件,自动创建父目录
7pub fn write_file<P: AsRef<Path>, D: AsRef<[u8]>>(path: P, data: D) -> Result<()> {
8    let path = path.as_ref();
9    if let Some(parent) = path.parent() {
10        fs::create_dir_all(parent).with_context(|| format!("创建父目录失败: {:?}", parent))?;
11    }
12    fs::write(path, data).with_context(|| format!("写入文件失败: {:?}", path))
13}
14
15/// 安全读取文件
16pub fn read_file<P: AsRef<Path>>(path: P) -> Result<Vec<u8>> {
17    let path = path.as_ref();
18    fs::read(path).with_context(|| format!("读取文件失败: {:?}", path))
19}
20
21#[cfg(feature = "mmap")]
22pub mod mmap {
23    use crate::error::Result;
24    use anyhow::Context;
25    use memmap2::Mmap;
26    use std::fs;
27    use std::fs::File;
28    use std::path::Path;
29
30    /// 内存映射读取文件(零拷贝高性能)
31    /// 适用于大文件处理,如 RAW 图片、向量索引等
32    pub unsafe fn map_file<P: AsRef<Path>>(path: P) -> Result<Mmap> {
33        let path = path.as_ref();
34        let file = File::open(path).with_context(|| format!("打开文件失败: {:?}", path))?;
35        let mmap = Mmap::map(&file).with_context(|| format!("内存映射失败: {:?}", path))?;
36        Ok(mmap)
37    }
38
39    /// 内存映射写入文件
40    pub unsafe fn map_file_mut<P: AsRef<Path>>(path: P) -> Result<memmap2::MmapMut> {
41        let path = path.as_ref();
42        let file = fs::OpenOptions::new()
43            .read(true)
44            .write(true)
45            .open(path)
46            .with_context(|| format!("打开文件失败: {:?}", path))?;
47        let mmap = memmap2::MmapMut::map_mut(&file)
48            .with_context(|| format!("内存映射失败: {:?}", path))?;
49        Ok(mmap)
50    }
51}
52
53#[cfg(feature = "async")]
54pub mod async_io {
55    use crate::error::Result;
56    use anyhow::Context;
57    use std::path::Path;
58    use tokio::fs;
59
60    /// 异步写入文件,自动创建父目录
61    pub async fn write_file_async<P: AsRef<Path>, D: AsRef<[u8]>>(path: P, data: D) -> Result<()> {
62        let path = path.as_ref();
63        if let Some(parent) = path.parent() {
64            fs::create_dir_all(parent)
65                .await
66                .with_context(|| format!("创建父目录失败: {:?}", parent))?;
67        }
68        fs::write(path, data)
69            .await
70            .with_context(|| format!("写入文件失败: {:?}", path))
71    }
72
73    /// 异步读取文件
74    pub async fn read_file_async<P: AsRef<Path>>(path: P) -> Result<Vec<u8>> {
75        let path = path.as_ref();
76        fs::read(path)
77            .await
78            .with_context(|| format!("读取文件失败: {:?}", path))
79    }
80}