Skip to content

List from_be_bytes as Alternative in Transmute Docs #71187

@domenukk

Description

@domenukk

Many code bases I see use transmute to convert raw bytes (&[u8]) to u32, f64, etc. - while they could, and probably should, use from_le_bytes or from_be_bytes.
The transmute docs include a lengthy section about Alternatives, but this obvious one seems to be missing.

Activity

added
E-easyCall for participation: Easy difficulty. Experience needed to fix: Not much. Good first issue.
T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.
C-enhancementCategory: An issue proposing an enhancement or a PR with one.
on Apr 16, 2020
huangjiahua

huangjiahua commented on Apr 16, 2020

@huangjiahua

@domenukk I've used from_le_bytes and from_be_bytes several times in my little project. I want to have a try. Will this code snippet work?

    let raw_data = &[0x78, 0x56, 0x34, 0x12];
    
    let num = unsafe {
        std::mem::transmute::<[u8; 4], u32>(*raw_data)
    };
    // This result depends on your machine
    assert_eq!(num, 0x12345678);


    // use from_be_bytes and from_le_bytes instead to produce predictable result
    let num = u32::from_le_bytes(*raw_data);
    assert_eq!(num, 0x12345678);
    
    let num = u32::from_be_bytes(*raw_data);
    assert_eq!(num, 0x78563412);
Duddino

Duddino commented on Apr 17, 2020

@Duddino

@huangjiahua maybe you can also add u32::from_ne_bytes() as an alternative to transmute but without unsafe
also you can show that u32::from_ne_bytes() is equal to mem::trasmute with an assertion

rustbot

rustbot commented on Apr 17, 2020

@rustbot
Collaborator

Error: Parsing assign command in comment failed: ...uangjiahua|error: user should start with @ at >|...

Please let @rust-lang/release know if you're having trouble with this bot.

rustbot

rustbot commented on Apr 17, 2020

@rustbot
Collaborator

Error: Parsing assign command in comment failed: ...uangjiahua|error: user should start with @ at >|...

Please let @rust-lang/release know if you're having trouble with this bot.

added 2 commits that reference this issue on Apr 19, 2020
15138ca
7cdcc87
Alexendoo

Alexendoo commented on Apr 22, 2020

@Alexendoo
Member

Closed by #71315

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

C-enhancementCategory: An issue proposing an enhancement or a PR with one.E-easyCall for participation: Easy difficulty. Experience needed to fix: Not much. Good first 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

      Participants

      @domenukk@jonas-schievink@Alexendoo@huangjiahua@Duddino

      Issue actions

        List from_be_bytes as Alternative in Transmute Docs · Issue #71187 · rust-lang/rust