Skip to content
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

Traits for NonZero types? #397

Open
jgarvin opened this issue Aug 12, 2020 · 3 comments
Open

Traits for NonZero types? #397

jgarvin opened this issue Aug 12, 2020 · 3 comments

Comments

@jgarvin
Copy link

jgarvin commented Aug 12, 2020

Can't find NonZero anywhere in the docs.

Similar to the #391, would be nice to have ToNonZero and ToHasZero and a trait for new, new_unchecked, and get.

@webern
Copy link

webern commented Jan 7, 2021

I found my way here looking for the ability to create a Ratio<NonZeroU32>. Is that possible? Is there some minimal set of traits I could impl on NonZeroU32 that would 'unlock' all the existent u32 trait impls? I'm not sure if this is strictly related to the OP.

@cuviper
Copy link
Member

cuviper commented Jan 7, 2021

If we were to add non-zero traits, I see it only as a generic consolidation of the functionality available in the specific NonZeroU32 etc. I'm not sure it's really needed though. You can use TryFrom<T> as the generic NonZero::new, and Into<T> as the generic NonZero::get. Only new_unchecked remains, but we don't have any history of exposing unsafe functionality here.

@webern

I found my way here looking for the ability to create a Ratio<NonZeroU32>. Is there some minimal set of traits I could impl on NonZeroU32 that would 'unlock' all the existent u32 trait impls?

Rust coherence means that impls require either the type or the trait to be local. Since that type is defined in core, most impls have to be there, and anything further has to be in the crate which defines that extra trait, or the trait has to involve a generic parameter and the impl is local to a specific type in that position.

NonZeroU32 implements almost no operator traits, just BitOr AFAICS. Further implementations would have to be added in the standard library itself, for the most part, and anything that could result in a zero would be invalid. Maybe those could be treated as panicking cases, but I think the general sense is that the NonZero types are meant to be a storage optimization, not to be used directly in computation.

For Ratio in particular, almost all of its functionality requires Integer, which requires Num, which requires Zero -- which is a non-starter for NonZeroU32, of course. That's beside all of the other operators that would be needed for Ratio to function mathematically.

@webern
Copy link

webern commented Jan 7, 2021

Ok. Thank you for explaining how it works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants