Skip to main content

mpi/
raw.rs

1//! Bridge between Rust types and their underlying raw handles. Mirrors
2//! `mpi::raw` in rsmpi. In a C-backed MPI these expose the opaque `MPI_*`
3//! handles; here the "raw" form of a handle is the pure-Rust identifier the
4//! runtime uses internally (e.g. a communicator context id).
5
6use crate::datatype::DatatypeRef;
7use crate::topology::{Communicator, SimpleCommunicator};
8
9/// A type that can produce its raw handle.
10///
11/// # Safety
12///
13/// The returned raw handle must remain valid for as long as `self` is alive.
14pub unsafe trait AsRaw {
15    /// The raw handle type.
16    type Raw;
17    /// Obtain the raw handle.
18    fn as_raw(&self) -> Self::Raw;
19}
20
21/// A type that can produce a mutable pointer to its raw handle.
22///
23/// # Safety
24///
25/// See [`AsRaw`].
26pub unsafe trait AsRawMut: AsRaw {
27    /// Obtain a mutable pointer to the raw handle.
28    fn as_raw_mut(&mut self) -> *mut Self::Raw;
29}
30
31/// A type that can be reconstructed from its raw handle.
32pub trait FromRaw: AsRaw {
33    /// Rebuild `Self` from a raw handle.
34    ///
35    /// # Safety
36    ///
37    /// `raw` must be a valid handle produced by a matching [`AsRaw::as_raw`].
38    unsafe fn from_raw(raw: Self::Raw) -> Self;
39}
40
41/// Marker for types whose in-memory layout is identical to their raw handle,
42/// so that `&[Self]` can be reinterpreted as `&[Self::Raw]`.
43///
44/// # Safety
45///
46/// The implementing type must be layout-compatible with `Self::Raw`.
47pub unsafe trait MatchesRaw: AsRaw {}
48
49// SAFETY: a communicator's raw identity is its context id.
50unsafe impl AsRaw for SimpleCommunicator {
51    type Raw = u32;
52    fn as_raw(&self) -> u32 {
53        self.comm_data().context
54    }
55}
56
57// SAFETY: a datatype's raw identity is its numeric id.
58unsafe impl AsRaw for DatatypeRef {
59    type Raw = u32;
60    fn as_raw(&self) -> u32 {
61        self.id
62    }
63}
64
65/// Re-exports of the raw-handle traits, for `use mpi::raw::traits::*;`.
66pub mod traits {
67    pub use super::{AsRaw, AsRawMut, FromRaw, MatchesRaw};
68}