Skip to content

Add truncate_into() #79477

Open
Open
@camelid

Description

@camelid

This is a proposal to add a truncate_into() method on the various small
primitive types (u*, i*, and f* primarily).

Currently, an as cast can be used to 'upcast' from e.g. u8 to u16, but it
can also be used to 'downcast' from e.g. u16 to u8. The downcast variant
will 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 downcasting
would 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() that
performs the downcasting behavior such that it is clear in the code what is
happening.

It would likely be implemented as two traits, TruncateFrom and TruncateInto,
akin to TryFrom and TryInto. TruncateInto would be implemented in terms of
TruncateFrom, and TruncateFrom could just use as internally. In the
future, if we change the behavior of as, we would probably have to convert
into 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-langRelevant to the language team, which will review and decide on the PR/issue.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions