ACP: Additional NonZero conversions #145
Labels
ACP-accepted
API Change Proposal is accepted (seconded with no objections)
api-change-proposal
A proposal to add or alter unstable APIs in the standard libraries
T-libs-api
Proposal
Problem statement
It was discussed in #135 that using
NonZeroU8
instead of simplyu8
would be more ergonomic forCStr
, but right now the ergonomics ofNonZero
slices aren't great.Motivation, use-cases
CStr
and slices could be kept safe with less checks if we leveraged[NonZeroU8]
as a type.Solution sketches
I think that we definitely want the following impls, where
X
is some primitive integer type:From<&NonZeroX> for &X
From<&[NonZeroX]> for &[X]
From<[NonZeroX; N]> for [X; N]
TryFrom<&X> for &NonZeroX
TryFrom<&[X]> for &[NonZeroX]
TryFrom<[X; N]> for [NonZeroX; N]
Note that mutable references are not supported explicitly since they could be unsound: converting from
&mut NonZeroX
to&mut X
could allow writing a zero and later observing it as aNonZeroX
. I don't believe that there's the same problem converting from&mut X
to&mut NonZeroX
(since the value could not be zero for the duration of the reborrow), but I'm not including it for now in case that's still unsound for some reason.Depending on how this is implemented, we could add methods directly on
NonZeroX
like:fn new_ref(val: &X) -> Option<&NonZeroX>
fn new_slice(val: &[X]) -> Option<&[NonZeroX]>
fn new_array<const N: usize>(val: [X; N]) -> Option<[NonZeroX; N]>
This would allow the addition of newer unsafe methods:
unsafe fn new_ref_unchecked(val: &X) -> &NonZeroX
unsafe fn new_slice_unchecked(val: &[X]) -> &[NonZeroX]
unsafe fn new_array_unchecked<const N: usize>(val: [X; N]) -> [NonZeroX; N]
Note that all of the unsafe methods would be equivalent to transmutes, and thus not gain any new functionality (whereas the safe methods would be impossible with safe code), although they would be more explicit than simple transmutes. I'm a fan of adding additional named methods over simple
From
andTryFrom
impls, since they can make clearer code, but discussing this is what the ACP is for.Links and related work
None known currently.
What happens now?
This issue is part of the libs-api team API change proposal process. Once this issue is filed the libs-api team will review open proposals in its weekly meeting. You should receive feedback within a week or two.
The text was updated successfully, but these errors were encountered: