Skip to content

Feature request: From<&[T]> for NonNull<T> #69316

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
tspiteri opened this issue Feb 20, 2020 · 4 comments
Closed

Feature request: From<&[T]> for NonNull<T> #69316

tspiteri opened this issue Feb 20, 2020 · 4 comments
Labels
C-feature-request Category: A feature request, i.e: not implemented / a PR. T-libs-api Relevant to the library API team, which will review and decide on the PR/issue.

Comments

@tspiteri
Copy link
Contributor

While NonNull<T> implements From<&T>, it does not implement From<&[T]>. Current options:

  1. Use NonNull::new(slice.as_ptr() as *mut T).unwrap(), and rely on the optimizer to remove the unwrap.
  2. Use unsafe { NonNull::new_unchecked(slice.as_ptr() as *mut T) }, which is correct but unfortunately has to use unsafe.
  3. It is tempting to use NonNull::from(&slice[0]), which looks more ergonomic than 1 and 2, but has incorrect pointer provenance.

Since both references and slices have as_ptr and as_mut_ptr methods, I think that NonNull should implement From for slices as well as for references.

@jonas-schievink
Copy link
Contributor

It implements <'a, T: ?Sized> From<&'a T>, so this should already work, right?

@tspiteri
Copy link
Contributor Author

But NonNull::from(slice) returns NonNull<[T]>, it does not return NonNull<T>. By comparison, slice::as_ptr returns *const T, not *const [T].

@jonas-schievink
Copy link
Contributor

Ah, I see

@jonas-schievink jonas-schievink added C-feature-request Category: A feature request, i.e: not implemented / a PR. T-libs-api Relevant to the library API team, which will review and decide on the PR/issue. labels Feb 20, 2020
@tspiteri
Copy link
Contributor Author

As pointed out in #69319 (review), this use case is already solved by NonNull::from(slice).cast::<T>().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-feature-request Category: A feature request, i.e: not implemented / a PR. T-libs-api Relevant to the library API team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants