Skip to content

Commit

Permalink
Don't allow trivial UB via FieldSlot in safe code
Browse files Browse the repository at this point in the history
cf. https://x.com/qdoit_/status/1848004580115726710, thanks qdoit_ and kupiakos
on twitter!
  • Loading branch information
fasterthanlime committed Oct 20, 2024
1 parent 22be5ed commit b307ad6
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 6 deletions.
6 changes: 2 additions & 4 deletions merde/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,7 @@ macro_rules! impl_deserialize {
Ok($struct_name {
$($field: {
if $field.is_none() {
let __field_type_name = std::any::type_name_of_val(&$field);
let __slot = $crate::FieldSlot::new(&mut $field, __field_type_name);
let __slot = $crate::FieldSlot::new(&mut $field);
__opinions.default_field_value(stringify!($field), __slot);
}
$crate::Deserialize::from_option($field, stringify!($field).into())?
Expand Down Expand Up @@ -163,8 +162,7 @@ macro_rules! impl_deserialize {
Ok($struct_name {
$($field: {
if $field.is_none() {
let __field_type_name = std::any::type_name_of_val(&$field);
let __slot = $crate::FieldSlot::new(&mut $field, __field_type_name);
let __slot = $crate::FieldSlot::new(&mut $field);
__opinions.default_field_value(stringify!($field), __slot);
}
$crate::Deserialize::from_option($field, stringify!($field).into())?
Expand Down
5 changes: 3 additions & 2 deletions merde_core/src/deserialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,12 +317,13 @@ pub struct FieldSlot<'s, 'borrow> {
impl<'s, 'borrow> FieldSlot<'s, 'borrow> {
/// Construct a new `FieldSlot`, ready to be filled
#[inline(always)]
pub fn new<T: 's>(option: &'borrow mut Option<T>, type_name_of_slot: &'static str) -> Self {
#[doc(hidden)]
pub fn new<T: 's>(option: &'borrow mut Option<T>) -> Self {
Self {
option: unsafe {
std::mem::transmute::<*mut Option<T>, *mut Option<()>>(option as *mut _)
},
type_name_of_option_field: type_name_of_slot,
type_name_of_option_field: std::any::type_name::<Option<T>>(),
_phantom: PhantomData,
}
}
Expand Down

0 comments on commit b307ad6

Please sign in to comment.