euv-core 0.54.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
use super::*;

/// Immutable read-only OS mappings are safely transferable across threads.
#[cfg(any(unix, windows))]
unsafe impl Send for EuvPakOsMap {}

/// Immutable read-only OS mappings can be shared concurrently across background I/O workers.
#[cfg(any(unix, windows))]
unsafe impl Sync for EuvPakOsMap {}

/// Deterministic RAII unmapping when the last `Arc<EuvPakOsMap>` drops.
#[cfg(any(unix, windows))]
impl Drop for EuvPakOsMap {
    /// Releases the underlying OS virtual memory mapping without leaking descriptors or pages.
    fn drop(&mut self) {
        #[cfg(unix)]
        {
            let Self { ptr, len } = *self;
            unmap_posix_region(ptr, len);
        }
        #[cfg(windows)]
        {
            let Self {
                ptr,
                mapping_handle,
                ..
            } = *self;
            unmap_win32_region(ptr, mapping_handle);
        }
    }
}

/// Default empty heap-backed `EuvPakMapping`.
impl Default for EuvPakMapping {
    /// Creates an empty read-only `EuvPakMapping`.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty in-memory mapping.
    fn default() -> Self {
        Self::from_bytes(Arc::new(Vec::new()))
    }
}

/// Cross-platform zero-copy constructors, OS `mmap` lifecycle, and paging hints for `EuvPakMapping`.
impl EuvPakMapping {
    /// Creates an in-memory zero-copy mapping over an `Arc<Vec<u8>>` buffer.
    ///
    /// # Arguments
    ///
    /// - `Arc<Vec<u8>>` - Shared immutable `.euvpak` archive byte buffer.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready read-only `EuvPakMapping`.
    #[must_use]
    pub fn from_bytes(bytes: Arc<Vec<u8>>) -> Self {
        Self {
            backing: EuvPakBacking::Owned(bytes),
        }
    }

    /// Opens an `.euvpak` archive from `path` using a single OS virtual memory map on native targets.
    ///
    /// # Arguments
    ///
    /// - `&Path` - Filesystem path to an `.euvpak` archive.
    ///
    /// # Returns
    ///
    /// - `Result<Self, String>` - Zero-copy OS-mapped archive view or structured I/O error.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn open_mmap(path: &Path) -> Result<Self, String> {
        #[cfg(unix)]
        {
            let mut file: File = File::open(path)
                .map_err(|err: io::Error| format!("{ERR_EUVPAK_OPEN_FAILED}: {err}"))?;
            let raw_fd: i32 = file.as_raw_fd();
            if raw_fd < 0 {
                return Err(ERR_EUVPAK_INVALID_HANDLE.to_string());
            }
            let file_len: u64 = file
                .seek(SeekFrom::End(0))
                .map_err(|err: io::Error| format!("{ERR_EUVPAK_OPEN_FAILED}: {err}"))?;
            if file_len == 0 {
                return Ok(Self::from_bytes(Arc::new(Vec::new())));
            }
            if file_len > usize::MAX as u64 {
                return Err(ERR_EUVPAK_TOO_LARGE.to_string());
            }
            let os_map: EuvPakOsMap = map_posix_readonly(raw_fd, file_len as usize)?;
            Ok(Self {
                backing: EuvPakBacking::OsMapped(Arc::new(os_map)),
            })
        }
        #[cfg(windows)]
        {
            let mut file: File = File::open(path)
                .map_err(|err: io::Error| format!("{ERR_EUVPAK_OPEN_FAILED}: {err}"))?;
            let raw_handle: *mut c_void = file.as_raw_handle();
            if raw_handle.is_null() || raw_handle as isize == -1 {
                return Err(ERR_EUVPAK_INVALID_HANDLE.to_string());
            }
            let file_len: u64 = file
                .seek(SeekFrom::End(0))
                .map_err(|err: io::Error| format!("{ERR_EUVPAK_OPEN_FAILED}: {err}"))?;
            if file_len == 0 {
                return Ok(Self::from_bytes(Arc::new(Vec::new())));
            }
            if file_len > usize::MAX as u64 {
                return Err(ERR_EUVPAK_TOO_LARGE.to_string());
            }
            let os_map: EuvPakOsMap = map_win32_readonly(raw_handle, file_len as usize)?;
            Ok(Self {
                backing: EuvPakBacking::OsMapped(Arc::new(os_map)),
            })
        }
        #[cfg(not(any(unix, windows)))]
        {
            let mut file: File = File::open(path)
                .map_err(|err: io::Error| format!("{ERR_EUVPAK_OPEN_FAILED}: {err}"))?;
            let file_len: u64 = file
                .seek(SeekFrom::End(0))
                .map_err(|err: io::Error| format!("{ERR_EUVPAK_OPEN_FAILED}: {err}"))?;
            let _: u64 = file
                .seek(SeekFrom::Start(0))
                .map_err(|err: io::Error| format!("{ERR_EUVPAK_OPEN_FAILED}: {err}"))?;
            let mut buffer: Vec<u8> = Vec::with_capacity(file_len as usize);
            let _: usize = file
                .read_to_end(&mut buffer)
                .map_err(|err: io::Error| format!("{ERR_EUVPAK_OPEN_FAILED}: {err}"))?;
            Ok(Self::from_bytes(Arc::new(buffer)))
        }
    }

    /// Returns an error on `wasm32` where direct OS filesystem `mmap` is unavailable.
    ///
    /// # Arguments
    ///
    /// - `&Path` - Unused filesystem path on `wasm32`.
    ///
    /// # Returns
    ///
    /// - `Result<Self, String>` - Always returns an unsupported error instructing callers to use `from_bytes`.
    #[cfg(target_arch = "wasm32")]
    pub fn open_mmap(_path: &Path) -> Result<Self, String> {
        Err(ERR_EUVPAK_WASM_UNSUPPORTED.to_string())
    }

    /// Advises the OS kernel to prefetch `[offset..offset+len]` via `MADV_WILLNEED` when OS-mapped.
    ///
    /// # Arguments
    ///
    /// - `usize` - Starting byte offset inside the mapping.
    /// - `usize` - Byte length to pre-fault sequentially.
    pub fn advise_willneed(&self, offset: usize, len: usize) {
        #[cfg(unix)]
        {
            let Self { backing } = self;
            if let EuvPakBacking::OsMapped(os_map) = backing {
                advise_posix_region(os_map, offset, len, POSIX_MADV_WILLNEED);
            }
        }
        #[cfg(not(unix))]
        {
            let _: (usize, usize) = (offset, len);
        }
    }

    /// Advises the OS kernel that `[offset..offset+len]` will be accessed randomly (`MADV_RANDOM`).
    ///
    /// # Arguments
    ///
    /// - `usize` - Starting byte offset inside the mapping.
    /// - `usize` - Byte length expected to experience random access.
    pub fn advise_random(&self, offset: usize, len: usize) {
        #[cfg(unix)]
        {
            let Self { backing } = self;
            if let EuvPakBacking::OsMapped(os_map) = backing {
                advise_posix_region(os_map, offset, len, POSIX_MADV_RANDOM);
            }
        }
        #[cfg(not(unix))]
        {
            let _: (usize, usize) = (offset, len);
        }
    }

    /// Returns the mapped archive payload as an immutable zero-copy byte slice.
    ///
    /// # Returns
    ///
    /// - `&[u8]` - Borrowed view of the mapped `.euvpak` bytes.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        let Self { backing } = self;
        match backing {
            EuvPakBacking::Owned(bytes) => bytes.as_slice(),
            #[cfg(any(unix, windows))]
            EuvPakBacking::OsMapped(os_map) => {
                let EuvPakOsMap { ptr, len, .. } = **os_map;
                unsafe { from_raw_parts(ptr.as_ptr(), len) }
            }
        }
    }

    /// Returns the non-null base pointer of the backing byte buffer on native targets when non-empty.
    ///
    /// # Returns
    ///
    /// - `Option<NonNull<u8>>` - Non-null pointer to the first byte or `None` when empty.
    #[cfg(any(unix, windows))]
    #[must_use]
    pub fn base_non_null(&self) -> Option<NonNull<u8>> {
        let Self { backing } = self;
        match backing {
            EuvPakBacking::Owned(bytes) => {
                if bytes.is_empty() {
                    None
                } else {
                    NonNull::new(bytes.as_ptr().cast_mut())
                }
            }
            EuvPakBacking::OsMapped(os_map) => Some(os_map.ptr),
        }
    }

    /// Returns the byte length of this mapped archive.
    ///
    /// # Returns
    ///
    /// - `usize` - Mapped byte length.
    #[must_use]
    pub fn len(&self) -> usize {
        self.as_bytes().len()
    }

    /// Returns `true` when the mapped archive contains zero bytes.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether the mapped byte slice is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.as_bytes().is_empty()
    }

    /// Returns `true` when backed by an OS virtual memory mapping (`mmap` / `MapViewOfFile`).
    ///
    /// # Returns
    ///
    /// - `bool` - Whether OS virtual memory mapping is active.
    #[must_use]
    pub fn is_os_mapped(&self) -> bool {
        let Self { backing } = self;
        match backing {
            EuvPakBacking::Owned(_) => false,
            #[cfg(any(unix, windows))]
            EuvPakBacking::OsMapped(_) => true,
        }
    }
}