Skip to main content

rustorb_core/idl/
value.rs

1//! Valuetypes and value boxes of generated code.
2//!
3//! A valuetype instance is shared: a [`ValueHandle`] is a reference to it,
4//! and the handles the generator makes for each valuetype wrap one. The
5//! state is a generated struct ([`ValueState`]) behind a mutex. An instance
6//! written twice in a message is sent once and then as an indirection, and
7//! is read back as one instance; instances may refer to each other in
8//! cycles, which keep them alive until the cycle is broken.
9
10use std::any::{Any, TypeId};
11use std::borrow::Borrow;
12use std::collections::BTreeMap;
13use std::fmt;
14use std::sync::{Arc, Mutex, MutexGuard, RwLock};
15
16use rustorb_cdr::ValueHeader;
17
18use super::{IdlType, Sys};
19use crate::{InStream, OutStream, TypeCode};
20
21/// What the generated code tells the runtime about a valuetype.
22#[derive(Debug)]
23pub struct ValueInfo {
24    /// The repository id.
25    pub id: &'static str,
26    /// The repository ids a value is sent with: its own, then those of
27    /// the base types it is truncatable to. A value with more than one is
28    /// sent chunked.
29    pub sent_ids: &'static [&'static str],
30    /// The repository ids of the type and of all its concrete base types:
31    /// where a value of this type may stand.
32    pub ancestors: &'static [&'static str],
33    /// Whether the type is custom marshaled: its state is written by
34    /// [`CustomMarshal`], and is always chunked.
35    pub custom: bool,
36    /// Makes an instance with the default state, which is then read.
37    pub make: fn() -> ValueHandle,
38    /// The TypeCode.
39    pub type_code: fn() -> TypeCode,
40}
41
42/// The state of a valuetype instance: the struct the generator makes for
43/// each valuetype, with the state of its base type as a member.
44pub trait ValueState: Send + 'static {
45    /// The type of the instance.
46    fn info(&self) -> &'static ValueInfo;
47    /// Writes the state members, those of the base types first.
48    fn write_state(&self, out: &mut OutStream<'_>) -> Sys<()>;
49    /// Reads the state members, those of the base types first.
50    fn read_state(&mut self, input: &mut InStream<'_>) -> Sys<()>;
51    /// The state of the type `ty` (this type or a base type) in this one.
52    fn view(&self, ty: TypeId) -> Option<&dyn Any>;
53    /// The same, to change.
54    fn view_mut(&mut self, ty: TypeId) -> Option<&mut dyn Any>;
55}
56
57struct ValueObj<S: ?Sized> {
58    info: &'static ValueInfo,
59    state: Mutex<S>,
60}
61
62/// A shared reference to a valuetype instance.
63#[derive(Clone)]
64pub struct ValueHandle(Arc<ValueObj<dyn ValueState>>);
65
66impl fmt::Debug for ValueHandle {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        // Not the state, which may refer back to this instance.
69        write!(f, "ValueHandle({} @ {:#x})", self.0.info.id, self.key())
70    }
71}
72
73impl ValueHandle {
74    /// A new instance with the state `state`.
75    pub fn new<S: ValueState>(state: S) -> ValueHandle {
76        let info = state.info();
77        let obj: Arc<ValueObj<dyn ValueState>> = Arc::new(ValueObj {
78            info,
79            state: Mutex::new(state),
80        });
81        ValueHandle(obj)
82    }
83
84    /// The type of the instance.
85    pub fn info(&self) -> &'static ValueInfo {
86        self.0.info
87    }
88
89    /// Whether the instance is of the valuetype `id` or of a type derived
90    /// from it.
91    pub fn is_a(&self, id: &str) -> bool {
92        self.0.info.ancestors.contains(&id)
93    }
94
95    /// Whether both are the same instance.
96    pub fn ptr_eq(&self, other: &ValueHandle) -> bool {
97        Arc::ptr_eq(&self.0, &other.0)
98    }
99
100    /// A number that identifies the instance while it is alive.
101    pub fn key(&self) -> u64 {
102        Arc::as_ptr(&self.0) as *const () as usize as u64
103    }
104
105    fn lock(&self) -> MutexGuard<'_, dyn ValueState> {
106        self.0.state.lock().unwrap_or_else(|e| e.into_inner())
107    }
108
109    /// Runs `f` on the state `S` of the instance (its own, or that of a
110    /// base type). Panics if the instance has no state `S`, which the
111    /// generated handles rule out. Touching the same instance in `f`
112    /// deadlocks.
113    pub fn with<S: 'static, R>(&self, f: impl FnOnce(&S) -> R) -> R {
114        let guard = self.lock();
115        let state = guard
116            .view(TypeId::of::<S>())
117            .and_then(|s| s.downcast_ref::<S>())
118            .expect("the state of a base type");
119        f(state)
120    }
121
122    /// Runs `f` on the state `S` of the instance, to change it.
123    pub fn with_mut<S: 'static, R>(&self, f: impl FnOnce(&mut S) -> R) -> R {
124        let mut guard = self.lock();
125        let state = guard
126            .view_mut(TypeId::of::<S>())
127            .and_then(|s| s.downcast_mut::<S>())
128            .expect("the state of a base type");
129        f(state)
130    }
131
132    /// Writes `v`, or `null`.
133    pub fn write(v: Option<&ValueHandle>, out: &mut OutStream<'_>) -> Sys<()> {
134        let Some(v) = v else {
135            out.write_null_value();
136            return Ok(());
137        };
138        let ids = v.0.info.sent_ids;
139        // The key is checked before the state is locked, so that an
140        // instance that refers to itself is written as an indirection.
141        if !out.begin_value(v.key(), ids, ids.len() > 1 || v.0.info.custom)? {
142            return Ok(());
143        }
144        v.lock().write_state(out)?;
145        out.end_value()?;
146        Ok(())
147    }
148
149    /// Reads a value where one of the valuetype `expected` (or `null`) is.
150    ///
151    /// A value is read as the first of the types it was sent with that is
152    /// `expected` or a type registered with [`register_value`] derived
153    /// from it, and is `MARSHAL` if there is none.
154    pub fn read(
155        input: &mut InStream<'_>,
156        expected: &'static ValueInfo,
157    ) -> Sys<Option<ValueHandle>> {
158        let e = input.marshal_error();
159        let header = input.read_value_header().map_err(|_| e.clone())?;
160        let (slot, ids) = match header {
161            ValueHeader::Null => return Ok(None),
162            ValueHeader::Indirection(slot) => {
163                let v = input
164                    .typed_values
165                    .get(slot)
166                    .and_then(|v| v.as_ref())
167                    .and_then(|v| v.downcast_ref::<ValueHandle>())
168                    .filter(|v| v.is_a(expected.id))
169                    .ok_or(e)?;
170                return Ok(Some(v.clone()));
171            }
172            ValueHeader::Value { slot, ids, .. } => (slot, ids),
173        };
174        let info = if ids.is_empty() {
175            expected
176        } else {
177            ids.iter()
178                .find_map(|id| {
179                    if id == expected.id {
180                        Some(expected)
181                    } else {
182                        lookup(id).filter(|i| i.ancestors.contains(&expected.id))
183                    }
184                })
185                .ok_or_else(|| e.clone())?
186        };
187        let v = (info.make)();
188        set_slot(input, slot, Box::new(v.clone()));
189        v.lock().read_state(input)?;
190        input.end_value().map_err(|_| e)?;
191        Ok(Some(v))
192    }
193}
194
195fn set_slot(input: &mut InStream<'_>, slot: usize, v: Box<dyn Any>) {
196    if input.typed_values.len() <= slot {
197        input.typed_values.resize_with(slot + 1, || None);
198    }
199    input.typed_values[slot] = Some(v);
200}
201
202/// The valuetypes known to the readers of generated code, by repository
203/// id.
204static VALUES: RwLock<BTreeMap<&'static str, &'static ValueInfo>> = RwLock::new(BTreeMap::new());
205
206/// Makes the valuetype `info` known to every ORB of the process, so that
207/// a value of it is read as itself where a base type of it is expected
208/// (rather than truncated). Its TypeCode is registered for anys as well
209/// ([`crate::register_value_type`]). Generated files have a
210/// `register_value_types` function that registers all of theirs.
211pub fn register_value(info: &'static ValueInfo) {
212    VALUES
213        .write()
214        .unwrap_or_else(|e| e.into_inner())
215        .insert(info.id, info);
216    crate::register_value_type(&(info.type_code)());
217    if info.custom {
218        crate::register_custom_reader(
219            info.id,
220            Arc::new(move |r, input| custom_reader(info, r, input)),
221        );
222    }
223}
224
225/// How the core reads the state of the custom valuetype `info` into an
226/// Any: an instance runs its `unmarshal`, and the items it reads (through
227/// [`DataInputStream`]) are the state of the core's instance `r`, which is
228/// written from them. The instance itself is dropped: extracting the
229/// value from the Any reads it again.
230fn custom_reader(
231    info: &'static ValueInfo,
232    r: &crate::ValueRef,
233    input: &mut InStream<'_>,
234) -> Sys<()> {
235    let v = (info.make)();
236    let outer = input.custom_items.replace(Vec::new());
237    let result = v.lock().read_state(input);
238    let items = std::mem::replace(&mut input.custom_items, outer).unwrap_or_default();
239    result?;
240    r.set_members(items);
241    Ok(())
242}
243
244fn lookup(id: &str) -> Option<&'static ValueInfo> {
245    VALUES
246        .read()
247        .unwrap_or_else(|e| e.into_inner())
248        .get(id)
249        .copied()
250}
251
252/// Writes the value box `v` of the type `id`, holding a `T`, or `null`.
253pub fn write_box<T: IdlType>(
254    v: Option<&Arc<T::Rust>>,
255    id: &str,
256    out: &mut OutStream<'_>,
257) -> Sys<()> {
258    let Some(v) = v else {
259        out.write_null_value();
260        return Ok(());
261    };
262    let key = Arc::as_ptr(v) as *const () as usize as u64;
263    if !out.begin_value(key, &[id], false)? {
264        return Ok(());
265    }
266    T::write(v.as_ref().borrow(), out)?;
267    out.end_value()?;
268    Ok(())
269}
270
271/// Reads a value box of the type `id`, holding a `T`, or `null`.
272pub fn read_box<T: IdlType>(input: &mut InStream<'_>, id: &str) -> Sys<Option<Arc<T::Rust>>> {
273    let e = input.marshal_error();
274    let header = input.read_value_header().map_err(|_| e.clone())?;
275    match header {
276        ValueHeader::Null => Ok(None),
277        ValueHeader::Indirection(slot) => input
278            .typed_values
279            .get(slot)
280            .and_then(|v| v.as_ref())
281            .and_then(|v| v.downcast_ref::<Arc<T::Rust>>())
282            .cloned()
283            .map(Some)
284            .ok_or(e),
285        ValueHeader::Value { slot, ids, .. } => {
286            if ids.first().is_some_and(|i| i != id) {
287                return Err(e);
288            }
289            let v = Arc::new(T::read(input)?);
290            set_slot(input, slot, Box::new(v.clone()));
291            input.end_value().map_err(|_| e)?;
292            Ok(Some(v))
293        }
294    }
295}
296
297/// The marshaling of a custom valuetype (`CORBA::CustomMarshal`), which
298/// the application implements for the state struct the generator makes
299/// for it: the generated code calls it to write and read the state.
300///
301/// ```ignore
302/// impl CustomMarshal for BlobState {
303///     fn marshal(&self, os: &mut DataOutputStream<'_, '_>) -> Sys<()> {
304///         os.write::<Long>(&self.n)?;
305///         os.write::<Point>(&self.pt)
306///     }
307///     fn unmarshal(&mut self, is: &mut DataInputStream<'_, '_>) -> Sys<()> {
308///         self.n = is.read::<Long>()?;
309///         self.pt = is.read::<Point>()?;
310///         Ok(())
311///     }
312/// }
313/// ```
314pub trait CustomMarshal {
315    /// Writes the state.
316    fn marshal(&self, os: &mut DataOutputStream<'_, '_>) -> Sys<()>;
317    /// Reads the state, in the order [`CustomMarshal::marshal`] writes it.
318    fn unmarshal(&mut self, is: &mut DataInputStream<'_, '_>) -> Sys<()>;
319}
320
321/// What a custom valuetype writes its state to (`CORBA::DataOutputStream`):
322/// items of IDL types, each written as CDR. Valuetypes written keep their
323/// sharing with the rest of the message.
324#[derive(Debug)]
325pub struct DataOutputStream<'s, 'a> {
326    out: &'s mut OutStream<'a>,
327}
328
329impl<'s, 'a> DataOutputStream<'s, 'a> {
330    /// A stream over `out`, for generated code.
331    pub fn new(out: &'s mut OutStream<'a>) -> Self {
332        DataOutputStream { out }
333    }
334
335    /// Writes a value of the IDL type `T` (`write_long` is
336    /// `write::<Long>`, `write_Value` of a `Point` is `write::<Point>`).
337    pub fn write<T: IdlType>(&mut self, v: &T::Borrowed) -> Sys<()> {
338        T::write(v, self.out)
339    }
340
341    /// Writes the elements of `items`, without a length
342    /// (`write_long_array(seq, offset, length)` is
343    /// `write_array::<Long>(&seq[offset..offset + length])`).
344    pub fn write_array<T: IdlType>(&mut self, items: &[T::Rust]) -> Sys<()> {
345        T::write_items(items, self.out)
346    }
347
348    /// The stream, for what the methods above do not cover.
349    pub fn stream(&mut self) -> &mut OutStream<'a> {
350        self.out
351    }
352}
353
354/// What a custom valuetype reads its state from (`CORBA::DataInputStream`).
355#[derive(Debug)]
356pub struct DataInputStream<'s, 'a> {
357    input: &'s mut InStream<'a>,
358}
359
360impl<'s, 'a> DataInputStream<'s, 'a> {
361    /// A stream over `input`, for generated code.
362    pub fn new(input: &'s mut InStream<'a>) -> Self {
363        DataInputStream { input }
364    }
365
366    /// Reads a value of the IDL type `T`.
367    pub fn read<T: IdlType>(&mut self) -> Sys<T::Rust> {
368        if self.input.custom_items.is_none() {
369            return T::read(self.input);
370        }
371        // The core reads the value into an Any (see `custom_reader`): the
372        // item is kept, as the state of the core's instance, and given to
373        // `unmarshal` converted.
374        let e = self.input.marshal_error();
375        let tc = T::type_code();
376        let value = self.input.read_value(&tc)?;
377        let item = crate::Any::new(tc, value);
378        let v = item.extract::<T>().ok_or_else(|| e.clone())?;
379        self.input
380            .custom_items
381            .as_mut()
382            .ok_or(e)?
383            .push(crate::Value::Any(Box::new(item)));
384        Ok(v)
385    }
386
387    /// Reads `len` elements of the IDL type `T`, written without a length.
388    pub fn read_array<T: IdlType>(&mut self, len: usize) -> Sys<Vec<T::Rust>> {
389        let e = self.input.marshal_error();
390        if len.saturating_mul(T::MIN_SIZE) > self.input.remaining() {
391            return Err(e);
392        }
393        if self.input.custom_items.is_none() {
394            return T::read_items(len, self.input);
395        }
396        (0..len).map(|_| self.read::<T>()).collect()
397    }
398
399    /// The stream, for what the methods above do not cover.
400    pub fn stream(&mut self) -> &mut InStream<'a> {
401        self.input
402    }
403}