Skip to content

Commit b2bcc61

Browse files
Mitigate UB
1 parent 6da6d58 commit b2bcc61

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/fixed.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,15 @@ pub trait FixedInt: Sized + Copy {
3232
/// on big-endian machines). If you receive a big-endian integer, and would like it to be
3333
/// treated correctly, use this helper method to convert between endiannesses.
3434
fn switch_endianness(self) -> Self {
35+
// an implementation of `FixedInt` may not provide the correct space,
36+
// resulting in UB.
37+
assert_eq!(size_of::<Self>(), Self::REQUIRED_SPACE);
3538
// Switch to intrinsic bswap when out of nightly.
3639
unsafe {
37-
let sl = std::slice::from_raw_parts_mut(transmute::<&Self, *mut u8>(&self), Self::REQUIRED_SPACE);
40+
let sl = std::slice::from_raw_parts_mut(
41+
transmute::<&Self, *mut u8>(&self),
42+
Self::REQUIRED_SPACE,
43+
);
3844
sl.reverse();
3945
*transmute::<*const u8, &Self>(sl.as_ptr())
4046
}

src/fixed_tests.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,33 @@ mod tests {
7575
}
7676
*/
7777

78+
#[should_panic]
79+
#[test]
80+
fn test_switch() {
81+
impl FixedInt for i128 {
82+
const REQUIRED_SPACE: usize = 256;
83+
84+
fn required_space() -> usize {
85+
todo!()
86+
}
87+
88+
fn encode_fixed(self, dst: &mut [u8]) {
89+
todo!()
90+
}
91+
92+
fn decode_fixed(src: &[u8]) -> Self {
93+
todo!()
94+
}
95+
96+
fn encode_fixed_light<'a>(&'a self) -> &'a [u8] {
97+
todo!()
98+
}
99+
}
100+
101+
let int = -32767i128;
102+
let int = int.switch_endianness();
103+
}
104+
78105
#[test]
79106
fn test_i32_enc_light() {
80107
let int = -32767 as i32;

0 commit comments

Comments
 (0)