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        read_value(input, Some(expected))
159    }
160
161    /// Reads a value where any valuetype (`ValueBase`, or `null`) may be,
162    /// as where an abstract interface is sent as a value: as the first of
163    /// the types it was sent with that is registered with
164    /// [`register_value`], and `MARSHAL` if there is none.
165    pub fn read_base(input: &mut InStream<'_>) -> Sys<Option<ValueHandle>> {
166        read_value(input, None)
167    }
168}
169
170fn read_value(
171    input: &mut InStream<'_>,
172    expected: Option<&'static ValueInfo>,
173) -> Sys<Option<ValueHandle>> {
174    let e = input.marshal_error();
175    let header = input.read_value_header().map_err(|_| e.clone())?;
176    let (slot, ids) = match header {
177        ValueHeader::Null => return Ok(None),
178        ValueHeader::Indirection(slot) => {
179            let v = input
180                .typed_values
181                .get(slot)
182                .and_then(|v| v.as_ref())
183                .and_then(|v| v.downcast_ref::<ValueHandle>())
184                .filter(|v| expected.is_none_or(|x| v.is_a(x.id)))
185                .ok_or(e)?;
186            return Ok(Some(v.clone()));
187        }
188        ValueHeader::Value { slot, ids, .. } => (slot, ids),
189    };
190    let info = match expected {
191        Some(x) if ids.is_empty() => x,
192        Some(x) => ids
193            .iter()
194            .find_map(|id| {
195                if id == x.id {
196                    Some(x)
197                } else {
198                    lookup(id).filter(|i| i.ancestors.contains(&x.id))
199                }
200            })
201            .ok_or_else(|| e.clone())?,
202        None => ids
203            .iter()
204            .find_map(|id| lookup(id))
205            .ok_or_else(|| e.clone())?,
206    };
207    let v = (info.make)();
208    set_slot(input, slot, Box::new(v.clone()));
209    v.lock().read_state(input)?;
210    input.end_value().map_err(|_| e)?;
211    Ok(Some(v))
212}
213
214fn set_slot(input: &mut InStream<'_>, slot: usize, v: Box<dyn Any>) {
215    if input.typed_values.len() <= slot {
216        input.typed_values.resize_with(slot + 1, || None);
217    }
218    input.typed_values[slot] = Some(v);
219}
220
221/// The valuetypes known to the readers of generated code, by repository
222/// id.
223static VALUES: RwLock<BTreeMap<&'static str, &'static ValueInfo>> = RwLock::new(BTreeMap::new());
224
225/// Makes the valuetype `info` known to every ORB of the process, so that
226/// a value of it is read as itself where a base type of it is expected
227/// (rather than truncated). Its TypeCode is registered for anys as well
228/// ([`crate::register_value_type`]). Generated files have a
229/// `register_value_types` function that registers all of theirs.
230pub fn register_value(info: &'static ValueInfo) {
231    VALUES
232        .write()
233        .unwrap_or_else(|e| e.into_inner())
234        .insert(info.id, info);
235    crate::register_value_type(&(info.type_code)());
236    if info.custom {
237        crate::register_custom_reader(
238            info.id,
239            Arc::new(move |r, input| custom_reader(info, r, input)),
240        );
241    }
242}
243
244/// How the core reads the state of the custom valuetype `info` into an
245/// Any: an instance runs its `unmarshal`, and the items it reads (through
246/// [`DataInputStream`]) are the state of the core's instance `r`, which is
247/// written from them. The instance itself is dropped: extracting the
248/// value from the Any reads it again.
249fn custom_reader(
250    info: &'static ValueInfo,
251    r: &crate::ValueRef,
252    input: &mut InStream<'_>,
253) -> Sys<()> {
254    let v = (info.make)();
255    let outer = input.custom_items.replace(Vec::new());
256    let result = v.lock().read_state(input);
257    let items = std::mem::replace(&mut input.custom_items, outer).unwrap_or_default();
258    result?;
259    r.set_members(items);
260    Ok(())
261}
262
263fn lookup(id: &str) -> Option<&'static ValueInfo> {
264    VALUES
265        .read()
266        .unwrap_or_else(|e| e.into_inner())
267        .get(id)
268        .copied()
269}
270
271/// Writes the value box `v` of the type `id`, holding a `T`, or `null`.
272pub fn write_box<T: IdlType>(
273    v: Option<&Arc<T::Rust>>,
274    id: &str,
275    out: &mut OutStream<'_>,
276) -> Sys<()> {
277    let Some(v) = v else {
278        out.write_null_value();
279        return Ok(());
280    };
281    let key = Arc::as_ptr(v) as *const () as usize as u64;
282    if !out.begin_value(key, &[id], false)? {
283        return Ok(());
284    }
285    T::write(v.as_ref().borrow(), out)?;
286    out.end_value()?;
287    Ok(())
288}
289
290/// Reads a value box of the type `id`, holding a `T`, or `null`.
291pub fn read_box<T: IdlType>(input: &mut InStream<'_>, id: &str) -> Sys<Option<Arc<T::Rust>>> {
292    let e = input.marshal_error();
293    let header = input.read_value_header().map_err(|_| e.clone())?;
294    match header {
295        ValueHeader::Null => Ok(None),
296        ValueHeader::Indirection(slot) => input
297            .typed_values
298            .get(slot)
299            .and_then(|v| v.as_ref())
300            .and_then(|v| v.downcast_ref::<Arc<T::Rust>>())
301            .cloned()
302            .map(Some)
303            .ok_or(e),
304        ValueHeader::Value { slot, ids, .. } => {
305            if ids.first().is_some_and(|i| i != id) {
306                return Err(e);
307            }
308            let v = Arc::new(T::read(input)?);
309            set_slot(input, slot, Box::new(v.clone()));
310            input.end_value().map_err(|_| e)?;
311            Ok(Some(v))
312        }
313    }
314}
315
316/// The marshaling of a custom valuetype (`CORBA::CustomMarshal`), which
317/// the application implements for the state struct the generator makes
318/// for it: the generated code calls it to write and read the state.
319///
320/// ```ignore
321/// impl CustomMarshal for BlobState {
322///     fn marshal(&self, os: &mut DataOutputStream<'_, '_>) -> Sys<()> {
323///         os.write::<Long>(&self.n)?;
324///         os.write::<Point>(&self.pt)
325///     }
326///     fn unmarshal(&mut self, is: &mut DataInputStream<'_, '_>) -> Sys<()> {
327///         self.n = is.read::<Long>()?;
328///         self.pt = is.read::<Point>()?;
329///         Ok(())
330///     }
331/// }
332/// ```
333pub trait CustomMarshal {
334    /// Writes the state.
335    fn marshal(&self, os: &mut DataOutputStream<'_, '_>) -> Sys<()>;
336    /// Reads the state, in the order [`CustomMarshal::marshal`] writes it.
337    fn unmarshal(&mut self, is: &mut DataInputStream<'_, '_>) -> Sys<()>;
338}
339
340/// What a custom valuetype writes its state to (`CORBA::DataOutputStream`):
341/// items of IDL types, each written as CDR. Valuetypes written keep their
342/// sharing with the rest of the message.
343#[derive(Debug)]
344pub struct DataOutputStream<'s, 'a> {
345    out: &'s mut OutStream<'a>,
346}
347
348impl<'s, 'a> DataOutputStream<'s, 'a> {
349    /// A stream over `out`, for generated code.
350    pub fn new(out: &'s mut OutStream<'a>) -> Self {
351        DataOutputStream { out }
352    }
353
354    /// Writes a value of the IDL type `T` (`write_long` is
355    /// `write::<Long>`, `write_Value` of a `Point` is `write::<Point>`).
356    pub fn write<T: IdlType>(&mut self, v: &T::Borrowed) -> Sys<()> {
357        T::write(v, self.out)
358    }
359
360    /// Writes the elements of `items`, without a length
361    /// (`write_long_array(seq, offset, length)` is
362    /// `write_array::<Long>(&seq[offset..offset + length])`).
363    pub fn write_array<T: IdlType>(&mut self, items: &[T::Rust]) -> Sys<()> {
364        T::write_items(items, self.out)
365    }
366
367    /// The stream, for what the methods above do not cover.
368    pub fn stream(&mut self) -> &mut OutStream<'a> {
369        self.out
370    }
371}
372
373/// What a custom valuetype reads its state from (`CORBA::DataInputStream`).
374#[derive(Debug)]
375pub struct DataInputStream<'s, 'a> {
376    input: &'s mut InStream<'a>,
377}
378
379impl<'s, 'a> DataInputStream<'s, 'a> {
380    /// A stream over `input`, for generated code.
381    pub fn new(input: &'s mut InStream<'a>) -> Self {
382        DataInputStream { input }
383    }
384
385    /// Reads a value of the IDL type `T`.
386    pub fn read<T: IdlType>(&mut self) -> Sys<T::Rust> {
387        if self.input.custom_items.is_none() {
388            return T::read(self.input);
389        }
390        // The core reads the value into an Any (see `custom_reader`): the
391        // item is kept, as the state of the core's instance, and given to
392        // `unmarshal` converted.
393        let e = self.input.marshal_error();
394        let tc = T::type_code();
395        let value = self.input.read_value(&tc)?;
396        let item = crate::Any::new(tc, value);
397        let v = item.extract::<T>().ok_or_else(|| e.clone())?;
398        self.input
399            .custom_items
400            .as_mut()
401            .ok_or(e)?
402            .push(crate::Value::Any(Box::new(item)));
403        Ok(v)
404    }
405
406    /// Reads `len` elements of the IDL type `T`, written without a length.
407    pub fn read_array<T: IdlType>(&mut self, len: usize) -> Sys<Vec<T::Rust>> {
408        let e = self.input.marshal_error();
409        if len.saturating_mul(T::MIN_SIZE) > self.input.remaining() {
410            return Err(e);
411        }
412        if self.input.custom_items.is_none() {
413            return T::read_items(len, self.input);
414        }
415        (0..len).map(|_| self.read::<T>()).collect()
416    }
417
418    /// The stream, for what the methods above do not cover.
419    pub fn stream(&mut self) -> &mut InStream<'a> {
420        self.input
421    }
422}