Skip to main content

rustorb_dds/
loan.rs

1//! Loaned samples (zero-copy): a writer fills a sample in shared memory
2//! and readers of this host read it there, with no serialization and no
3//! copy. See [`DataWriter::loan_sample`](crate::DataWriter::loan_sample)
4//! and [`DataReader::take_loaned`](crate::DataReader::take_loaned).
5// Without shared memory every loan is on the heap.
6#![cfg_attr(not(feature = "shm"), allow(dead_code, unused_imports))]
7
8use std::marker::PhantomData;
9use std::ops::{Deref, DerefMut};
10use std::sync::OnceLock;
11use std::sync::atomic::{AtomicBool, Ordering};
12
13/// A type whose samples can be loaned: one of a fixed size, whose value
14/// in memory is its serialized form.
15///
16/// # Safety
17///
18/// The type must be plain data: `#[repr(C)]` (or a primitive, or an
19/// array of such), with no pointers or references, valid when all its
20/// octets are zero, and valid for any octets that a value of it holds,
21/// since a reader of another process takes the octets of a writer's
22/// sample as a value. Its layout must be its serialized form (after the
23/// 4-octet encapsulation) in the writer's data representation and the
24/// host's byte order: the members in order, each aligned as the
25/// representation aligns it (to its size in XCDR1, to at most 4 in
26/// XCDR2). A writer checks this on its first loaned sample, and copies
27/// the samples it lends when it does not hold.
28pub unsafe trait PlainType: Copy + Send + Sync + 'static {}
29
30macro_rules! plain {
31    ($($t:ty),*) => {
32        $(
33            // SAFETY: a primitive with every bit pattern valid.
34            unsafe impl PlainType for $t {}
35        )*
36    };
37}
38plain!(u8, i8, u16, i16, u32, i32, u64, i64, f32, f64);
39
40// SAFETY: an array of plain data is laid out as its elements, in order.
41unsafe impl<T: PlainType, const N: usize> PlainType for [T; N] {}
42
43/// A zero `T` on the heap (it may be too large for the stack).
44pub(crate) fn zeroed_box<T: PlainType>() -> Box<T> {
45    let layout = std::alloc::Layout::new::<T>();
46    if layout.size() == 0 {
47        // SAFETY: `PlainType` is valid as all zeros.
48        return Box::new(unsafe { std::mem::zeroed() });
49    }
50    // SAFETY: a zeroed allocation of the layout of `T`, a valid `T`
51    // (`PlainType`), owned by the box.
52    unsafe {
53        let p = std::alloc::alloc_zeroed(layout) as *mut T;
54        if p.is_null() {
55            std::alloc::handle_alloc_error(layout);
56        }
57        Box::from_raw(p)
58    }
59}
60
61/// What a writer learnt of the layout of its type: the encapsulation of
62/// a sample whose value in memory is its serialized form, and whether a
63/// sample written showed that it is.
64#[derive(Debug, Default)]
65pub(crate) struct LoanCheck {
66    /// The encapsulation header, if the serialized form of a zero sample
67    /// is as long as the type plus the header.
68    pub(crate) header: OnceLock<Option<[u8; 4]>>,
69    /// Whether a sample showed that the layout is the serialized form
70    /// (until then, loaned samples are serialized).
71    verified: AtomicBool,
72}
73
74impl LoanCheck {
75    pub(crate) fn verified(&self) -> bool {
76        self.verified.load(Ordering::Relaxed)
77    }
78
79    pub(crate) fn set_verified(&self) {
80        self.verified.store(true, Ordering::Relaxed);
81    }
82}
83
84/// A sample loaned to a writer to fill: in shared memory when the writer
85/// has a pool, else on the heap. It holds zeros, or (a slot used again)
86/// an earlier sample of the writer; it is published
87/// with [`DataWriter::write_loaned`](crate::DataWriter::write_loaned),
88/// and returned unwritten when dropped.
89pub struct WriteLoan<T: PlainType> {
90    pub(crate) inner: WriteInner<T>,
91}
92
93pub(crate) enum WriteInner<T> {
94    #[cfg(feature = "shm")]
95    Shared(rustorb_rtps::shm::PoolSlot, PhantomData<T>),
96    Heap(Box<T>),
97}
98
99impl<T: PlainType> WriteLoan<T> {
100    pub(crate) fn heap() -> Self {
101        WriteLoan {
102            inner: WriteInner::Heap(zeroed_box()),
103        }
104    }
105
106    /// The sample in a slot.
107    #[cfg(feature = "shm")]
108    pub(crate) fn value_of(slot: &rustorb_rtps::shm::PoolSlot) -> &T {
109        // SAFETY: the slot holds a `T` after the header, aligned to 8
110        // (`loan_sample` checks that `T` needs no more), held by the loan
111        // alone; it holds zeros or an earlier `T`, valid either way.
112        unsafe { &*(slot.bytes()[4..].as_ptr() as *const T) }
113    }
114
115    /// Whether the sample is in shared memory.
116    pub fn is_shared(&self) -> bool {
117        match &self.inner {
118            #[cfg(feature = "shm")]
119            WriteInner::Shared(..) => true,
120            WriteInner::Heap(_) => false,
121        }
122    }
123}
124
125impl<T: PlainType> std::fmt::Debug for WriteLoan<T> {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        f.debug_struct("WriteLoan")
128            .field("shared", &self.is_shared())
129            .finish()
130    }
131}
132
133impl<T: PlainType> Deref for WriteLoan<T> {
134    type Target = T;
135    fn deref(&self) -> &T {
136        match &self.inner {
137            #[cfg(feature = "shm")]
138            WriteInner::Shared(slot, _) => Self::value_of(slot),
139            WriteInner::Heap(b) => b,
140        }
141    }
142}
143
144impl<T: PlainType> DerefMut for WriteLoan<T> {
145    fn deref_mut(&mut self) -> &mut T {
146        match &mut self.inner {
147            #[cfg(feature = "shm")]
148            WriteInner::Shared(slot, _) => {
149                // SAFETY: as in `value_of`.
150                unsafe { &mut *(slot.bytes_mut()[4..].as_mut_ptr() as *mut T) }
151            }
152            WriteInner::Heap(b) => b,
153        }
154    }
155}
156
157/// A sample read without a copy: in the shared memory of the writer that
158/// loaned it, held there until this is dropped, or a value of its own
159/// (a sample that was serialized).
160pub struct ReadLoan<T: PlainType> {
161    inner: ReadInner<T>,
162}
163
164enum ReadInner<T> {
165    #[cfg(feature = "shm")]
166    Shared(rustorb_rtps::shm::PoolLoan, PhantomData<T>),
167    /// Boxed: a `ReadLoan` is moved around, and `T` may be large.
168    Owned(Box<T>),
169}
170
171impl<T: PlainType> ReadLoan<T> {
172    pub(crate) fn owned(v: T) -> Self {
173        ReadLoan {
174            inner: ReadInner::Owned(Box::new(v)),
175        }
176    }
177
178    /// The sample in a pool, if its octets are a `T` there: as long as a
179    /// `T` plus the header, in the host's byte order, and aligned.
180    #[cfg(feature = "shm")]
181    pub(crate) fn shared(l: &rustorb_rtps::shm::PoolLoan) -> Option<Self> {
182        let b = l.bytes();
183        let native = u8::from(cfg!(target_endian = "little"));
184        let fits = b.len() == 4 + std::mem::size_of::<T>()
185            && b[0] == 0
186            && b[1] & 1 == native
187            && (b[4..].as_ptr() as usize).is_multiple_of(std::mem::align_of::<T>());
188        fits.then_some(ReadLoan {
189            inner: ReadInner::Shared(l.clone(), PhantomData),
190        })
191    }
192
193    /// Whether the sample is read in place, in shared memory.
194    pub fn is_shared(&self) -> bool {
195        match &self.inner {
196            #[cfg(feature = "shm")]
197            ReadInner::Shared(..) => true,
198            ReadInner::Owned(_) => false,
199        }
200    }
201}
202
203impl<T: PlainType> Deref for ReadLoan<T> {
204    type Target = T;
205    fn deref(&self) -> &T {
206        match &self.inner {
207            #[cfg(feature = "shm")]
208            ReadInner::Shared(l, _) => {
209                // SAFETY: checked in `shared`; the writer published the
210                // slot and does not write it while it is held.
211                unsafe { &*(l.bytes()[4..].as_ptr() as *const T) }
212            }
213            ReadInner::Owned(v) => v,
214        }
215    }
216}
217
218impl<T: PlainType + std::fmt::Debug> std::fmt::Debug for ReadLoan<T> {
219    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220        (**self).fmt(f)
221    }
222}