Skip to content

ACP: Additional NonZero conversions #145

Closed
@clarfonthey

Description

@clarfonthey

Proposal

Problem statement

It was discussed in #135 that using NonZeroU8 instead of simply u8 would be more ergonomic for CStr, but right now the ergonomics of NonZero slices aren't great.

Motivation, use-cases

  • Conversions between CStr and slices could be kept safe with less checks if we leveraged [NonZeroU8] as a type.
  • (probably more, will add more later)

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 a NonZeroX. 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 and TryFrom 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    ACP-acceptedAPI Change Proposal is accepted (seconded with no objections)T-libs-apiapi-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions