mmap_io/
manager.rs

1//! High-level API for managing memory-mapped files.
2//!
3//! Provides convenience functions that wrap low-level mmap operations.
4
5use std::fs;
6use std::path::Path;
7
8use crate::errors::Result;
9use crate::mmap::{MemoryMappedFile, MmapMode};
10
11/// Create a new read-write memory-mapped file of the given size.
12/// Truncates if the file already exists.
13///
14/// # Errors
15///
16/// Returns errors from `MemoryMappedFile::create_rw`.
17pub fn create_mmap<P: AsRef<Path>>(path: P, size: u64) -> Result<MemoryMappedFile> {
18    MemoryMappedFile::create_rw(path, size)
19}
20
21/// Load an existing memory-mapped file in the requested mode.
22///
23/// # Errors
24///
25/// Returns errors from `MemoryMappedFile::open_ro` or `open_rw`.
26pub fn load_mmap<P: AsRef<Path>>(path: P, mode: MmapMode) -> Result<MemoryMappedFile> {
27    match mode {
28        MmapMode::ReadOnly => MemoryMappedFile::open_ro(path),
29        MmapMode::ReadWrite => MemoryMappedFile::open_rw(path),
30        #[cfg(feature = "cow")]
31        MmapMode::CopyOnWrite => MemoryMappedFile::open_cow(path),
32        #[cfg(not(feature = "cow"))]
33        MmapMode::CopyOnWrite => Err(crate::errors::MmapIoError::InvalidMode("copy-on-write mode not enabled (feature `cow`)")),
34    }
35}
36
37/// Write bytes at an offset into the specified file path (RW).
38/// Convenience wrapper around creating/loading and `update_region`.
39///
40/// # Errors
41///
42/// Returns errors from file opening or update operations.
43pub fn write_mmap<P: AsRef<Path>>(path: P, offset: u64, data: &[u8]) -> Result<()> {
44    let mmap = MemoryMappedFile::open_rw(path)?;
45    mmap.update_region(offset, data)
46}
47
48/// Update a region in an existing mapping (RW).
49///
50/// # Errors
51///
52/// Returns errors from `MemoryMappedFile::update_region`.
53pub fn update_region(mmap: &MemoryMappedFile, offset: u64, data: &[u8]) -> Result<()> {
54    mmap.update_region(offset, data)
55}
56
57/// Flush changes for an existing mapping.
58///
59/// # Errors
60///
61/// Returns errors from `MemoryMappedFile::flush`.
62pub fn flush(mmap: &MemoryMappedFile) -> Result<()> {
63    mmap.flush()
64}
65
66/// Copy a mapped file to a new destination using the filesystem.
67/// This does not copy the mapping identity, only the underlying file contents.
68///
69/// # Errors
70///
71/// Returns `MmapIoError::Io` if the copy operation fails.
72pub fn copy_mmap<P: AsRef<Path>>(src: P, dst: P) -> Result<()> {
73    fs::copy(src, dst)?;
74    Ok(())
75}
76
77/// Delete the file backing a mapping path. The mapping itself should be dropped by users before invoking this.
78/// On Unix, deleting an open file keeps the data until last handle drops; prefer dropping mappings before deleting.
79///
80/// # Errors
81///
82/// Returns `MmapIoError::Io` if the delete operation fails.
83pub fn delete_mmap<P: AsRef<Path>>(path: P) -> Result<()> {
84    fs::remove_file(path)?;
85    Ok(())
86}
87
88#[cfg(feature = "async")]
89pub mod r#async {
90    //! Async helpers (Tokio) for creating and copying files without blocking the current thread.
91    use std::path::Path;
92
93    use tokio::fs as tfs;
94
95    use crate::errors::Result;
96    use crate::mmap::MemoryMappedFile;
97
98    /// Create a new file with the specified size asynchronously, then map it RW.
99    ///
100    /// # Errors
101    ///
102    /// Returns errors from async file operations or mapping.
103    pub async fn create_mmap_async<P: AsRef<Path>>(path: P, size: u64) -> Result<MemoryMappedFile> {
104        let path_ref = path.as_ref();
105        // Create and set size via tokio
106        let file = tfs::OpenOptions::new()
107            .create(true)
108            .write(true)
109            .read(true)
110            .truncate(true)
111            .open(path_ref)
112            .await?;
113        file.set_len(size).await?;
114        drop(file);
115        MemoryMappedFile::open_rw(path_ref)
116    }
117
118    /// Copy a file asynchronously.
119    ///
120    /// # Errors
121    ///
122    /// Returns `MmapIoError::Io` if the async copy operation fails.
123    pub async fn copy_mmap_async<P: AsRef<Path>>(src: P, dst: P) -> Result<()> {
124        tfs::copy(src, dst).await?;
125        Ok(())
126    }
127
128    /// Delete a file asynchronously.
129    ///
130    /// # Errors
131    ///
132    /// Returns `MmapIoError::Io` if the async delete operation fails.
133    pub async fn delete_mmap_async<P: AsRef<Path>>(path: P) -> Result<()> {
134        tfs::remove_file(path).await?;
135        Ok(())
136    }
137}