Skip to content

Implementations of sdl2::gfx::primitives::ToColor has undefined behavior #1304

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

Closed
belak opened this issue Apr 30, 2023 · 0 comments · Fixed by #1470
Closed

Implementations of sdl2::gfx::primitives::ToColor has undefined behavior #1304

belak opened this issue Apr 30, 2023 · 0 comments · Fixed by #1470
Labels

Comments

@belak
Copy link

belak commented Apr 30, 2023

https://github.com/Rust-SDL2/rust-sdl2/blob/7fd7ee4/src/sdl2/gfx/primitives.rs#L21

Hello! I was trying to get some of the basic drawing functions working for an SDL 1.2 library and I was looking here for sample code. However, I was having issues with some colors not working. After investigating I found that ToColor uses UB because the layout of tuples in memory isn't guaranteed (so mem::transmute won't always work).

I think most uses of transmute can be replaced with either u32::to_be_bytes or u32::from_be_bytes to fix the issue. Ideally, there could be a single color type for the whole crate, but that might be too complex.

Here's a sample test which fails for me:

#[test]
fn test_color() {
    let r: u8 = 255;
    let g: u8 = 0;
    let b: u8 = 255;
    let a: u8 = 255;

    assert_eq!((r, g, b, a), 0xFF00FFFFu32.as_rgba());
}

It's not a great test, but it shows the issue I'm running into.

@belak belak changed the title Implementation of sdl2::gfx::primitives::ToColor has undefined behavior Implementations of sdl2::gfx::primitives::ToColor has undefined behavior Apr 30, 2023
@Cobrand Cobrand added the bug label May 2, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants