Skip to main content

rustorb_dds_ros2/
value.rs

1//! Values of ROS 2 messages as a tree of named fields, to and from
2//! [`DynamicData`].
3//!
4//! [`Value`] is what a program that does not know the types at build
5//! time (a bridge to another middleware, a tool) works with: a struct is
6//! its fields by name, in order. [`MessageType::to_data`] makes the
7//! DynamicData of a value and checks it against the type: an integer
8//! out of the range of its field, a string longer than its bound, an
9//! array of another length or a sequence longer than its bound, a field
10//! the message does not have, are errors. Fields the value leaves out
11//! take their default (from the `.msg` file, else zero, empty).
12//! [`MessageType::from_data`] reads one back.
13
14use rustorb_xtypes::dynamic::{DynamicData, DynamicDataFactory, MEMBER_ID_INVALID};
15
16use crate::library::{BaseType, FieldType, MessageType};
17use crate::msg::{ArraySpec, Primitive};
18use crate::{Error, Result};
19
20/// A value of a field of a ROS 2 message.
21#[derive(Clone, Debug, PartialEq)]
22pub enum Value {
23    /// `bool`.
24    Bool(bool),
25    /// A signed integer (`int8` to `int64`).
26    Int(i64),
27    /// An unsigned integer (`uint8` to `uint64`, `char`, `byte`).
28    UInt(u64),
29    /// `float32` or `float64`.
30    Float(f64),
31    /// `string` or `wstring`.
32    String(String),
33    /// An array or a sequence of `byte`, `uint8` or `char`.
34    Bytes(Vec<u8>),
35    /// An array or a sequence of other elements.
36    List(Vec<Value>),
37    /// A message: its fields by name, in order.
38    Struct(Vec<(String, Value)>),
39}
40
41impl Value {
42    /// The field `name` of a struct.
43    pub fn get(&self, name: &str) -> Option<&Value> {
44        match self {
45            Value::Struct(fields) => fields.iter().find(|(n, _)| n == name).map(|(_, v)| v),
46            _ => None,
47        }
48    }
49
50    fn kind(&self) -> &'static str {
51        match self {
52            Value::Bool(_) => "a bool",
53            Value::Int(_) => "an integer",
54            Value::UInt(_) => "an unsigned integer",
55            Value::Float(_) => "a float",
56            Value::String(_) => "a string",
57            Value::Bytes(_) => "bytes",
58            Value::List(_) => "a list",
59            Value::Struct(_) => "a struct",
60        }
61    }
62
63    fn as_i128(&self) -> Option<i128> {
64        match self {
65            Value::Int(v) => Some(*v as i128),
66            Value::UInt(v) => Some(*v as i128),
67            Value::Bool(b) => Some(*b as i128),
68            _ => None,
69        }
70    }
71}
72
73fn err(path: &str, what: impl std::fmt::Display) -> Error {
74    Error::Value(format!(
75        "{}: {what}",
76        if path.is_empty() { "." } else { path }
77    ))
78}
79
80fn is_octet(p: Primitive) -> bool {
81    matches!(p, Primitive::Byte | Primitive::Uint8 | Primitive::Char)
82}
83
84/// Writes a primitive `v` into `d` itself.
85fn write_primitive(d: &mut DynamicData, p: Primitive, v: &Value, path: &str) -> Result<()> {
86    let id = MEMBER_ID_INVALID;
87    let r = match p {
88        Primitive::Bool => match v {
89            Value::Bool(b) => d.set_boolean_value(id, *b),
90            _ => return Err(err(path, format!("{} for a bool", v.kind()))),
91        },
92        Primitive::Float32 | Primitive::Float64 => {
93            let f = match v {
94                Value::Float(f) => *f,
95                Value::Int(i) => *i as f64,
96                Value::UInt(u) => *u as f64,
97                _ => return Err(err(path, format!("{} for a {}", v.kind(), p.name()))),
98            };
99            if p == Primitive::Float32 {
100                if f.is_finite() && f.abs() > f32::MAX as f64 {
101                    return Err(err(path, format!("{f} is out of the range of a float32")));
102                }
103                d.set_float32_value(id, f as f32)
104            } else {
105                d.set_float64_value(id, f)
106            }
107        }
108        _ => {
109            let (lo, hi) = p.integer_range().expect("an integer");
110            let i = v
111                .as_i128()
112                .filter(|_| !matches!(v, Value::Bool(_)))
113                .ok_or_else(|| err(path, format!("{} for a {}", v.kind(), p.name())))?;
114            if i < lo || i > hi {
115                return Err(err(
116                    path,
117                    format!("{i} is out of the range of a {}", p.name()),
118                ));
119            }
120            match p {
121                Primitive::Byte => d.set_byte_value(id, i as u8),
122                Primitive::Char | Primitive::Uint8 => d.set_uint8_value(id, i as u8),
123                Primitive::Int8 => d.set_int8_value(id, i as i8),
124                Primitive::Int16 => d.set_int16_value(id, i as i16),
125                Primitive::Uint16 => d.set_uint16_value(id, i as u16),
126                Primitive::Int32 => d.set_int32_value(id, i as i32),
127                Primitive::Uint32 => d.set_uint32_value(id, i as u32),
128                Primitive::Int64 => d.set_int64_value(id, i as i64),
129                Primitive::Uint64 => d.set_uint64_value(id, i as u64),
130                _ => unreachable!("an integer"),
131            }
132        }
133    };
134    r.map_err(|e| err(path, e))
135}
136
137fn read_primitive(d: &DynamicData, p: Primitive) -> rustorb_xtypes::Result<Value> {
138    let id = MEMBER_ID_INVALID;
139    Ok(match p {
140        Primitive::Bool => Value::Bool(d.get_boolean_value(id)?),
141        Primitive::Byte => Value::UInt(d.get_byte_value(id)? as u64),
142        Primitive::Char | Primitive::Uint8 => Value::UInt(d.get_uint8_value(id)? as u64),
143        Primitive::Int8 => Value::Int(d.get_int8_value(id)? as i64),
144        Primitive::Int16 => Value::Int(d.get_int16_value(id)? as i64),
145        Primitive::Uint16 => Value::UInt(d.get_uint16_value(id)? as u64),
146        Primitive::Int32 => Value::Int(d.get_int32_value(id)? as i64),
147        Primitive::Uint32 => Value::UInt(d.get_uint32_value(id)? as u64),
148        Primitive::Int64 => Value::Int(d.get_int64_value(id)?),
149        Primitive::Uint64 => Value::UInt(d.get_uint64_value(id)?),
150        Primitive::Float32 => Value::Float(d.get_float32_value(id)? as f64),
151        Primitive::Float64 => Value::Float(d.get_float64_value(id)?),
152    })
153}
154
155/// Writes one element (not an array) of type `base` into `d` itself.
156fn write_element(d: &mut DynamicData, base: &BaseType, v: &Value, path: &str) -> Result<()> {
157    match base {
158        BaseType::Primitive(p) => write_primitive(d, *p, v, path),
159        BaseType::String { wide, bound } => {
160            let Value::String(s) = v else {
161                return Err(err(path, format!("{} for a string", v.kind())));
162            };
163            if let Some(b) = bound
164                && s.chars().count() > *b as usize
165            {
166                return Err(err(path, format!("a string longer than its bound {b}")));
167            }
168            if *wide {
169                d.set_wstring_value(MEMBER_ID_INVALID, s)
170            } else {
171                d.set_string_value(MEMBER_ID_INVALID, s)
172            }
173            .map_err(|e| err(path, e))
174        }
175        BaseType::Message(m) => write_struct(d, m, v, path),
176    }
177}
178
179/// Writes a field of type `ty` into `d` itself.
180fn write_field(d: &mut DynamicData, ty: &FieldType, v: &Value, path: &str) -> Result<()> {
181    if ty.array == ArraySpec::None {
182        return write_element(d, &ty.base, v, path);
183    }
184    let len = match v {
185        Value::List(l) => l.len(),
186        Value::Bytes(b) => b.len(),
187        _ => {
188            return Err(err(
189                path,
190                format!("{} for an array or a sequence", v.kind()),
191            ));
192        }
193    };
194    match ty.array {
195        ArraySpec::Fixed(n) if len != n as usize => {
196            return Err(err(path, format!("{len} elements for an array of {n}")));
197        }
198        ArraySpec::Bounded(n) if len > n as usize => {
199            return Err(err(
200                path,
201                format!("{len} elements for a sequence bounded to {n}"),
202            ));
203        }
204        _ => {}
205    }
206    if let (BaseType::Primitive(p), Value::Bytes(b)) = (&ty.base, v) {
207        if !is_octet(*p) {
208            return Err(err(path, format!("bytes for an array of {}", p.name())));
209        }
210        let r = match p {
211            Primitive::Byte => d.set_byte_values(MEMBER_ID_INVALID, b),
212            _ => d.set_uint8_values(MEMBER_ID_INVALID, b),
213        };
214        return r.map_err(|e| err(path, e));
215    }
216    let Value::List(items) = v else {
217        unreachable!("a list")
218    };
219    if !matches!(ty.array, ArraySpec::Fixed(_)) {
220        // A sequence: empty it first.
221        d.clear_all_values().map_err(|e| err(path, e))?;
222    }
223    for (i, item) in items.iter().enumerate() {
224        let p = format!("{path}[{i}]");
225        let e = d.loan_value(i as u32).map_err(|e| err(&p, e))?;
226        write_element(e, &ty.base, item, &p)?;
227    }
228    Ok(())
229}
230
231/// Writes a message `v` (a [`Value::Struct`]) into `d` itself; the
232/// fields it leaves out take their defaults.
233fn write_struct(d: &mut DynamicData, m: &MessageType, v: &Value, path: &str) -> Result<()> {
234    let Value::Struct(given) = v else {
235        return Err(err(
236            path,
237            format!("{} for the message {}", v.kind(), m.name()),
238        ));
239    };
240    for (name, _) in given {
241        if !m.fields().iter().any(|f| &f.name == name) {
242            return Err(err(path, format!("{} has no field {name}", m.name())));
243        }
244    }
245    for (i, f) in m.fields().iter().enumerate() {
246        let p = if path.is_empty() {
247            f.name.clone()
248        } else {
249            format!("{path}.{}", f.name)
250        };
251        let value = given.iter().find(|(n, _)| n == &f.name).map(|(_, v)| v);
252        let value = match (value, &f.default, &f.ty) {
253            (Some(v), _, _) => v,
254            (None, Some(d), _) => d,
255            (
256                None,
257                None,
258                FieldType {
259                    base: BaseType::Message(_),
260                    array: ArraySpec::None,
261                },
262            ) => &Value::Struct(Vec::new()),
263            (None, None, _) => continue,
264        };
265        let e = d.loan_value(i as u32).map_err(|e| err(&p, e))?;
266        write_field(e, &f.ty, value, &p)?;
267    }
268    Ok(())
269}
270
271fn read_element(d: &DynamicData, base: &BaseType) -> rustorb_xtypes::Result<Value> {
272    match base {
273        BaseType::Primitive(p) => read_primitive(d, *p),
274        BaseType::String { wide: false, .. } => {
275            Ok(Value::String(d.get_string_value(MEMBER_ID_INVALID)?))
276        }
277        BaseType::String { wide: true, .. } => {
278            Ok(Value::String(d.get_wstring_value(MEMBER_ID_INVALID)?))
279        }
280        BaseType::Message(m) => read_struct(d, m),
281    }
282}
283
284fn read_field(d: &DynamicData, ty: &FieldType) -> rustorb_xtypes::Result<Value> {
285    if ty.array == ArraySpec::None {
286        return read_element(d, &ty.base);
287    }
288    match ty.base {
289        BaseType::Primitive(Primitive::Byte) => {
290            Ok(Value::Bytes(d.get_byte_values(MEMBER_ID_INVALID)?))
291        }
292        BaseType::Primitive(Primitive::Uint8 | Primitive::Char) => {
293            Ok(Value::Bytes(d.get_uint8_values(MEMBER_ID_INVALID)?))
294        }
295        _ => (0..d.get_item_count())
296            .map(|i| read_element(d.get_value(i)?, &ty.base))
297            .collect::<rustorb_xtypes::Result<Vec<_>>>()
298            .map(Value::List),
299    }
300}
301
302fn read_struct(d: &DynamicData, m: &MessageType) -> rustorb_xtypes::Result<Value> {
303    m.fields()
304        .iter()
305        .enumerate()
306        .map(|(i, f)| Ok((f.name.clone(), read_field(d.get_value(i as u32)?, &f.ty)?)))
307        .collect::<rustorb_xtypes::Result<Vec<_>>>()
308        .map(Value::Struct)
309}
310
311impl MessageType {
312    /// A DynamicData of this message with the defaults of its fields.
313    pub fn new_data(&self) -> DynamicData {
314        self.to_data(&Value::Struct(Vec::new()))
315            .expect("the defaults are checked when the type is made")
316    }
317
318    /// The DynamicData of `value`, a [`Value::Struct`], checked against
319    /// this type; the fields it leaves out take their defaults.
320    pub fn to_data(&self, value: &Value) -> Result<DynamicData> {
321        let mut d = DynamicDataFactory::create_data(self.dynamic_type());
322        write_struct(&mut d, self, value, "")?;
323        Ok(d)
324    }
325
326    /// The value of a DynamicData of this type.
327    pub fn from_data(&self, data: &DynamicData) -> Result<Value> {
328        if data.get_type().get_name() != self.dynamic_type().get_name() {
329            return Err(Error::Value(format!(
330                "a DynamicData of {}, not of {}",
331                data.get_type().get_name(),
332                self.name().dds_name()
333            )));
334        }
335        read_struct(data, self).map_err(|e| Error::Value(e.to_string()))
336    }
337
338    /// The value of this message with the defaults of its fields.
339    pub fn default_value(&self) -> Value {
340        self.from_data(&self.new_data())
341            .expect("a DynamicData of this type")
342    }
343}
344
345/// Parses a value written in a `.msg` file (a default or a constant) for
346/// a field of type `ty`.
347pub(crate) fn parse_literal(ty: &FieldType, s: &str) -> Result<Value> {
348    let s = s.trim();
349    if ty.array == ArraySpec::None {
350        return parse_scalar(&ty.base, s);
351    }
352    let inner = s
353        .strip_prefix('[')
354        .and_then(|r| r.strip_suffix(']'))
355        .ok_or_else(|| Error::Parse(format!("{s:?} is not a list [a, b, ...]")))?;
356    let items: Vec<Value> = split_list(inner)?
357        .iter()
358        .map(|item| parse_scalar(&ty.base, item))
359        .collect::<Result<_>>()?;
360    match ty.base {
361        BaseType::Primitive(p) if is_octet(p) => Ok(Value::Bytes(
362            items
363                .iter()
364                .map(|v| match v {
365                    Value::UInt(u) => *u as u8,
366                    _ => unreachable!("parsed as an octet"),
367                })
368                .collect(),
369        )),
370        _ => Ok(Value::List(items)),
371    }
372}
373
374/// The items of a list, split at the commas that are not in a string.
375fn split_list(s: &str) -> Result<Vec<String>> {
376    let mut items = Vec::new();
377    let mut current = String::new();
378    let mut quote: Option<char> = None;
379    let mut escaped = false;
380    for c in s.chars() {
381        if escaped {
382            escaped = false;
383        } else if let Some(q) = quote {
384            if c == '\\' {
385                escaped = true;
386            } else if c == q {
387                quote = None;
388            }
389        } else if c == '"' || c == '\'' {
390            quote = Some(c);
391        } else if c == ',' {
392            items.push(std::mem::take(&mut current).trim().to_string());
393            continue;
394        }
395        current.push(c);
396    }
397    if quote.is_some() {
398        return Err(Error::Parse(format!("{s:?}: a string is not closed")));
399    }
400    let last = current.trim().to_string();
401    if !last.is_empty() {
402        items.push(last);
403    } else if !items.is_empty() {
404        return Err(Error::Parse(format!("{s:?}: an empty item")));
405    }
406    Ok(items)
407}
408
409fn unquote(s: &str) -> Result<String> {
410    match s.chars().next() {
411        Some(c @ ('"' | '\'')) if s.len() >= 2 && s.ends_with(c) => {}
412        _ => return Ok(s.to_string()),
413    }
414    let body = &s[1..s.len() - 1];
415    let mut out = String::new();
416    let mut chars = body.chars();
417    while let Some(c) = chars.next() {
418        if c != '\\' {
419            out.push(c);
420            continue;
421        }
422        match chars.next() {
423            Some('n') => out.push('\n'),
424            Some('t') => out.push('\t'),
425            Some('r') => out.push('\r'),
426            Some(c) => out.push(c),
427            None => return Err(Error::Parse(format!("{s:?} ends with '\\'"))),
428        }
429    }
430    Ok(out)
431}
432
433fn parse_scalar(base: &BaseType, s: &str) -> Result<Value> {
434    let bad = || Error::Parse(format!("{s:?} is not a value of {}", base.describe()));
435    match base {
436        BaseType::Primitive(Primitive::Bool) => match s.to_ascii_lowercase().as_str() {
437            "true" | "1" => Ok(Value::Bool(true)),
438            "false" | "0" => Ok(Value::Bool(false)),
439            _ => Err(bad()),
440        },
441        BaseType::Primitive(Primitive::Float32 | Primitive::Float64) => {
442            s.parse::<f64>().map(Value::Float).map_err(|_| bad())
443        }
444        BaseType::Primitive(p) => {
445            let (neg, digits) = match s.strip_prefix('-') {
446                Some(d) => (true, d),
447                None => (false, s.strip_prefix('+').unwrap_or(s)),
448            };
449            let v = match digits
450                .strip_prefix("0x")
451                .or_else(|| digits.strip_prefix("0X"))
452            {
453                Some(h) => i128::from_str_radix(h, 16),
454                None => digits.parse::<i128>(),
455            }
456            .map_err(|_| bad())?;
457            let v = if neg { -v } else { v };
458            let (lo, hi) = p.integer_range().expect("an integer");
459            if v < lo || v > hi {
460                return Err(Error::Parse(format!(
461                    "{s} is out of the range of a {}",
462                    p.name()
463                )));
464            }
465            Ok(if lo < 0 {
466                Value::Int(v as i64)
467            } else {
468                Value::UInt(v as u64)
469            })
470        }
471        BaseType::String { bound, .. } => {
472            let v = unquote(s)?;
473            if let Some(b) = bound
474                && v.chars().count() > *b as usize
475            {
476                return Err(Error::Parse(format!("{s:?} is longer than the bound {b}")));
477            }
478            Ok(Value::String(v))
479        }
480        BaseType::Message(_) => Err(Error::Parse(format!(
481            "{s:?}: a message field cannot have a default"
482        ))),
483    }
484}
485
486/// Checks the length of a parsed array value against its type.
487pub(crate) fn check_length(ty: &FieldType, v: &Value) -> Result<()> {
488    let len = match v {
489        Value::List(l) => l.len(),
490        Value::Bytes(b) => b.len(),
491        _ => return Ok(()),
492    };
493    match ty.array {
494        ArraySpec::Fixed(n) if len != n as usize => {
495            Err(Error::Parse(format!("{len} elements for an array of {n}")))
496        }
497        ArraySpec::Bounded(n) if len > n as usize => Err(Error::Parse(format!(
498            "{len} elements for a sequence bounded to {n}"
499        ))),
500        _ => Ok(()),
501    }
502}