Skip to content

Tracking issue for floats ↔ bytes conversions #60446

Closed
@SimonSapin

Description

@SimonSapin

#58756 #62366 adds:

impl f32 {
    pub const fn to_be_bytes(self) -> [u8; 4] { self.to_bits().to_be_bytes() }
    pub const fn to_le_bytes(self) -> [u8; 4] { self.to_bits().to_le_bytes() }
    pub const fn to_ne_bytes(self) -> [u8; 4] { self.to_bits().to_ne_bytes() }
    pub const fn from_be_bytes(bytes: [u8; 4]) -> Self { Self::from_bits(u32::from_be_bytes(bytes)) }
    pub const fn from_le_bytes(bytes: [u8; 4]) -> Self { Self::from_bits(u32::from_le_bytes(bytes)) }
    pub const fn from_ne_bytes(bytes: [u8; 4]) -> Self { Self::from_bits(u32::from_ne_bytes(bytes)) }
}

impl f64 {
    pub const fn to_be_bytes(self) -> [u8; 8] { self.to_bits().to_be_bytes() }
    pub const fn to_le_bytes(self) -> [u8; 8] { self.to_bits().to_le_bytes() }
    pub const fn to_ne_bytes(self) -> [u8; 8] { self.to_bits().to_ne_bytes() }
    pub const fn from_be_bytes(bytes: [u8; 8]) -> Self { Self::from_bits(u64::from_be_bytes(bytes)) }
    pub const fn from_le_bytes(bytes: [u8; 8]) -> Self { Self::from_bits(u64::from_le_bytes(bytes)) }
    pub const fn from_ne_bytes(bytes: [u8; 8]) -> Self { Self::from_bits(u64::from_ne_bytes(bytes)) }
}

PR discussion summary: unlike corresponding integer methods, these can be implemented without unsafe code. So the need for having them in the standard library feels less pressing. At the same time, it might not be obvious to everyone that to_bits and from_bits can be combined with integer methods in this way. So having these float methods helps discoverability.

Metadata

Metadata

Assignees

No one assigned

    Labels

    B-unstableBlocker: Implemented in the nightly compiler and unstable.C-tracking-issueCategory: An issue tracking the progress of sth. like the implementation of an RFCT-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.disposition-mergeThis issue / PR is in PFCP or FCP with a disposition to merge it.finished-final-comment-periodThe final comment period is finished for this PR / Issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions