From 5903d732efdb7107edb1970ebcc1a9d4050f07a9 Mon Sep 17 00:00:00 2001 From: Sam Privett Date: Sun, 29 Sep 2024 08:12:49 -0700 Subject: [PATCH] Add in missing nullptr check when calling `std::slice::from_raw_parts` (#416) * Add in missing nullptr check when calling `std::slice::from_raw_parts` * Added missing testcase --- rosidl_runtime_rs/src/sequence.rs | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) 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());