Skip to content

ACP: Add NonZero::<T>::from_str_radix #548

Open
@sorairolake

Description

@sorairolake

Proposal

Problem statement

NonZero::<T>::from_str is already implemented and it only supports decimal, just like T::from_str. In other words, there is no direct way to convert a string which represents non-decimal such as octal and hexadecimal to NonZero<T>.

To do this, we need to combine T::from_str and NonZero::<T>::new as follows:

let n = NonZeroU8::new(u8::from_str_radix("ff", 16)?);

Also, unlike NonZero::<T>::from_str, this cannot return IntErrorKind::Zero.

Motivating examples or use cases

I think it would be useful to be able to convert a string which represents non-decimal directly to NonZero<T> like T::from_str_radix. This method also allows you to check whether the error kind is IntErrorKind::Zero or not, because it can return this error kind.

let err = NonZeroU64::from_str_radix("0", 16).unwrap_err();
assert_eq!(err.kind(), &IntErrorKind::Zero);

Unlike NonZero::<T>::from_str, NonZero::<T>::from_str_radix can also be used in constant contexts, which may be an advantage (because rust-lang/rust#67792 not yet stable and NonZero::<T>::from_str_radix is not a trait method):

const N: NonZeroU32 = if let Ok(n) = NonZeroU32::from_str_radix("644", 8) {
    n
} else {
    panic!()
};
assert_eq!(N.get(), 0o644);

Solution sketch

// `src/num/nonzero.rs`
impl NonZero<$Int> {
    pub const fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
        let n = match <$Int>::from_str_radix(src, radix) {
            Ok(n) => n,
            Err(err) => return Err(err),
        };
        if let Some(n) = Self::new(n) {
            Ok(n)
        } else {
            Err(ParseIntError { kind: IntErrorKind::Zero })
        }
    }
}

Alternatives

We can do something similar by combining T::from_str and NonZero::<T>::new. We can also check whether a number is zero by checking whether NonZero::<T>::new returns None. However, existing APIs cannot return IntErrorKind::Zero.

Links and related work

https://internals.rust-lang.org/t/implement-nonzero-from-str-radix/22464

What happens now?

This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.

Possible responses

The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):

  • We think this problem seems worth solving, and the standard library might be the right place to solve it.
  • We think that this probably doesn't belong in the standard library.

Second, if there's a concrete solution:

  • We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
  • We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    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