Skip to content

Commit

Permalink
glib: Don't misuse slice::get_unchecked()
Browse files Browse the repository at this point in the history
It will panic in debug builds when trying to access indices outside the
slice. Instead, use pointer operations here to check that there is a
`NULL` at the end of the array.
  • Loading branch information
sdroege committed Mar 19, 2024
1 parent c5dc463 commit 11bd6c4
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions glib/src/collections/strv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1479,37 +1479,37 @@ mod test {
let items = ["str1", "str2", "str3", "str4"];

items[..].run_with_strv(|s| unsafe {
assert!(s.get_unchecked(4).is_null());
assert!((*s.as_ptr().add(4)).is_null());
assert_eq!(s.len(), items.len());
let s = StrV::from_glib_borrow(s.as_ptr() as *const *const c_char);
assert_eq!(s, items);
});

Vec::from(&items[..]).run_with_strv(|s| unsafe {
assert!(s.get_unchecked(4).is_null());
assert!((*s.as_ptr().add(4)).is_null());
assert_eq!(s.len(), items.len());
let s = StrV::from_glib_borrow(s.as_ptr() as *const *const c_char);
assert_eq!(s, items);
});

StrV::from(&items[..]).run_with_strv(|s| unsafe {
assert!(s.get_unchecked(4).is_null());
assert!((*s.as_ptr().add(4)).is_null());
assert_eq!(s.len(), items.len());
let s = StrV::from_glib_borrow(s.as_ptr() as *const *const c_char);
assert_eq!(s, items);
});

let v = items.iter().copied().map(String::from).collect::<Vec<_>>();
items.run_with_strv(|s| unsafe {
assert!(s.get_unchecked(4).is_null());
assert!((*s.as_ptr().add(4)).is_null());
assert_eq!(s.len(), v.len());
let s = StrV::from_glib_borrow(s.as_ptr() as *const *const c_char);
assert_eq!(s, items);
});

let v = items.iter().copied().map(GString::from).collect::<Vec<_>>();
items.run_with_strv(|s| unsafe {
assert!(s.get_unchecked(4).is_null());
assert!((*s.as_ptr().add(4)).is_null());
assert_eq!(s.len(), v.len());
let s = StrV::from_glib_borrow(s.as_ptr() as *const *const c_char);
assert_eq!(s, items);
Expand Down

0 comments on commit 11bd6c4

Please sign in to comment.