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