Merge pull request #53 from RalfJung/unsafe

avoid putting user code inside unsafe blocks
This commit is contained in:
Gilad Naaman 2021-03-26 11:39:43 +03:00 committed by GitHub
commit c063d2c4ca
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 9 additions and 5 deletions

View File

@ -50,11 +50,13 @@ macro_rules! _memoffset__let_base_ptr {
#[macro_export]
#[doc(hidden)]
macro_rules! _memoffset_offset_from {
($field:expr, $base:expr) => {
($field:expr, $base:expr) => {{
let field = $field; // evaluate $field outside the `unsafe` block
let base = $base; // evaluate $base outside the `unsafe` block
// Compute offset, with unstable `offset_from` for const-compatibility.
// (Requires the pointers to not dangle, but we already need that for `raw_field!` anyway.)
unsafe { ($field as *const u8).offset_from($base as *const u8) as usize }
};
unsafe { (field as *const u8).offset_from(base as *const u8) as usize }
}};
}
#[cfg(not(feature = "unstable_const"))]
#[macro_export]

View File

@ -82,13 +82,14 @@ macro_rules! _memoffset__field_check_tuple {
macro_rules! raw_field {
($base:expr, $parent:path, $field:tt) => {{
_memoffset__field_check!($parent, $field);
let base = $base; // evaluate $base outside the `unsafe` block
// Get the field address.
// Crucially, we know that this will not trigger a deref coercion because
// of the field check we did above.
#[allow(unused_unsafe)] // for when the macro is used in an unsafe block
unsafe {
_memoffset__addr_of!((*($base as *const $parent)).$field)
_memoffset__addr_of!((*(base as *const $parent)).$field)
}
}};
}
@ -103,13 +104,14 @@ macro_rules! raw_field {
macro_rules! raw_field_tuple {
($base:expr, $parent:ty, $field:tt) => {{
_memoffset__field_check_tuple!($parent, $field);
let base = $base; // evaluate $base outside the `unsafe` block
// Get the field address.
// Crucially, we know that this will not trigger a deref coercion because
// of the field check we did above.
#[allow(unused_unsafe)] // for when the macro is used in an unsafe block
unsafe {
_memoffset__addr_of!((*($base as *const $parent)).$field)
_memoffset__addr_of!((*(base as *const $parent)).$field)
}
}};
}