xtap-core-lib 0.5.1

星TAP实验室通用 Rust 基座:跨平台路径/IO/硬件/MCP HTTP 服务/egui 主题与字体(features 按需裁剪)
Documentation
use crate::error::Result;
use anyhow::Context;
use std::fs;
use std::path::Path;

/// 写入文件,自动创建父目录
pub fn write_file<P: AsRef<Path>, D: AsRef<[u8]>>(path: P, data: D) -> Result<()> {
    let path = path.as_ref();
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).with_context(|| format!("创建父目录失败: {:?}", parent))?;
    }
    fs::write(path, data).with_context(|| format!("写入文件失败: {:?}", path))
}

/// 安全读取文件
pub fn read_file<P: AsRef<Path>>(path: P) -> Result<Vec<u8>> {
    let path = path.as_ref();
    fs::read(path).with_context(|| format!("读取文件失败: {:?}", path))
}

#[cfg(feature = "mmap")]
pub mod mmap {
    use crate::error::Result;
    use anyhow::Context;
    use memmap2::Mmap;
    use std::fs;
    use std::fs::File;
    use std::path::Path;

    /// 内存映射读取文件(零拷贝高性能)
    /// 适用于大文件处理,如 RAW 图片、向量索引等
    pub unsafe fn map_file<P: AsRef<Path>>(path: P) -> Result<Mmap> {
        let path = path.as_ref();
        let file = File::open(path).with_context(|| format!("打开文件失败: {:?}", path))?;
        let mmap = Mmap::map(&file).with_context(|| format!("内存映射失败: {:?}", path))?;
        Ok(mmap)
    }

    /// 内存映射写入文件
    pub unsafe fn map_file_mut<P: AsRef<Path>>(path: P) -> Result<memmap2::MmapMut> {
        let path = path.as_ref();
        let file = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(path)
            .with_context(|| format!("打开文件失败: {:?}", path))?;
        let mmap = memmap2::MmapMut::map_mut(&file)
            .with_context(|| format!("内存映射失败: {:?}", path))?;
        Ok(mmap)
    }
}

#[cfg(feature = "async")]
pub mod async_io {
    use crate::error::Result;
    use anyhow::Context;
    use std::path::Path;
    use tokio::fs;

    /// 异步写入文件,自动创建父目录
    pub async fn write_file_async<P: AsRef<Path>, D: AsRef<[u8]>>(path: P, data: D) -> Result<()> {
        let path = path.as_ref();
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)
                .await
                .with_context(|| format!("创建父目录失败: {:?}", parent))?;
        }
        fs::write(path, data)
            .await
            .with_context(|| format!("写入文件失败: {:?}", path))
    }

    /// 异步读取文件
    pub async fn read_file_async<P: AsRef<Path>>(path: P) -> Result<Vec<u8>> {
        let path = path.as_ref();
        fs::read(path)
            .await
            .with_context(|| format!("读取文件失败: {:?}", path))
    }
}