Add safe layout reprs and safety comments about layout

This commit is contained in:
Ross Smyth 2022-08-13 01:56:55 -04:00
parent f8a2f458b0
commit 80f14f61df
No known key found for this signature in database
GPG Key ID: F1090CED11840CA3
5 changed files with 12 additions and 2 deletions

View File

@ -152,6 +152,7 @@ impl Symbol {
}
pub const fn to_ne_bytes(self) -> [u8; 8] {
// repr(packed(4)) is repr(c), and with the fields as defined will not having padding.
unsafe { std::mem::transmute(self) }
}

View File

@ -66,6 +66,7 @@ struct ErrorTypeState {
recursive_tag_unions_seen: Vec<Variable>,
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
struct SubsHeader {
utable: u64,
@ -99,10 +100,12 @@ impl SubsHeader {
}
fn to_array(self) -> [u8; std::mem::size_of::<Self>()] {
// Safety: With repr(c) all fields are in order and properly aligned without padding.
unsafe { std::mem::transmute(self) }
}
fn from_array(array: [u8; std::mem::size_of::<Self>()]) -> Self {
// Safety: With repr(c) all fields are in order and properly aligned without padding.
unsafe { std::mem::transmute(array) }
}
}

View File

@ -6,11 +6,14 @@
use cgmath::Vector2;
#[derive(Copy, Clone)]
#[repr(C)]
pub struct Vertex {
pub position: Vector2<f32>,
pub color: [f32; 4],
}
// Safety: As defined, there is no padding
// the type is repr(C), and Vector2 is repr(C)
unsafe impl bytemuck::Pod for Vertex {}
unsafe impl bytemuck::Zeroable for Vertex {}

View File

@ -2,6 +2,7 @@
/// A polygon with 4 corners
#[derive(Copy, Clone)]
#[repr(C)]
pub struct Quad {
pub pos: [f32; 2],
pub width: f32,
@ -28,4 +29,4 @@ impl Quad {
6 => Float32,
),
};
}
}

View File

@ -1,6 +1,7 @@
/// A polygon with 4 corners
#[repr(C)]
#[derive(Copy, Clone)]
pub struct Quad {
pub pos: [f32; 2],
@ -11,6 +12,7 @@ pub struct Quad {
pub border_width: f32,
}
// Safety: repr(C), and as defined will not having padding.
unsafe impl bytemuck::Pod for Quad {}
unsafe impl bytemuck::Zeroable for Quad {}
@ -28,4 +30,4 @@ impl Quad {
6 => Float32,
),
};
}
}