-
-
Notifications
You must be signed in to change notification settings - Fork 14.8k
Add truncate_into() #79477
Copy link
Copy link
Open
Labels
C-feature-requestCategory: A feature request, i.e: not implemented / a PR.Category: A feature request, i.e: not implemented / a PR.T-langRelevant to the language teamRelevant to the language teamT-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.Relevant to the library API team, which will review and decide on the PR/issue.
Metadata
Metadata
Assignees
Labels
C-feature-requestCategory: A feature request, i.e: not implemented / a PR.Category: A feature request, i.e: not implemented / a PR.T-langRelevant to the language teamRelevant to the language teamT-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.Relevant to the library API team, which will review and decide on the PR/issue.
Type
Fields
Give feedbackNo fields configured for issues without a type.
This is a proposal to add a
truncate_into()method on the various smallprimitive types (
u*,i*, andf*primarily).Currently, an
ascast can be used to 'upcast' from e.g.u8tou16, but itcan also be used to 'downcast' from e.g.
u16tou8. The downcast variantwill truncate any bits that can't fit into the smaller variant, which may be
unexpected behavior. Changing
as's behavior so it does not support downcastingwould be a big task, and perhaps not worth it – that is out of the scope of this
proposal. Instead, I propose to add a new method,
truncate_into()thatperforms the downcasting behavior such that it is clear in the code what is
happening.
It would likely be implemented as two traits,
TruncateFromandTruncateInto,akin to
TryFromandTryInto.TruncateIntowould be implemented in terms ofTruncateFrom, andTruncateFromcould just useasinternally. In thefuture, if we change the behavior of
as, we would probably have to convertinto an array first and then ignore some of the bytes.
This proposal stemmed from discussion on Zulip about the confusion arising
from
as's truncating behavior.