Skip to content

Commit edfb9fe

Browse files
maspe36esteve
authored andcommitted
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
1 parent 2b215e8 commit edfb9fe

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

rosidl_runtime_rs/src/sequence.rs

+20-6
Original file line numberDiff line numberDiff line change
@@ -261,18 +261,26 @@ where
261261
///
262262
/// Equivalent to `&seq[..]`.
263263
pub fn as_slice(&self) -> &[T] {
264-
// SAFETY: self.data points to self.size consecutive, initialized elements and
265-
// isn't modified externally.
266-
unsafe { std::slice::from_raw_parts(self.data, self.size) }
264+
if self.data.is_null() {
265+
&[]
266+
} else {
267+
// SAFETY: self.data is not null and points to self.size consecutive,
268+
// initialized elements and isn't modified externally.
269+
unsafe { std::slice::from_raw_parts(self.data, self.size) }
270+
}
267271
}
268272

269273
/// Extracts a mutable slice containing the entire sequence.
270274
///
271275
/// Equivalent to `&mut seq[..]`.
272276
pub fn as_mut_slice(&mut self) -> &mut [T] {
273-
// SAFETY: self.data points to self.size consecutive, initialized elements and
274-
// isn't modified externally.
275-
unsafe { std::slice::from_raw_parts_mut(self.data, self.size) }
277+
if self.data.is_null() {
278+
&mut []
279+
} else {
280+
// SAFETY: self.data is not null and points to self.size consecutive,
281+
// initialized elements and isn't modified externally.
282+
unsafe { std::slice::from_raw_parts_mut(self.data, self.size) }
283+
}
276284
}
277285
}
278286

@@ -666,6 +674,12 @@ mod tests {
666674
}
667675
}
668676

677+
#[test]
678+
fn test_empty_sequence() {
679+
assert!(Sequence::<i32>::default().is_empty());
680+
assert!(BoundedSequence::<i32, 5>::default().is_empty());
681+
}
682+
669683
quickcheck! {
670684
fn test_extend(xs: Vec<i32>, ys: Vec<i32>) -> bool {
671685
let mut xs_seq = Sequence::new(xs.len());

0 commit comments

Comments
 (0)