zenoh_shm/api/buffer/
traits.rs

1//
2// Copyright (c) 2023 ZettaScale Technology
3//
4// This program and the accompanying materials are made available under the
5// terms of the Eclipse Public License 2.0 which is available at
6// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
7// which is available at https://www.apache.org/licenses/LICENSE-2.0.
8//
9// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
10//
11// Contributors:
12//   ZettaScale Zenoh Team, <zenoh@zettascale.tech>
13//
14use std::num::NonZeroUsize;
15
16use stabby::{abi::typenum2::B0, IStable};
17
18use crate::api::provider::memory_layout::MemoryLayout;
19
20/// # Safety
21/// This trait is unsafe because it allows types to be used in shared memory.
22/// It is the responsibility of the implementer to ensure that the type is safe to use in shared memory.
23/// There are some safe blanket implementations below
24pub unsafe trait ResideInShm: Send {}
25
26unsafe impl<T: Send + IStable<ContainsIndirections = B0>> ResideInShm for T {}
27
28/// Errors for buffer relayouting operation.
29#[zenoh_macros::unstable_doc]
30#[derive(Debug)]
31pub enum BufferRelayoutError {
32    IncompatibleAlignment,
33    SizeTooBig,
34}
35
36#[zenoh_macros::unstable_doc]
37pub trait ShmBuf<T: ?Sized>: Sized + AsRef<T> {
38    #[zenoh_macros::unstable_doc]
39    fn is_valid(&self) -> bool;
40}
41
42#[zenoh_macros::unstable_doc]
43pub trait ShmBufUnsafeMut<T: ?Sized>: ShmBuf<T> {
44    #[zenoh_macros::unstable_doc]
45    /// Get unchecked mutable access to buffer's memory.
46    ///
47    /// This is unsafe yet very powerful API for building concurrent access logic around SHM buffer contents.
48    /// For safe version please see `ShmBufMut` trait.
49    ///
50    /// # Safety
51    ///
52    /// Safe if multiple conditions are met:
53    /// - user code guarantees no data race across all applications that share the buffer
54    /// - the buffer is not being concurrently sent to the outside of SHM domain
55    /// - the buffer is valid
56    unsafe fn as_mut_unchecked(&mut self) -> &mut T;
57}
58
59#[zenoh_macros::unstable_doc]
60pub trait ShmBufMut<T: ?Sized>: ShmBuf<T> + AsMut<T> {}
61
62#[zenoh_macros::unstable_doc]
63pub trait OwnedShmBuf<T: ?Sized>: ShmBuf<T> {
64    #[zenoh_macros::unstable_doc]
65    fn try_resize(&mut self, new_size: NonZeroUsize) -> Option<()>;
66
67    #[zenoh_macros::unstable_doc]
68    fn try_relayout(&mut self, new_layout: MemoryLayout) -> Result<(), BufferRelayoutError>;
69}
70
71#[zenoh_macros::unstable_doc]
72pub trait ShmBufIntoImmut<T: ?Sized>: ShmBuf<T> {
73    type ImmutBuf: ShmBuf<T>;
74
75    #[zenoh_macros::unstable_doc]
76    fn into_immut(self) -> Self::ImmutBuf;
77}