-
Notifications
You must be signed in to change notification settings - Fork 20
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
Add uN::to_signed and iN::to_unsigned #183
Comments
This also has the benefit that methods bring with them of being able to be converted to a function pointer or being passed to generic functions like |
Makes sense to me, and I like it as a method on the source type so that The one 🚲🏚 that comes to mind is whether it should have something in the name to acknowledge the "not exactly the same value"-ness, since If it's described as "the same as an |
I'm not so sure. |
I think these got approved as |
Proposal
Problem statement
Currently, users wanting to change "signed-ness" of an integer while preserving it's bit representation (
u8
toi8
, or vice versa) would useas
conversion. This has problems, asas
doesn't restrict its input type, making it possible to introduce bugs during refactors or through code duplication.Motivation, use-cases
For example, user might have started writing code using
u8
type, and needs to usei8
(with wrapping behaviour) in a specific place:Later, user decides to change the type to e.g.
u16
, so foo becomesfn foo(x: u16)
, but now the code will truncate the value before passing it tobar
, potentially introducing subtle bugs. This could be dangerous for low-level and/or unsafe code, where this kind of conversions are not uncommon.If user used
bar(x.to_signed())
, they would get an type error instead, making them aware of situation, and forcing them to resolve it in some way.The proposed solution is also inspired by pointers methods like
cast
,cast_const
,cast_mut
, which have similar goals of making it safer to perform conversion without usingas
.Solution sketches
My solution is to introduce set of methods on primitive integer type,
to_signed
andto_unsigned
:Other solution could be to use an "inverse" of this,
from_signed
/from_unsigned
, e.g.:or to add both sets of methods:
{to,from}_{signed,unsigned}
, but the added value here seems negligible to author.Links and related work
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: