How to cast *mut u8 as [u8]?

I have a function in a trait that returns std::ptrNonNull<[u8]>. I'm having a forgetful day:

  1. What data type is [u8] - by my understanding, it's not a slice (no reference &) nor is it an array (no size).
  2. How do I cast *mut u8 to [u8] so that ptr as an argument to NonNull::new(ptr) is the correct type?

I have the following, but ptr is the wrong type:

unsafe {
    let ptr = self.data.as_mut_ptr().add(self.used);
    self.used += layout.size();

    std::ptr::NonNull::new(ptr).ok_or(std::alloc::AllocError)
}

Giving:

mismatched types
expected enum `Result<NonNull<[u8]>, _>`
   found enum `Result<NonNull<u8>, _>`

It is a slice. It's just not a reference to a slice.

Usually, casting pointers works with as:

ptr as *mut OtherType

or better yet

ptr.cast::<OtherType>()

which can't accidentally cast away (im)mutability.

However, for casting to a fat pointer, you have to supply the length information somehow, for which you can use core::slice::from_raw_parts().

2 Likes

Exciting - that's just improved my knowledge.

Doh - I was close with ptr as [u8].

Many thanks :smiley:

How do I convert that thin pointer to a fat pointer?

Always find the answer just after asking!

let p = std::ptr::slice_from_raw_parts_mut(ptr, layout.size());

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.