Do not pass nullptr to slice::from_raw_parts

Pass dangling, but well-aligned pointer instead as per
https://doc.rust-lang.org/std/slice/fn.from_raw_parts.html#safety.

PiperOrigin-RevId: 539924021
pull/13039/head
Marcel Hlopko 1 year ago committed by Copybara-Service
parent 0246e09df8
commit cc83427ee3
  1. 8
      rust/shared.rs
  2. 3
      rust/test/shared/accessors_test.rs

@ -46,6 +46,7 @@ pub use __runtime::SerializedData;
use std::fmt;
use std::slice;
use std::ptr::NonNull;
/// An error that happened during deserialization.
#[derive(Debug, Clone)]
@ -73,6 +74,11 @@ pub struct PtrAndLen {
impl PtrAndLen {
pub unsafe fn as_ref<'a>(self) -> &'a [u8] {
slice::from_raw_parts(self.ptr, self.len)
assert!(self.len == 0 || !self.ptr.is_null());
if self.len == 0 {
slice::from_raw_parts(NonNull::dangling().as_ptr(), 0)
} else {
slice::from_raw_parts(self.ptr, self.len)
}
}
}

@ -65,4 +65,7 @@ fn test_optional_bytes_accessors() {
msg.optional_bytes_set(None);
assert_eq!(msg.optional_bytes(), None);
msg.optional_bytes_set(Some(b""));
assert_eq!(msg.optional_bytes().unwrap(), b"");
}

Loading…
Cancel
Save