rustorb-dds-ros2 0.4.0

The ROS 2 conventions on DDS for rustorb-dds: names, interface types from .msg/.srv, RIHS01 type hashes, node discovery
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Values of ROS 2 messages as a tree of named fields, to and from
//! [`DynamicData`].
//!
//! [`Value`] is what a program that does not know the types at build
//! time (a bridge to another middleware, a tool) works with: a struct is
//! its fields by name, in order. [`MessageType::to_data`] makes the
//! DynamicData of a value and checks it against the type: an integer
//! out of the range of its field, a string longer than its bound, an
//! array of another length or a sequence longer than its bound, a field
//! the message does not have, are errors. Fields the value leaves out
//! take their default (from the `.msg` file, else zero, empty).
//! [`MessageType::from_data`] reads one back.

use rustorb_xtypes::dynamic::{DynamicData, DynamicDataFactory, MEMBER_ID_INVALID};

use crate::library::{BaseType, FieldType, MessageType};
use crate::msg::{ArraySpec, Primitive};
use crate::{Error, Result};

/// A value of a field of a ROS 2 message.
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
    /// `bool`.
    Bool(bool),
    /// A signed integer (`int8` to `int64`).
    Int(i64),
    /// An unsigned integer (`uint8` to `uint64`, `char`, `byte`).
    UInt(u64),
    /// `float32` or `float64`.
    Float(f64),
    /// `string` or `wstring`.
    String(String),
    /// An array or a sequence of `byte`, `uint8` or `char`.
    Bytes(Vec<u8>),
    /// An array or a sequence of other elements.
    List(Vec<Value>),
    /// A message: its fields by name, in order.
    Struct(Vec<(String, Value)>),
}

impl Value {
    /// The field `name` of a struct.
    pub fn get(&self, name: &str) -> Option<&Value> {
        match self {
            Value::Struct(fields) => fields.iter().find(|(n, _)| n == name).map(|(_, v)| v),
            _ => None,
        }
    }

    fn kind(&self) -> &'static str {
        match self {
            Value::Bool(_) => "a bool",
            Value::Int(_) => "an integer",
            Value::UInt(_) => "an unsigned integer",
            Value::Float(_) => "a float",
            Value::String(_) => "a string",
            Value::Bytes(_) => "bytes",
            Value::List(_) => "a list",
            Value::Struct(_) => "a struct",
        }
    }

    fn as_i128(&self) -> Option<i128> {
        match self {
            Value::Int(v) => Some(*v as i128),
            Value::UInt(v) => Some(*v as i128),
            Value::Bool(b) => Some(*b as i128),
            _ => None,
        }
    }
}

fn err(path: &str, what: impl std::fmt::Display) -> Error {
    Error::Value(format!(
        "{}: {what}",
        if path.is_empty() { "." } else { path }
    ))
}

fn is_octet(p: Primitive) -> bool {
    matches!(p, Primitive::Byte | Primitive::Uint8 | Primitive::Char)
}

/// Writes a primitive `v` into `d` itself.
fn write_primitive(d: &mut DynamicData, p: Primitive, v: &Value, path: &str) -> Result<()> {
    let id = MEMBER_ID_INVALID;
    let r = match p {
        Primitive::Bool => match v {
            Value::Bool(b) => d.set_boolean_value(id, *b),
            _ => return Err(err(path, format!("{} for a bool", v.kind()))),
        },
        Primitive::Float32 | Primitive::Float64 => {
            let f = match v {
                Value::Float(f) => *f,
                Value::Int(i) => *i as f64,
                Value::UInt(u) => *u as f64,
                _ => return Err(err(path, format!("{} for a {}", v.kind(), p.name()))),
            };
            if p == Primitive::Float32 {
                if f.is_finite() && f.abs() > f32::MAX as f64 {
                    return Err(err(path, format!("{f} is out of the range of a float32")));
                }
                d.set_float32_value(id, f as f32)
            } else {
                d.set_float64_value(id, f)
            }
        }
        _ => {
            let (lo, hi) = p.integer_range().expect("an integer");
            let i = v
                .as_i128()
                .filter(|_| !matches!(v, Value::Bool(_)))
                .ok_or_else(|| err(path, format!("{} for a {}", v.kind(), p.name())))?;
            if i < lo || i > hi {
                return Err(err(
                    path,
                    format!("{i} is out of the range of a {}", p.name()),
                ));
            }
            match p {
                Primitive::Byte => d.set_byte_value(id, i as u8),
                Primitive::Char | Primitive::Uint8 => d.set_uint8_value(id, i as u8),
                Primitive::Int8 => d.set_int8_value(id, i as i8),
                Primitive::Int16 => d.set_int16_value(id, i as i16),
                Primitive::Uint16 => d.set_uint16_value(id, i as u16),
                Primitive::Int32 => d.set_int32_value(id, i as i32),
                Primitive::Uint32 => d.set_uint32_value(id, i as u32),
                Primitive::Int64 => d.set_int64_value(id, i as i64),
                Primitive::Uint64 => d.set_uint64_value(id, i as u64),
                _ => unreachable!("an integer"),
            }
        }
    };
    r.map_err(|e| err(path, e))
}

fn read_primitive(d: &DynamicData, p: Primitive) -> rustorb_xtypes::Result<Value> {
    let id = MEMBER_ID_INVALID;
    Ok(match p {
        Primitive::Bool => Value::Bool(d.get_boolean_value(id)?),
        Primitive::Byte => Value::UInt(d.get_byte_value(id)? as u64),
        Primitive::Char | Primitive::Uint8 => Value::UInt(d.get_uint8_value(id)? as u64),
        Primitive::Int8 => Value::Int(d.get_int8_value(id)? as i64),
        Primitive::Int16 => Value::Int(d.get_int16_value(id)? as i64),
        Primitive::Uint16 => Value::UInt(d.get_uint16_value(id)? as u64),
        Primitive::Int32 => Value::Int(d.get_int32_value(id)? as i64),
        Primitive::Uint32 => Value::UInt(d.get_uint32_value(id)? as u64),
        Primitive::Int64 => Value::Int(d.get_int64_value(id)?),
        Primitive::Uint64 => Value::UInt(d.get_uint64_value(id)?),
        Primitive::Float32 => Value::Float(d.get_float32_value(id)? as f64),
        Primitive::Float64 => Value::Float(d.get_float64_value(id)?),
    })
}

/// Writes one element (not an array) of type `base` into `d` itself.
fn write_element(d: &mut DynamicData, base: &BaseType, v: &Value, path: &str) -> Result<()> {
    match base {
        BaseType::Primitive(p) => write_primitive(d, *p, v, path),
        BaseType::String { wide, bound } => {
            let Value::String(s) = v else {
                return Err(err(path, format!("{} for a string", v.kind())));
            };
            if let Some(b) = bound
                && s.chars().count() > *b as usize
            {
                return Err(err(path, format!("a string longer than its bound {b}")));
            }
            if *wide {
                d.set_wstring_value(MEMBER_ID_INVALID, s)
            } else {
                d.set_string_value(MEMBER_ID_INVALID, s)
            }
            .map_err(|e| err(path, e))
        }
        BaseType::Message(m) => write_struct(d, m, v, path),
    }
}

/// Writes a field of type `ty` into `d` itself.
fn write_field(d: &mut DynamicData, ty: &FieldType, v: &Value, path: &str) -> Result<()> {
    if ty.array == ArraySpec::None {
        return write_element(d, &ty.base, v, path);
    }
    let len = match v {
        Value::List(l) => l.len(),
        Value::Bytes(b) => b.len(),
        _ => {
            return Err(err(
                path,
                format!("{} for an array or a sequence", v.kind()),
            ));
        }
    };
    match ty.array {
        ArraySpec::Fixed(n) if len != n as usize => {
            return Err(err(path, format!("{len} elements for an array of {n}")));
        }
        ArraySpec::Bounded(n) if len > n as usize => {
            return Err(err(
                path,
                format!("{len} elements for a sequence bounded to {n}"),
            ));
        }
        _ => {}
    }
    if let (BaseType::Primitive(p), Value::Bytes(b)) = (&ty.base, v) {
        if !is_octet(*p) {
            return Err(err(path, format!("bytes for an array of {}", p.name())));
        }
        let r = match p {
            Primitive::Byte => d.set_byte_values(MEMBER_ID_INVALID, b),
            _ => d.set_uint8_values(MEMBER_ID_INVALID, b),
        };
        return r.map_err(|e| err(path, e));
    }
    let Value::List(items) = v else {
        unreachable!("a list")
    };
    if !matches!(ty.array, ArraySpec::Fixed(_)) {
        // A sequence: empty it first.
        d.clear_all_values().map_err(|e| err(path, e))?;
    }
    for (i, item) in items.iter().enumerate() {
        let p = format!("{path}[{i}]");
        let e = d.loan_value(i as u32).map_err(|e| err(&p, e))?;
        write_element(e, &ty.base, item, &p)?;
    }
    Ok(())
}

/// Writes a message `v` (a [`Value::Struct`]) into `d` itself; the
/// fields it leaves out take their defaults.
fn write_struct(d: &mut DynamicData, m: &MessageType, v: &Value, path: &str) -> Result<()> {
    let Value::Struct(given) = v else {
        return Err(err(
            path,
            format!("{} for the message {}", v.kind(), m.name()),
        ));
    };
    for (name, _) in given {
        if !m.fields().iter().any(|f| &f.name == name) {
            return Err(err(path, format!("{} has no field {name}", m.name())));
        }
    }
    for (i, f) in m.fields().iter().enumerate() {
        let p = if path.is_empty() {
            f.name.clone()
        } else {
            format!("{path}.{}", f.name)
        };
        let value = given.iter().find(|(n, _)| n == &f.name).map(|(_, v)| v);
        let value = match (value, &f.default, &f.ty) {
            (Some(v), _, _) => v,
            (None, Some(d), _) => d,
            (
                None,
                None,
                FieldType {
                    base: BaseType::Message(_),
                    array: ArraySpec::None,
                },
            ) => &Value::Struct(Vec::new()),
            (None, None, _) => continue,
        };
        let e = d.loan_value(i as u32).map_err(|e| err(&p, e))?;
        write_field(e, &f.ty, value, &p)?;
    }
    Ok(())
}

fn read_element(d: &DynamicData, base: &BaseType) -> rustorb_xtypes::Result<Value> {
    match base {
        BaseType::Primitive(p) => read_primitive(d, *p),
        BaseType::String { wide: false, .. } => {
            Ok(Value::String(d.get_string_value(MEMBER_ID_INVALID)?))
        }
        BaseType::String { wide: true, .. } => {
            Ok(Value::String(d.get_wstring_value(MEMBER_ID_INVALID)?))
        }
        BaseType::Message(m) => read_struct(d, m),
    }
}

fn read_field(d: &DynamicData, ty: &FieldType) -> rustorb_xtypes::Result<Value> {
    if ty.array == ArraySpec::None {
        return read_element(d, &ty.base);
    }
    match ty.base {
        BaseType::Primitive(Primitive::Byte) => {
            Ok(Value::Bytes(d.get_byte_values(MEMBER_ID_INVALID)?))
        }
        BaseType::Primitive(Primitive::Uint8 | Primitive::Char) => {
            Ok(Value::Bytes(d.get_uint8_values(MEMBER_ID_INVALID)?))
        }
        _ => (0..d.get_item_count())
            .map(|i| read_element(d.get_value(i)?, &ty.base))
            .collect::<rustorb_xtypes::Result<Vec<_>>>()
            .map(Value::List),
    }
}

fn read_struct(d: &DynamicData, m: &MessageType) -> rustorb_xtypes::Result<Value> {
    m.fields()
        .iter()
        .enumerate()
        .map(|(i, f)| Ok((f.name.clone(), read_field(d.get_value(i as u32)?, &f.ty)?)))
        .collect::<rustorb_xtypes::Result<Vec<_>>>()
        .map(Value::Struct)
}

impl MessageType {
    /// A DynamicData of this message with the defaults of its fields.
    pub fn new_data(&self) -> DynamicData {
        self.to_data(&Value::Struct(Vec::new()))
            .expect("the defaults are checked when the type is made")
    }

    /// The DynamicData of `value`, a [`Value::Struct`], checked against
    /// this type; the fields it leaves out take their defaults.
    pub fn to_data(&self, value: &Value) -> Result<DynamicData> {
        let mut d = DynamicDataFactory::create_data(self.dynamic_type());
        write_struct(&mut d, self, value, "")?;
        Ok(d)
    }

    /// The value of a DynamicData of this type.
    pub fn from_data(&self, data: &DynamicData) -> Result<Value> {
        if data.get_type().get_name() != self.dynamic_type().get_name() {
            return Err(Error::Value(format!(
                "a DynamicData of {}, not of {}",
                data.get_type().get_name(),
                self.name().dds_name()
            )));
        }
        read_struct(data, self).map_err(|e| Error::Value(e.to_string()))
    }

    /// The value of this message with the defaults of its fields.
    pub fn default_value(&self) -> Value {
        self.from_data(&self.new_data())
            .expect("a DynamicData of this type")
    }
}

/// Parses a value written in a `.msg` file (a default or a constant) for
/// a field of type `ty`.
pub(crate) fn parse_literal(ty: &FieldType, s: &str) -> Result<Value> {
    let s = s.trim();
    if ty.array == ArraySpec::None {
        return parse_scalar(&ty.base, s);
    }
    let inner = s
        .strip_prefix('[')
        .and_then(|r| r.strip_suffix(']'))
        .ok_or_else(|| Error::Parse(format!("{s:?} is not a list [a, b, ...]")))?;
    let items: Vec<Value> = split_list(inner)?
        .iter()
        .map(|item| parse_scalar(&ty.base, item))
        .collect::<Result<_>>()?;
    match ty.base {
        BaseType::Primitive(p) if is_octet(p) => Ok(Value::Bytes(
            items
                .iter()
                .map(|v| match v {
                    Value::UInt(u) => *u as u8,
                    _ => unreachable!("parsed as an octet"),
                })
                .collect(),
        )),
        _ => Ok(Value::List(items)),
    }
}

/// The items of a list, split at the commas that are not in a string.
fn split_list(s: &str) -> Result<Vec<String>> {
    let mut items = Vec::new();
    let mut current = String::new();
    let mut quote: Option<char> = None;
    let mut escaped = false;
    for c in s.chars() {
        if escaped {
            escaped = false;
        } else if let Some(q) = quote {
            if c == '\\' {
                escaped = true;
            } else if c == q {
                quote = None;
            }
        } else if c == '"' || c == '\'' {
            quote = Some(c);
        } else if c == ',' {
            items.push(std::mem::take(&mut current).trim().to_string());
            continue;
        }
        current.push(c);
    }
    if quote.is_some() {
        return Err(Error::Parse(format!("{s:?}: a string is not closed")));
    }
    let last = current.trim().to_string();
    if !last.is_empty() {
        items.push(last);
    } else if !items.is_empty() {
        return Err(Error::Parse(format!("{s:?}: an empty item")));
    }
    Ok(items)
}

fn unquote(s: &str) -> Result<String> {
    match s.chars().next() {
        Some(c @ ('"' | '\'')) if s.len() >= 2 && s.ends_with(c) => {}
        _ => return Ok(s.to_string()),
    }
    let body = &s[1..s.len() - 1];
    let mut out = String::new();
    let mut chars = body.chars();
    while let Some(c) = chars.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        match chars.next() {
            Some('n') => out.push('\n'),
            Some('t') => out.push('\t'),
            Some('r') => out.push('\r'),
            Some(c) => out.push(c),
            None => return Err(Error::Parse(format!("{s:?} ends with '\\'"))),
        }
    }
    Ok(out)
}

fn parse_scalar(base: &BaseType, s: &str) -> Result<Value> {
    let bad = || Error::Parse(format!("{s:?} is not a value of {}", base.describe()));
    match base {
        BaseType::Primitive(Primitive::Bool) => match s.to_ascii_lowercase().as_str() {
            "true" | "1" => Ok(Value::Bool(true)),
            "false" | "0" => Ok(Value::Bool(false)),
            _ => Err(bad()),
        },
        BaseType::Primitive(Primitive::Float32 | Primitive::Float64) => {
            s.parse::<f64>().map(Value::Float).map_err(|_| bad())
        }
        BaseType::Primitive(p) => {
            let (neg, digits) = match s.strip_prefix('-') {
                Some(d) => (true, d),
                None => (false, s.strip_prefix('+').unwrap_or(s)),
            };
            let v = match digits
                .strip_prefix("0x")
                .or_else(|| digits.strip_prefix("0X"))
            {
                Some(h) => i128::from_str_radix(h, 16),
                None => digits.parse::<i128>(),
            }
            .map_err(|_| bad())?;
            let v = if neg { -v } else { v };
            let (lo, hi) = p.integer_range().expect("an integer");
            if v < lo || v > hi {
                return Err(Error::Parse(format!(
                    "{s} is out of the range of a {}",
                    p.name()
                )));
            }
            Ok(if lo < 0 {
                Value::Int(v as i64)
            } else {
                Value::UInt(v as u64)
            })
        }
        BaseType::String { bound, .. } => {
            let v = unquote(s)?;
            if let Some(b) = bound
                && v.chars().count() > *b as usize
            {
                return Err(Error::Parse(format!("{s:?} is longer than the bound {b}")));
            }
            Ok(Value::String(v))
        }
        BaseType::Message(_) => Err(Error::Parse(format!(
            "{s:?}: a message field cannot have a default"
        ))),
    }
}

/// Checks the length of a parsed array value against its type.
pub(crate) fn check_length(ty: &FieldType, v: &Value) -> Result<()> {
    let len = match v {
        Value::List(l) => l.len(),
        Value::Bytes(b) => b.len(),
        _ => return Ok(()),
    };
    match ty.array {
        ArraySpec::Fixed(n) if len != n as usize => {
            Err(Error::Parse(format!("{len} elements for an array of {n}")))
        }
        ArraySpec::Bounded(n) if len > n as usize => Err(Error::Parse(format!(
            "{len} elements for a sequence bounded to {n}"
        ))),
        _ => Ok(()),
    }
}