diff --git a/rosidl_runtime_rs/src/sequence.rs b/rosidl_runtime_rs/src/sequence.rs index 22fbfbae5..3d7cd5832 100644 --- a/rosidl_runtime_rs/src/sequence.rs +++ b/rosidl_runtime_rs/src/sequence.rs @@ -261,18 +261,26 @@ where /// /// Equivalent to `&seq[..]`. pub fn as_slice(&self) -> &[T] { - // 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) } + if self.data.is_null() { + &[] + } else { + // SAFETY: self.data is not null and points to self.size consecutive, + // initialized elements and isn't modified externally. + unsafe { std::slice::from_raw_parts(self.data, self.size) } + } } /// Extracts a mutable slice containing the entire sequence. /// /// Equivalent to `&mut seq[..]`. pub fn as_mut_slice(&mut self) -> &mut [T] { - // 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) } + if self.data.is_null() { + &mut [] + } else { + // SAFETY: self.data is not null and points to self.size consecutive, + // initialized elements and isn't modified externally. + unsafe { std::slice::from_raw_parts_mut(self.data, self.size) } + } } } @@ -666,6 +674,12 @@ mod tests { } } + #[test] + fn test_empty_sequence() { + assert!(Sequence::::default().is_empty()); + assert!(BoundedSequence::::default().is_empty()); + } + quickcheck! { fn test_extend(xs: Vec, ys: Vec) -> bool { let mut xs_seq = Sequence::new(xs.len());