from_ptr_range in std::slice - Rust (original) (raw)

Function from_ptr_range

Source

pub const unsafe fn from_ptr_range<'a, T>(range: Range<*const T>) -> &'a [T]

🔬This is a nightly-only experimental API. (slice_from_ptr_range #89792)

Expand description

Forms a slice from a pointer range.

This function is useful for interacting with foreign interfaces which use two pointers to refer to a range of elements in memory, as is common in C++.

§Safety

Behavior is undefined if any of the following conditions are violated:

Note that a range created from slice::as_ptr_range fulfills these requirements.

§Panics

This function panics if T is a Zero-Sized Type (“ZST”).

§Caveat

The lifetime for the returned slice is inferred from its usage. To prevent accidental misuse, it’s suggested to tie the lifetime to whichever source lifetime is safe in the context, such as by providing a helper function taking the lifetime of a host value for the slice, or by explicit annotation.

§Examples

#![feature(slice_from_ptr_range)]

use core::slice;

let x = [1, 2, 3];
let range = x.as_ptr_range();

unsafe {
    assert_eq!(slice::from_ptr_range(range), &x);
}