Skip to content

Commit

Permalink
Use memoffset::offset_of instead of homegrown macro
Browse files Browse the repository at this point in the history
The homegrown macro was fine in 2016, but at some point it technically
became UB.  The memoffset crate does the same thing, but avoids UB when
using rustc 1.51.0 or later.

Fixes #1415
  • Loading branch information
asomers committed Aug 14, 2021
1 parent e266b7c commit c0a9fd7
Show file tree
Hide file tree
Showing 4 changed files with 5 additions and 13 deletions.
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ libc = { version = "0.2.99", features = [ "extra_traits" ] }
bitflags = ">= 1.1.0, < 1.3.0"
cfg-if = "1.0"

[target.'cfg(not(target_os = "redox"))'.dependencies]
memoffset = "0.6.3"

[target.'cfg(target_os = "dragonfly")'.build-dependencies]
cc = "1"

Expand Down
13 changes: 0 additions & 13 deletions src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,16 +203,3 @@ macro_rules! libc_enum {
}
};
}

/// A Rust version of the familiar C `offset_of` macro. It returns the byte
/// offset of `field` within struct `ty`
#[cfg(not(target_os = "redox"))]
macro_rules! offset_of {
($ty:ty, $field:ident) => {{
// Safe because we don't actually read from the dereferenced pointer
#[allow(unused_unsafe)] // for when the macro is used in an unsafe block
unsafe {
&(*(ptr::null() as *const $ty)).$field as *const _ as usize
}
}}
}
1 change: 1 addition & 0 deletions src/sys/socket/addr.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use super::sa_family_t;
use crate::{Error, Result, NixPath};
use crate::errno::Errno;
use memoffset::offset_of;
use std::{fmt, mem, net, ptr, slice};
use std::ffi::OsStr;
use std::hash::{Hash, Hasher};
Expand Down
1 change: 1 addition & 0 deletions src/sys/socket/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use cfg_if::cfg_if;
use crate::{Error, Result, errno::Errno};
use libc::{self, c_void, c_int, iovec, socklen_t, size_t,
CMSG_FIRSTHDR, CMSG_NXTHDR, CMSG_DATA, CMSG_LEN};
use memoffset::offset_of;
use std::{mem, ptr, slice};
use std::os::unix::io::RawFd;
use crate::sys::time::TimeVal;
Expand Down

0 comments on commit c0a9fd7

Please sign in to comment.