Skip to content

Commit

Permalink
Add in missing nullptr check when calling std::slice::from_raw_parts (
Browse files Browse the repository at this point in the history
#416)

* Add in missing nullptr check when calling `std::slice::from_raw_parts`

* Added missing testcase
  • Loading branch information
maspe36 authored Sep 29, 2024
1 parent e485b1c commit 5903d73
Showing 1 changed file with 20 additions and 6 deletions.
26 changes: 20 additions & 6 deletions rosidl_runtime_rs/src/sequence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) }
}
}
}

Expand Down Expand Up @@ -666,6 +674,12 @@ mod tests {
}
}

#[test]
fn test_empty_sequence() {
assert!(Sequence::<i32>::default().is_empty());
assert!(BoundedSequence::<i32, 5>::default().is_empty());
}

quickcheck! {
fn test_extend(xs: Vec<i32>, ys: Vec<i32>) -> bool {
let mut xs_seq = Sequence::new(xs.len());
Expand Down

0 comments on commit 5903d73

Please sign in to comment.