Use mem::transmute to deserialize raw fill data

This commit is contained in:
Belén Albeza 2025-05-06 12:38:30 +02:00
parent cba65972dd
commit ec73bd640c
3 changed files with 6 additions and 40 deletions

View file

@ -7,6 +7,7 @@ const RAW_GRADIENT_DATA_SIZE: usize =
#[derive(Debug, PartialEq, Clone, Copy)]
#[repr(C)]
#[repr(align(4))]
pub struct RawGradientData {
start_x: f32,
start_y: f32,
@ -15,31 +16,12 @@ pub struct RawGradientData {
opacity: f32,
width: f32,
stop_count: u8,
_pad: [u8; 3],
stops: [RawStopData; MAX_GRADIENT_STOPS],
}
impl From<[u8; RAW_GRADIENT_DATA_SIZE]> for RawGradientData {
fn from(bytes: [u8; RAW_GRADIENT_DATA_SIZE]) -> Self {
Self {
start_x: f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]),
start_y: f32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]),
end_x: f32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]),
end_y: f32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]),
opacity: f32::from_le_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]),
width: f32::from_le_bytes([bytes[20], bytes[21], bytes[22], bytes[23]]),
stop_count: bytes[24],
_pad: [0; 3],
// FIXME: 2025-04-22: use `array_chunks` once the next release is out
// and we update our devenv.
// See https://github.com/rust-lang/rust/issues/74985
stops: bytes[28..]
.chunks_exact(RAW_STOP_DATA_SIZE)
.map(|chunk| RawStopData::try_from(chunk).unwrap())
.collect::<Vec<_>>()
.try_into()
.unwrap(),
}
unsafe { std::mem::transmute(bytes) }
}
}

View file

@ -4,6 +4,7 @@ const RAW_IMAGE_DATA_SIZE: usize = 28;
#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(C)]
#[repr(align(4))]
pub struct RawImageFillData {
a: u32,
b: u32,
@ -25,23 +26,7 @@ impl From<RawImageFillData> for ImageFill {
impl From<[u8; RAW_IMAGE_DATA_SIZE]> for RawImageFillData {
fn from(value: [u8; RAW_IMAGE_DATA_SIZE]) -> Self {
let a = u32::from_le_bytes([value[0], value[1], value[2], value[3]]);
let b = u32::from_le_bytes([value[4], value[5], value[6], value[7]]);
let c = u32::from_le_bytes([value[8], value[9], value[10], value[11]]);
let d = u32::from_le_bytes([value[12], value[13], value[14], value[15]]);
let opacity = f32::from_le_bytes([value[16], value[17], value[18], value[19]]);
let width = i32::from_le_bytes([value[20], value[21], value[22], value[23]]);
let height = i32::from_le_bytes([value[24], value[25], value[26], value[27]]);
Self {
a,
b,
c,
d,
opacity,
width,
height,
}
unsafe { std::mem::transmute(value) }
}
}

View file

@ -3,6 +3,7 @@ use crate::shapes::{Color, SolidColor};
const RAW_SOLID_DATA_SIZE: usize = 4;
#[repr(C)]
#[repr(align(4))]
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct RawSolidData {
pub color: u32,
@ -10,9 +11,7 @@ pub struct RawSolidData {
impl From<[u8; 4]> for RawSolidData {
fn from(value: [u8; RAW_SOLID_DATA_SIZE]) -> Self {
Self {
color: u32::from_le_bytes(value),
}
unsafe { std::mem::transmute(value) }
}
}