Skip to main content

mesa3d_util/
shm.rs

1// Copyright 2025 Google
2// SPDX-License-Identifier: MIT
3
4use std::ffi::CString;
5
6use crate::sys::platform::page_size;
7use crate::sys::platform::SharedMemory as PlatformSharedMemory;
8use crate::AsRawDescriptor;
9use crate::FromRawDescriptor;
10use crate::IntoRawDescriptor;
11use crate::MesaError;
12use crate::MesaResult;
13use crate::OwnedDescriptor;
14use crate::RawDescriptor;
15
16pub struct SharedMemory(pub(crate) PlatformSharedMemory);
17impl SharedMemory {
18    /// Creates a new shared memory object of the given size.
19    ///
20    /// |name| is purely for debugging purposes. It does not need to be unique, and it does
21    /// not affect any non-debugging related properties of the constructed shared memory.
22    pub fn new<T: Into<Vec<u8>>>(debug_name: T, size: u64) -> MesaResult<SharedMemory> {
23        let debug_name = CString::new(debug_name)?;
24        PlatformSharedMemory::new(&debug_name, size).map(SharedMemory)
25    }
26
27    pub fn size(&self) -> u64 {
28        self.0.size()
29    }
30}
31
32impl AsRawDescriptor for SharedMemory {
33    fn as_raw_descriptor(&self) -> RawDescriptor {
34        self.0.as_raw_descriptor()
35    }
36}
37
38impl IntoRawDescriptor for SharedMemory {
39    fn into_raw_descriptor(self) -> RawDescriptor {
40        self.0.into_raw_descriptor()
41    }
42}
43
44impl From<SharedMemory> for OwnedDescriptor {
45    fn from(sm: SharedMemory) -> OwnedDescriptor {
46        // SAFETY:
47        // Safe because we own the SharedMemory at this point.
48        unsafe { OwnedDescriptor::from_raw_descriptor(sm.into_raw_descriptor()) }
49    }
50}
51
52/// Uses the system's page size in bytes to round the given value up to the nearest page boundary.
53pub fn round_up_to_page_size(v: u64) -> MesaResult<u64> {
54    v.checked_next_multiple_of(page_size()? as _)
55        .ok_or(MesaError::WithContext("rounding up caused overflow"))
56}