use std::io::{Seek, Write};

use memmap2::*;

/// 以只读的方式创建文件映射
pub fn mmap_file(file_path: &str) -> Result<Mmap, std::io::Error> {
    let file = std::fs::OpenOptions::new().read(true).open(file_path)?;
    unsafe {
        MmapOptions::new()
            .map(&file)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))
    }
}

/// 以读写方式创建文件映射
pub fn mmap_file_rw(file_path: &str) -> Result<MmapMut, std::io::Error> {
    let file = std::fs::OpenOptions::new().read(true).write(true).open(file_path)?;
    unsafe {
        MmapOptions::new()
            .map_mut(&file)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))
    }
}

// 拓展文件大小
pub fn expand_file_size(file_path: &str, expand_size: u32) -> Result<(), std::io::Error> {
    let mut file = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .open(file_path)?;
    // 文件指针移动到文件末尾
    file.seek(std::io::SeekFrom::End(0))?;
    // 拓展文件大小
    file.set_len(file.metadata()?.len() + expand_size as u64)?;
    file.seek(std::io::SeekFrom::Start(0))?;
    file.flush()?;
    Ok(())
}
