rosidl_runtime_rs 0.4.0

Message generation code shared by Rust projects in ROS 2
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
use std::cmp::Ordering;
use std::ffi::CStr;
use std::fmt::{self, Debug, Display};
use std::hash::{Hash, Hasher};
use std::ops::{Deref, DerefMut};

#[cfg(feature = "serde")]
mod serde;

use crate::sequence::Sequence;
use crate::traits::SequenceAlloc;

/// A zero-terminated string of 8-bit characters.
///
/// The layout of this type is the same as `rosidl_runtime_c__String`. See the
/// [`Message`](crate::Message) trait for background information on this topic.
///
///
/// # Example
///
/// ```
/// # use rosidl_runtime_rs::String;
/// let mut s = String::from("Grüß Gott!");
/// // Conversion back to a std::string::String is done with the ToString trait from the standard
/// // library.
/// assert_eq!(&s.to_string(), "Grüß Gott!");
/// ```
#[repr(C)]
pub struct String {
    /// Dynamic memory in this type is allocated and deallocated by C, but this is a detail that is managed by
    /// the relevant functions and trait impls.
    data: *mut std::os::raw::c_char,
    size: usize,
    capacity: usize,
}

/// A zero-terminated string of 16-bit characters.
///
/// The layout of this type is the same as `rosidl_runtime_c__U16String`. See the
/// [`Message`](crate::Message) trait for background information on this topic.
///
/// # Example
///
/// ```
/// # use rosidl_runtime_rs::WString;
/// let mut s = WString::from("Grüß Gott!");
/// // Conversion back to a std::string::String is done with the ToString trait from the standard
/// // library.
/// assert_eq!(&s.to_string(), "Grüß Gott!");
/// ```
#[repr(C)]
pub struct WString {
    data: *mut std::os::raw::c_ushort,
    size: usize,
    capacity: usize,
}

/// A zero-terminated string of 8-bit characters with a length limit.
///
/// The same as [`String`], but it cannot be constructed from a string that is too large.
/// The length is measured as the number of Unicode scalar values, not bytes.
///
/// # Example
///
/// ```
/// # use rosidl_runtime_rs::BoundedString;
/// let mut maybe_str = BoundedString::<3>::try_from("noo!");
/// assert!(maybe_str.is_err());
/// maybe_str = BoundedString::<3>::try_from("ok!");
/// assert!(maybe_str.is_ok());
/// let bounded_str = maybe_str.unwrap();
/// assert_eq!(&bounded_str.to_string(), "ok!");
/// ```
#[derive(Clone, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
pub struct BoundedString<const N: usize> {
    inner: String,
}

/// A zero-terminated string of 16-bit characters with a length limit.
///
/// The same as [`WString`], but it cannot be constructed from a string that is too large.
/// The length is measured as the number of Unicode scalar values, not bytes.
///
/// # Example
///
/// ```
/// # use rosidl_runtime_rs::BoundedWString;
/// let mut maybe_wstr = BoundedWString::<3>::try_from("noo!");
/// assert!(maybe_wstr.is_err());
/// maybe_wstr = BoundedWString::<3>::try_from("ok!");
/// assert!(maybe_wstr.is_ok());
/// let bounded_wstr = maybe_wstr.unwrap();
/// assert_eq!(&bounded_wstr.to_string(), "ok!");
/// ```
#[derive(Clone, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
pub struct BoundedWString<const N: usize> {
    inner: WString,
}

/// Error type for [`BoundedString::try_from()`] and [`BoundedWString::try_from()`].
#[derive(Debug)]
pub struct StringExceedsBoundsError {
    /// The actual length the string would have after the operation.
    pub len: usize,
    /// The upper bound on the string length.
    pub upper_bound: usize,
}

// ========================= impls for String and WString =========================

// There is a lot of redundancy between String and WString, which this macro aims to reduce.
macro_rules! string_impl {
    ($string:ty, $char_type:ty, $unsigned_char_type:ty, $string_conversion_func:ident, $init:ident, $fini:ident, $assignn:ident, $sequence_init:ident, $sequence_fini:ident, $sequence_copy:ident) => {
        #[link(name = "rosidl_runtime_c")]
        extern "C" {
            fn $init(s: *mut $string) -> bool;
            fn $fini(s: *mut $string);
            fn $assignn(s: *mut $string, value: *const $char_type, n: usize) -> bool;
            fn $sequence_init(seq: *mut Sequence<$string>, size: usize) -> bool;
            fn $sequence_fini(seq: *mut Sequence<$string>);
            fn $sequence_copy(
                in_seq: *const Sequence<$string>,
                out_seq: *mut Sequence<$string>,
            ) -> bool;
        }

        impl Clone for $string {
            fn clone(&self) -> Self {
                let mut msg = Self::default();
                // SAFETY: This is doing the same thing as rosidl_runtime_c__String__copy.
                if !unsafe { $assignn(&mut msg as *mut _, self.data as *const _, self.size) } {
                    panic!("$assignn failed");
                }
                msg
            }
        }

        impl Debug for $string {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
                Debug::fmt(&self.to_string(), f)
            }
        }

        impl Default for $string {
            fn default() -> Self {
                let mut msg = Self {
                    data: std::ptr::null_mut(),
                    size: 0,
                    capacity: 0,
                };
                // SAFETY: Passing in a zeroed string is safe.
                if !unsafe { $init(&mut msg as *mut _) } {
                    panic!("$init failed");
                }
                msg
            }
        }

        // It's not guaranteed that there are no interior null bytes, hence no Deref to CStr.
        // This does not include the null byte at the end!
        impl Deref for $string {
            type Target = [$char_type];
            fn deref(&self) -> &Self::Target {
                // SAFETY: self.data points to self.size consecutive, initialized elements and
                // isn't modified externally.
                unsafe { std::slice::from_raw_parts(self.data, self.size) }
            }
        }

        impl DerefMut for $string {
            fn deref_mut(&mut self) -> &mut Self::Target {
                // SAFETY: self.data points to self.size consecutive, initialized elements and
                // isn't modified externally.
                unsafe { std::slice::from_raw_parts_mut(self.data, self.size) }
            }
        }

        impl Display for $string {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
                // SAFETY: Same as deref, but with an additional cast to the unsigned type.
                // See also https://users.rust-lang.org/t/how-to-convert-i8-to-u8/16308/11
                let u8_slice = unsafe {
                    std::slice::from_raw_parts(self.data as *mut $unsigned_char_type, self.size)
                };
                let converted = std::string::String::$string_conversion_func(u8_slice);
                Display::fmt(&converted, f)
            }
        }

        impl Drop for $string {
            fn drop(&mut self) {
                // SAFETY: There are no special preconditions to the fini function.
                unsafe {
                    $fini(self as *mut _);
                }
            }
        }

        impl Eq for $string {}

        impl Extend<char> for $string {
            fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
                let mut s = self.to_string();
                s.extend(iter);
                *self = Self::from(s.as_str());
            }
        }

        impl<'a> Extend<&'a char> for $string {
            fn extend<I: IntoIterator<Item = &'a char>>(&mut self, iter: I) {
                self.extend(iter.into_iter().cloned());
            }
        }

        impl FromIterator<char> for $string {
            fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> Self {
                let mut buf = <$string>::default();
                buf.extend(iter);
                buf
            }
        }

        impl<'a> FromIterator<&'a char> for $string {
            fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> Self {
                let mut buf = <$string>::default();
                buf.extend(iter);
                buf
            }
        }

        impl Hash for $string {
            fn hash<H: Hasher>(&self, state: &mut H) {
                self.deref().hash(state)
            }
        }

        impl Ord for $string {
            fn cmp(&self, other: &Self) -> Ordering {
                self.deref().cmp(other.deref())
            }
        }

        impl PartialEq for $string {
            fn eq(&self, other: &Self) -> bool {
                self.deref().eq(other.deref())
            }
        }

        impl PartialOrd for $string {
            fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
                self.deref().partial_cmp(other.deref())
            }
        }

        // SAFETY: A string is a simple data structure, and therefore not thread-specific.
        unsafe impl Send for $string {}
        // SAFETY: A string does not have interior mutability, so it can be shared.
        unsafe impl Sync for $string {}

        impl SequenceAlloc for $string {
            fn sequence_init(seq: &mut Sequence<Self>, size: usize) -> bool {
                // SAFETY: There are no special preconditions to the sequence_init function.
                unsafe { $sequence_init(seq as *mut _, size) }
            }
            fn sequence_fini(seq: &mut Sequence<Self>) {
                // SAFETY: There are no special preconditions to the sequence_fini function.
                unsafe { $sequence_fini(seq as *mut _) }
            }
            fn sequence_copy(in_seq: &Sequence<Self>, out_seq: &mut Sequence<Self>) -> bool {
                // SAFETY: There are no special preconditions to the sequence_copy function.
                unsafe { $sequence_copy(in_seq as *const _, out_seq as *mut _) }
            }
        }
    };
}

string_impl!(
    String,
    std::os::raw::c_char,
    u8,
    from_utf8_lossy,
    rosidl_runtime_c__String__init,
    rosidl_runtime_c__String__fini,
    rosidl_runtime_c__String__assignn,
    rosidl_runtime_c__String__Sequence__init,
    rosidl_runtime_c__String__Sequence__fini,
    rosidl_runtime_c__String__Sequence__copy
);
string_impl!(
    WString,
    std::os::raw::c_ushort,
    u16,
    from_utf16_lossy,
    rosidl_runtime_c__U16String__init,
    rosidl_runtime_c__U16String__fini,
    rosidl_runtime_c__U16String__assignn,
    rosidl_runtime_c__U16String__Sequence__init,
    rosidl_runtime_c__U16String__Sequence__fini,
    rosidl_runtime_c__U16String__Sequence__copy
);

impl From<&str> for String {
    fn from(s: &str) -> Self {
        let mut msg = Self {
            data: std::ptr::null_mut(),
            size: 0,
            capacity: 0,
        };
        // SAFETY: It's okay to pass a non-zero-terminated string here since assignn uses the
        // specified length and will append the 0 byte to the dest string itself.
        if !unsafe {
            rosidl_runtime_c__String__assignn(&mut msg as *mut _, s.as_ptr() as *const _, s.len())
        } {
            panic!("rosidl_runtime_c__String__assignn failed");
        }
        msg
    }
}

impl String {
    /// Creates a CStr from this String.
    ///
    /// This scales with the length of the string but does not create copy of the string.
    /// See also [`CStr::from_ptr()`].
    pub fn to_cstr(&self) -> &CStr {
        // SAFETY: self.data is a valid pointer and won't change.
        // Also, the lifetime of the CStr is the same as self, which is correct.
        unsafe { CStr::from_ptr(self.data as *const _) }
    }
}

impl From<&str> for WString {
    fn from(s: &str) -> Self {
        let mut msg = Self {
            data: std::ptr::null_mut(),
            size: 0,
            capacity: 0,
        };
        let buf: Vec<u16> = s.encode_utf16().collect();
        // SAFETY: It's okay to pass a non-zero-terminated string here since assignn uses the
        // specified length and will append the 0 to the dest string itself.
        if !unsafe {
            rosidl_runtime_c__U16String__assignn(
                &mut msg as *mut _,
                buf.as_ptr() as *const _,
                buf.len(),
            )
        } {
            panic!("rosidl_runtime_c__U16String__assignn failed");
        }
        msg
    }
}

// ========================= impl for BoundedString =========================

impl<const N: usize> Debug for BoundedString<N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        Debug::fmt(&self.inner, f)
    }
}

impl<const N: usize> Deref for BoundedString<N> {
    type Target = [std::os::raw::c_char];
    fn deref(&self) -> &Self::Target {
        self.inner.deref()
    }
}

impl<const N: usize> DerefMut for BoundedString<N> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.inner.deref_mut()
    }
}

impl<const N: usize> Display for BoundedString<N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        Display::fmt(&self.inner, f)
    }
}

impl<const N: usize> SequenceAlloc for BoundedString<N> {
    fn sequence_init(seq: &mut Sequence<Self>, size: usize) -> bool {
        // SAFETY: There are no special preconditions to the rosidl_runtime_c__String__Sequence__init function.
        unsafe {
            rosidl_runtime_c__String__Sequence__init(seq as *mut Sequence<Self> as *mut _, size)
        }
    }
    fn sequence_fini(seq: &mut Sequence<Self>) {
        // SAFETY: There are no special preconditions to the rosidl_runtime_c__String__Sequence__fini function.
        unsafe { rosidl_runtime_c__String__Sequence__fini(seq as *mut Sequence<Self> as *mut _) }
    }
    fn sequence_copy(in_seq: &Sequence<Self>, out_seq: &mut Sequence<Self>) -> bool {
        // SAFETY: Transmute of a transparent type to the inner type is fine
        unsafe {
            <String as SequenceAlloc>::sequence_copy(
                std::mem::transmute::<&Sequence<Self>, &Sequence<String>>(in_seq),
                std::mem::transmute::<&mut Sequence<Self>, &mut Sequence<String>>(out_seq),
            )
        }
    }
}

impl<const N: usize> TryFrom<&str> for BoundedString<N> {
    type Error = StringExceedsBoundsError;
    fn try_from(s: &str) -> Result<Self, Self::Error> {
        let length = s.chars().count();
        if length <= N {
            Ok(Self {
                inner: String::from(s),
            })
        } else {
            Err(StringExceedsBoundsError {
                len: length,
                upper_bound: N,
            })
        }
    }
}

// ========================= impl for BoundedWString =========================

impl<const N: usize> Debug for BoundedWString<N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        Debug::fmt(&self.inner, f)
    }
}

impl<const N: usize> Deref for BoundedWString<N> {
    type Target = [u16];
    fn deref(&self) -> &Self::Target {
        self.inner.deref()
    }
}

impl<const N: usize> DerefMut for BoundedWString<N> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.inner.deref_mut()
    }
}

impl<const N: usize> Display for BoundedWString<N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        Display::fmt(&self.inner, f)
    }
}

impl<const N: usize> SequenceAlloc for BoundedWString<N> {
    fn sequence_init(seq: &mut Sequence<Self>, size: usize) -> bool {
        // SAFETY: There are no special preconditions to the rosidl_runtime_c__U16String__Sequence__init function.
        unsafe {
            rosidl_runtime_c__U16String__Sequence__init(seq as *mut Sequence<Self> as *mut _, size)
        }
    }
    fn sequence_fini(seq: &mut Sequence<Self>) {
        // SAFETY: There are no special preconditions to the rosidl_runtime_c__U16String__Sequence__fini function.
        unsafe { rosidl_runtime_c__U16String__Sequence__fini(seq as *mut Sequence<Self> as *mut _) }
    }
    fn sequence_copy(in_seq: &Sequence<Self>, out_seq: &mut Sequence<Self>) -> bool {
        // SAFETY: Transmute of a transparent type to the inner type is fine
        unsafe {
            <WString as SequenceAlloc>::sequence_copy(
                std::mem::transmute::<&Sequence<Self>, &Sequence<WString>>(in_seq),
                std::mem::transmute::<&mut Sequence<Self>, &mut Sequence<WString>>(out_seq),
            )
        }
    }
}

impl<const N: usize> TryFrom<&str> for BoundedWString<N> {
    type Error = StringExceedsBoundsError;
    fn try_from(s: &str) -> Result<Self, Self::Error> {
        let length = s.chars().count();
        if length <= N {
            Ok(Self {
                inner: WString::from(s),
            })
        } else {
            Err(StringExceedsBoundsError {
                len: length,
                upper_bound: N,
            })
        }
    }
}

// ========================= impl for StringExceedsBoundsError =========================

impl Display for StringExceedsBoundsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        write!(
            f,
            "BoundedString with upper bound {} initialized with len {}",
            self.upper_bound, self.len
        )
    }
}

impl std::error::Error for StringExceedsBoundsError {}

#[cfg(test)]
mod tests {
    use quickcheck::{Arbitrary, Gen};

    use super::*;

    impl Arbitrary for String {
        fn arbitrary(g: &mut Gen) -> Self {
            std::string::String::arbitrary(g).as_str().into()
        }
    }

    impl Arbitrary for WString {
        fn arbitrary(g: &mut Gen) -> Self {
            std::string::String::arbitrary(g).as_str().into()
        }
    }

    impl Arbitrary for BoundedString<256> {
        fn arbitrary(g: &mut Gen) -> Self {
            let len = u8::arbitrary(g);
            let s: std::string::String = (0..len).map(|_| char::arbitrary(g)).collect();
            s.as_str().try_into().unwrap()
        }
    }

    impl Arbitrary for BoundedWString<256> {
        fn arbitrary(g: &mut Gen) -> Self {
            let len = u8::arbitrary(g);
            let s: std::string::String = (0..len).map(|_| char::arbitrary(g)).collect();
            s.as_str().try_into().unwrap()
        }
    }

    #[test]
    fn string_from_char_iterator() {
        // Base char case
        let expected = String::from("abc");
        let actual = "abc".chars().collect::<String>();

        assert_eq!(expected, actual);

        // Empty case
        let expected = String::from("");
        let actual = "".chars().collect::<String>();

        assert_eq!(expected, actual);

        // Non-ascii char case
        let expected = String::from("Grüß Gott! 𝕊");
        let actual = "Grüß Gott! 𝕊".chars().collect::<String>();

        assert_eq!(expected, actual);
    }

    #[test]
    fn extend_string_with_char_iterator() {
        let expected = WString::from("abcdef");
        let mut actual = WString::from("abc");
        actual.extend("def".chars());

        assert_eq!(expected, actual);
    }

    #[test]
    fn wstring_from_char_iterator() {
        // Base char case
        let expected = WString::from("abc");
        let actual = "abc".chars().collect::<WString>();

        assert_eq!(expected, actual);

        // Empty case
        let expected = WString::from("");
        let actual = "".chars().collect::<WString>();

        assert_eq!(expected, actual);

        // Non-ascii char case
        let expected = WString::from("Grüß Gott! 𝕊");
        let actual = "Grüß Gott! 𝕊".chars().collect::<WString>();

        assert_eq!(expected, actual);
    }

    #[test]
    fn extend_wstring_with_char_iterator() {
        let expected = WString::from("abcdef");
        let mut actual = WString::from("abc");
        actual.extend("def".chars());

        assert_eq!(expected, actual);
    }
}