Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit f9231b4

Browse files
authoredMar 26, 2025··
replace unsound use of transmute with u32::from_be_bytes (#1470)
1 parent 6534b96 commit f9231b4

File tree

1 file changed

+8
-9
lines changed

1 file changed

+8
-9
lines changed
 

‎src/sdl2/gfx/primitives.rs

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ use pixels;
77
use render::Canvas;
88
use std::convert::TryFrom;
99
use std::ffi::CString;
10-
use std::mem;
1110
use std::ptr;
1211
use surface::Surface;
1312
use sys::gfx::primitives;
@@ -18,7 +17,8 @@ pub trait ToColor {
1817

1918
#[inline]
2019
fn as_u32(&self) -> u32 {
21-
unsafe { mem::transmute(self.as_rgba()) }
20+
let (r, g, b, a) = self.as_rgba();
21+
u32::from_be_bytes([r, g, b, a])
2222
}
2323
}
2424

@@ -34,17 +34,13 @@ impl ToColor for (u8, u8, u8, u8) {
3434
fn as_rgba(&self) -> (u8, u8, u8, u8) {
3535
*self
3636
}
37-
38-
#[inline]
39-
fn as_u32(&self) -> u32 {
40-
unsafe { mem::transmute(*self) }
41-
}
4237
}
4338

4439
impl ToColor for u32 {
4540
#[inline]
4641
fn as_rgba(&self) -> (u8, u8, u8, u8) {
47-
unsafe { mem::transmute(*self) }
42+
let [r, g, b, a] = self.to_be_bytes();
43+
(r, g, b, a)
4844
}
4945

5046
#[inline]
@@ -57,7 +53,10 @@ impl ToColor for u32 {
5753
impl ToColor for isize {
5854
#[inline]
5955
fn as_rgba(&self) -> (u8, u8, u8, u8) {
60-
unsafe { mem::transmute(u32::try_from(*self).expect("Can't convert to Color Type")) }
56+
let [r, g, b, a] = u32::try_from(*self)
57+
.expect("Can't convert to Color Type")
58+
.to_be_bytes();
59+
(r, g, b, a)
6160
}
6261

6362
#[inline]

0 commit comments

Comments
 (0)
Please sign in to comment.