From 417e91363a25c663ff884f3dcb879832bf0a66ed Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Mon, 19 Aug 2019 15:55:25 -0600 Subject: [PATCH 1/6] Clippy cleanup --- CHANGELOG.md | 11 +++++++ src/dir.rs | 6 ++-- src/errno.rs | 4 +-- src/fcntl.rs | 6 ++-- src/ifaddrs.rs | 4 +-- src/lib.rs | 36 ++++++++++++++++++++-- src/macros.rs | 2 +- src/mqueue.rs | 4 ++- src/poll.rs | 4 +-- src/pty.rs | 8 ++--- src/sys/aio.rs | 1 - src/sys/event.rs | 2 +- src/sys/sendfile.rs | 4 ++- src/sys/signal.rs | 4 +-- src/sys/socket/addr.rs | 63 ++++++++++++++++++++------------------- src/sys/socket/mod.rs | 54 ++++++++++++++++----------------- src/sys/socket/sockopt.rs | 2 +- src/sys/time.rs | 8 ++--- src/sys/wait.rs | 2 +- src/unistd.rs | 24 ++++++++------- 20 files changed, 149 insertions(+), 100 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 91af769efe..cace80d7ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ This project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] - ReleaseDate ### Added + +- Added `NixPath::is_empty`. + ([#1107](https://github.com/nix-rust/nix/pull/1107)) + ### Changed - Changed `readlink` and `readlinkat` to return `OsString` ([#1109](https://github.com/nix-rust/nix/pull/1109)) @@ -25,6 +29,13 @@ This project adheres to [Semantic Versioning](http://semver.org/). - Minimum supported Rust version is now 1.36.0. ([#1108](https://github.com/nix-rust/nix/pull/1108)) + +- `Ipv4Addr::octets`, `Ipv4Addr::to_std`, `Error::as_errno`, + `ForkResult::is_child`, `ForkResult::is_parent`, `Gid::as_raw`, + `Uid::is_root`, `Uid::as_raw`, `Pid::as_raw`, and `PollFd::revents` now take + `self` by value. + ([#1107](https://github.com/nix-rust/nix/pull/1107)) + ### Fixed ### Removed diff --git a/src/dir.rs b/src/dir.rs index 1820b5330f..5dfc51c9c1 100644 --- a/src/dir.rs +++ b/src/dir.rs @@ -107,11 +107,11 @@ impl<'d> Iterator for Iter<'d> { if let Err(e) = Errno::result(readdir_r((self.0).0.as_ptr(), &mut ent.0, &mut result)) { return Some(Err(e)); } - if result == ptr::null_mut() { + if result.is_null() { return None; } assert_eq!(result, &mut ent.0 as *mut dirent); - return Some(Ok(ent)); + Some(Ok(ent)) } } } @@ -165,7 +165,7 @@ impl Entry { target_os = "macos", target_os = "solaris")))] pub fn ino(&self) -> u64 { - self.0.d_fileno as u64 + u64::from(self.0.d_fileno) } /// Returns the bare file name of this directory entry without any other leading path component. diff --git a/src/errno.rs b/src/errno.rs index 6a2447bc52..287bbea432 100644 --- a/src/errno.rs +++ b/src/errno.rs @@ -46,7 +46,7 @@ cfg_if! { } /// Sets the platform-specific errno to no-error -unsafe fn clear() -> () { +unsafe fn clear() { *errno_location() = 0; } @@ -70,7 +70,7 @@ impl Errno { from_i32(err) } - pub unsafe fn clear() -> () { + pub unsafe fn clear() { clear() } diff --git a/src/fcntl.rs b/src/fcntl.rs index 08c339a912..7ccb737670 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -152,7 +152,8 @@ libc_bitflags!( pub fn open(path: &P, oflag: OFlag, mode: Mode) -> Result { let fd = path.with_nix_path(|cstr| { - unsafe { libc::open(cstr.as_ptr(), oflag.bits(), mode.bits() as c_uint) } + let modebits = c_uint::from(mode.bits()); + unsafe { libc::open(cstr.as_ptr(), oflag.bits(), modebits) } })?; Errno::result(fd) @@ -160,7 +161,8 @@ pub fn open(path: &P, oflag: OFlag, mode: Mode) -> Result(dirfd: RawFd, path: &P, oflag: OFlag, mode: Mode) -> Result { let fd = path.with_nix_path(|cstr| { - unsafe { libc::openat(dirfd, cstr.as_ptr(), oflag.bits(), mode.bits() as c_uint) } + let modebits = c_uint::from(mode.bits()); + unsafe { libc::openat(dirfd, cstr.as_ptr(), oflag.bits(), modebits) } })?; Errno::result(fd) } diff --git a/src/ifaddrs.rs b/src/ifaddrs.rs index 12b59bcc92..0485b1bb71 100644 --- a/src/ifaddrs.rs +++ b/src/ifaddrs.rs @@ -52,8 +52,8 @@ impl InterfaceAddress { let mut addr = InterfaceAddress { interface_name: ifname.to_string_lossy().to_string(), flags: InterfaceFlags::from_bits_truncate(info.ifa_flags as i32), - address: address, - netmask: netmask, + address, + netmask, broadcast: None, destination: None, }; diff --git a/src/lib.rs b/src/lib.rs index 71485d2af1..e3f064c6b5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -121,9 +121,9 @@ impl Error { /// let e = Error::from(Errno::EPERM); /// assert_eq!(Some(Errno::EPERM), e.as_errno()); /// ``` - pub fn as_errno(&self) -> Option { - if let &Error::Sys(ref e) = self { - Some(*e) + pub fn as_errno(self) -> Option { + if let Error::Sys(e) = self { + Some(e) } else { None } @@ -177,6 +177,8 @@ impl fmt::Display for Error { } pub trait NixPath { + fn is_empty(&self) -> bool; + fn len(&self) -> usize; fn with_nix_path(&self, f: F) -> Result @@ -184,6 +186,10 @@ pub trait NixPath { } impl NixPath for str { + fn is_empty(&self) -> bool { + NixPath::is_empty(OsStr::new(self)) + } + fn len(&self) -> usize { NixPath::len(OsStr::new(self)) } @@ -195,6 +201,10 @@ impl NixPath for str { } impl NixPath for OsStr { + fn is_empty(&self) -> bool { + self.as_bytes().is_empty() + } + fn len(&self) -> usize { self.as_bytes().len() } @@ -206,6 +216,10 @@ impl NixPath for OsStr { } impl NixPath for CStr { + fn is_empty(&self) -> bool { + self.to_bytes().is_empty() + } + fn len(&self) -> usize { self.to_bytes().len() } @@ -222,6 +236,10 @@ impl NixPath for CStr { } impl NixPath for [u8] { + fn is_empty(&self) -> bool { + self.is_empty() + } + fn len(&self) -> usize { self.len() } @@ -249,6 +267,10 @@ impl NixPath for [u8] { } impl NixPath for Path { + fn is_empty(&self) -> bool { + NixPath::is_empty(self.as_os_str()) + } + fn len(&self) -> usize { NixPath::len(self.as_os_str()) } @@ -259,6 +281,10 @@ impl NixPath for Path { } impl NixPath for PathBuf { + fn is_empty(&self) -> bool { + NixPath::is_empty(self.as_os_str()) + } + fn len(&self) -> usize { NixPath::len(self.as_os_str()) } @@ -270,6 +296,10 @@ impl NixPath for PathBuf { /// Treats `None` as an empty string. impl<'a, NP: ?Sized + NixPath> NixPath for Option<&'a NP> { + fn is_empty(&self) -> bool { + self.map_or(true, NixPath::is_empty) + } + fn len(&self) -> usize { self.map_or(0, NixPath::len) } diff --git a/src/macros.rs b/src/macros.rs index 3d1b0e4b76..7ec00c86c6 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -259,6 +259,6 @@ macro_rules! libc_enum { /// offset of `field` within struct `ty` macro_rules! offset_of { ($ty:ty, $field:ident) => { - &(*(0 as *const $ty)).$field as *const _ as usize + &(*(ptr::null() as *const $ty)).$field as *const _ as usize } } diff --git a/src/mqueue.rs b/src/mqueue.rs index b958b71cdd..a35f895b84 100644 --- a/src/mqueue.rs +++ b/src/mqueue.rs @@ -57,6 +57,8 @@ impl MqAttr { /// Open a message queue /// /// See also [`mq_open(2)`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mq_open.html) +// The mode.bits cast is only lossless on some OSes +#[allow(clippy::cast_lossless)] pub fn mq_open(name: &CString, oflag: MQ_OFlag, mode: Mode, @@ -142,7 +144,7 @@ pub fn mq_setattr(mqd: mqd_t, newattr: &MqAttr) -> Result { /// Returns the old attributes pub fn mq_set_nonblock(mqd: mqd_t) -> Result<(MqAttr)> { let oldattr = mq_getattr(mqd)?; - let newattr = MqAttr::new(MQ_OFlag::O_NONBLOCK.bits() as c_long, + let newattr = MqAttr::new(c_long::from(MQ_OFlag::O_NONBLOCK.bits()), oldattr.mq_attr.mq_maxmsg, oldattr.mq_attr.mq_msgsize, oldattr.mq_attr.mq_curmsgs); diff --git a/src/poll.rs b/src/poll.rs index c603611e31..15bafe2d64 100644 --- a/src/poll.rs +++ b/src/poll.rs @@ -29,7 +29,7 @@ impl PollFd { pub fn new(fd: RawFd, events: PollFlags) -> PollFd { PollFd { pollfd: libc::pollfd { - fd: fd, + fd, events: events.bits(), revents: PollFlags::empty().bits(), }, @@ -37,7 +37,7 @@ impl PollFd { } /// Returns the events that occured in the last call to `poll` or `ppoll`. - pub fn revents(&self) -> Option { + pub fn revents(self) -> Option { PollFlags::from_bits(self.pollfd.revents) } } diff --git a/src/pty.rs b/src/pty.rs index db012d8158..51b269ef66 100644 --- a/src/pty.rs +++ b/src/pty.rs @@ -274,8 +274,8 @@ pub fn openpty<'a, 'b, T: Into>, U: Into Errno::result(ret)?; Ok(OpenptyResult { - master: master, - slave: slave, + master, + slave, }) } @@ -319,8 +319,8 @@ pub fn forkpty<'a, 'b, T: Into>, U: Into })?; Ok(ForkptyResult { - master: master, - fork_result: fork_result, + master, + fork_result, }) } diff --git a/src/sys/aio.rs b/src/sys/aio.rs index 9258a0657c..dc2663ca89 100644 --- a/src/sys/aio.rs +++ b/src/sys/aio.rs @@ -1213,7 +1213,6 @@ impl<'a> LioCb<'a> { }, Err(Error::Sys(Errno::EINPROGRESS)) => { // aiocb is was successfully queued; no need to do anything - () }, Err(Error::Sys(Errno::EINVAL)) => panic!( "AioCb was never submitted, or already finalized"), diff --git a/src/sys/event.rs b/src/sys/event.rs index 8cd7372f88..882223bd76 100644 --- a/src/sys/event.rs +++ b/src/sys/event.rs @@ -234,7 +234,7 @@ impl KEvent { pub fn new(ident: uintptr_t, filter: EventFilter, flags: EventFlag, fflags:FilterFlag, data: intptr_t, udata: intptr_t) -> KEvent { KEvent { kevent: libc::kevent { - ident: ident, + ident, filter: filter as type_of_event_filter, flags: flags.bits(), fflags: fflags.bits(), diff --git a/src/sys/sendfile.rs b/src/sys/sendfile.rs index a47d8962f7..1618558a10 100644 --- a/src/sys/sendfile.rs +++ b/src/sys/sendfile.rs @@ -123,6 +123,7 @@ cfg_if! { /// /// For more information, see /// [the sendfile(2) man page.](https://www.freebsd.org/cgi/man.cgi?query=sendfile&sektion=2) + #[allow(clippy::too_many_arguments)] pub fn sendfile( in_fd: RawFd, out_sock: RawFd, @@ -136,7 +137,8 @@ cfg_if! { // Readahead goes in upper 16 bits // Flags goes in lower 16 bits // see `man 2 sendfile` - let flags: u32 = ((readahead as u32) << 16) | (flags.bits() as u32); + let ra32 = u32::from(readahead); + let flags: u32 = (ra32 << 16) | (flags.bits() as u32); let mut bytes_sent: off_t = 0; let hdtr = headers.or(trailers).map(|_| SendfileHeaderTrailer::new(headers, trailers)); let hdtr_ptr = hdtr.as_ref().map_or(ptr::null(), |s| &s.0 as *const libc::sf_hdtr); diff --git a/src/sys/signal.rs b/src/sys/signal.rs index 1013a77fd4..51df7b12f9 100644 --- a/src/sys/signal.rs +++ b/src/sys/signal.rs @@ -338,14 +338,14 @@ impl SigSet { let mut sigset: libc::sigset_t = unsafe { mem::uninitialized() }; let _ = unsafe { libc::sigfillset(&mut sigset as *mut libc::sigset_t) }; - SigSet { sigset: sigset } + SigSet { sigset } } pub fn empty() -> SigSet { let mut sigset: libc::sigset_t = unsafe { mem::uninitialized() }; let _ = unsafe { libc::sigemptyset(&mut sigset as *mut libc::sigset_t) }; - SigSet { sigset: sigset } + SigSet { sigset } } pub fn add(&mut self, signal: Signal) { diff --git a/src/sys/socket/addr.rs b/src/sys/socket/addr.rs index ed41441155..1c6f1b545d 100644 --- a/src/sys/socket/addr.rs +++ b/src/sys/socket/addr.rs @@ -367,6 +367,8 @@ impl IpAddr { /// Create a new IpAddr that contains an IPv6 address. /// /// The result will represent the IP address a:b:c:d:e:f + #[allow(clippy::many_single_char_names)] + #[allow(clippy::too_many_arguments)] pub fn new_v6(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> IpAddr { IpAddr::V6(Ipv6Addr::new(a, b, c, d, e, f, g, h)) } @@ -405,15 +407,18 @@ impl fmt::Display for IpAddr { pub struct Ipv4Addr(pub libc::in_addr); impl Ipv4Addr { + #[allow(clippy::identity_op)] // More readable this way pub fn new(a: u8, b: u8, c: u8, d: u8) -> Ipv4Addr { - let ip = (((a as u32) << 24) | - ((b as u32) << 16) | - ((c as u32) << 8) | - ((d as u32) << 0)).to_be(); + let ip = ((u32::from(a) << 24) | + (u32::from(b) << 16) | + (u32::from(c) << 8) | + (u32::from(d) << 0)).to_be(); Ipv4Addr(libc::in_addr { s_addr: ip }) } + // Use pass by reference for symmetry with Ipv6Addr::from_std + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn from_std(std: &net::Ipv4Addr) -> Ipv4Addr { let bits = std.octets(); Ipv4Addr::new(bits[0], bits[1], bits[2], bits[3]) @@ -423,12 +428,12 @@ impl Ipv4Addr { Ipv4Addr(libc::in_addr { s_addr: libc::INADDR_ANY }) } - pub fn octets(&self) -> [u8; 4] { + pub fn octets(self) -> [u8; 4] { let bits = u32::from_be(self.0.s_addr); [(bits >> 24) as u8, (bits >> 16) as u8, (bits >> 8) as u8, bits as u8] } - pub fn to_std(&self) -> net::Ipv4Addr { + pub fn to_std(self) -> net::Ipv4Addr { let bits = self.octets(); net::Ipv4Addr::new(bits[0], bits[1], bits[2], bits[3]) } @@ -467,6 +472,8 @@ macro_rules! to_u16_array { } impl Ipv6Addr { + #[allow(clippy::many_single_char_names)] + #[allow(clippy::too_many_arguments)] pub fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> Ipv6Addr { let mut in6_addr_var: libc::in6_addr = unsafe{mem::uninitialized()}; in6_addr_var.s6_addr = to_u8_array!(a,b,c,d,e,f,g,h); @@ -713,7 +720,7 @@ impl SockAddr { if addr.is_null() { None } else { - match AddressFamily::from_i32((*addr).sa_family as i32) { + match AddressFamily::from_i32(i32::from((*addr).sa_family)) { Some(AddressFamily::Unix) => None, Some(AddressFamily::Inet) => Some(SockAddr::Inet( InetAddr::V4(*(addr as *const libc::sockaddr_in)))), @@ -957,7 +964,7 @@ pub mod sys_control { let mut ctl_name = [0; MAX_KCTL_NAME]; ctl_name[..name.len()].clone_from_slice(name.as_bytes()); - let mut info = ctl_ioc_info { ctl_id: 0, ctl_name: ctl_name }; + let mut info = ctl_ioc_info { ctl_id: 0, ctl_name }; unsafe { ctl_info(sockfd, &mut info)?; } @@ -1023,14 +1030,14 @@ mod datalink { /// Physical-layer address (MAC) pub fn addr(&self) -> [u8; 6] { - let a = self.0.sll_addr[0] as u8; - let b = self.0.sll_addr[1] as u8; - let c = self.0.sll_addr[2] as u8; - let d = self.0.sll_addr[3] as u8; - let e = self.0.sll_addr[4] as u8; - let f = self.0.sll_addr[5] as u8; - - [a, b, c, d, e, f] + [ + self.0.sll_addr[0] as u8, + self.0.sll_addr[1] as u8, + self.0.sll_addr[2] as u8, + self.0.sll_addr[3] as u8, + self.0.sll_addr[4] as u8, + self.0.sll_addr[5] as u8, + ] } } @@ -1069,7 +1076,7 @@ mod datalink { /// always == AF_LINK pub fn family(&self) -> AddressFamily { - assert_eq!(self.0.sdl_family as i32, libc::AF_LINK); + assert_eq!(i32::from(self.0.sdl_family), libc::AF_LINK); AddressFamily::Link } @@ -1105,11 +1112,7 @@ mod datalink { let alen = self.alen(); let data_len = self.0.sdl_data.len(); - if alen > 0 && nlen + alen < data_len { - false - } else { - true - } + alen == 0 || nlen + alen >= data_len } /// Physical-layer address (MAC) @@ -1119,14 +1122,14 @@ mod datalink { assert!(!self.is_empty()); - let a = data[nlen] as u8; - let b = data[nlen + 1] as u8; - let c = data[nlen + 2] as u8; - let d = data[nlen + 3] as u8; - let e = data[nlen + 4] as u8; - let f = data[nlen + 5] as u8; - - [a, b, c, d, e, f] + [ + data[nlen] as u8, + data[nlen + 1] as u8, + data[nlen + 2] as u8, + data[nlen + 3] as u8, + data[nlen + 4] as u8, + data[nlen + 5] as u8, + ] } } diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 1c12c5f851..0bb7b2f331 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -553,11 +553,10 @@ impl ControlMessageOwned { let n = len / mem::size_of::(); let mut fds = Vec::with_capacity(n); for i in 0..n { - let fdp = (p as *const RawFd).offset(i as isize); + let fdp = (p as *const RawFd).add(i); fds.push(ptr::read_unaligned(fdp)); } - let cmo = ControlMessageOwned::ScmRights(fds); - cmo + ControlMessageOwned::ScmRights(fds) }, #[cfg(any(target_os = "android", target_os = "linux"))] (libc::SOL_SOCKET, libc::SCM_CREDENTIALS) => { @@ -715,16 +714,16 @@ impl<'a> ControlMessage<'a> { /// Return a reference to the payload data as a byte pointer fn copy_to_cmsg_data(&self, cmsg_data: *mut u8) { - let data_ptr = match self { - &ControlMessage::ScmRights(fds) => { + let data_ptr = match *self { + ControlMessage::ScmRights(fds) => { fds as *const _ as *const u8 }, #[cfg(any(target_os = "android", target_os = "linux"))] - &ControlMessage::ScmCredentials(creds) => { + ControlMessage::ScmCredentials(creds) => { creds as *const libc::ucred as *const u8 } #[cfg(any(target_os = "android", target_os = "linux"))] - &ControlMessage::AlgSetIv(iv) => { + ControlMessage::AlgSetIv(iv) => { unsafe { let alg_iv = cmsg_data as *mut libc::af_alg_iv; (*alg_iv).ivlen = iv.len() as u32; @@ -737,11 +736,11 @@ impl<'a> ControlMessage<'a> { return }, #[cfg(any(target_os = "android", target_os = "linux"))] - &ControlMessage::AlgSetOp(op) => { + ControlMessage::AlgSetOp(op) => { op as *const _ as *const u8 }, #[cfg(any(target_os = "android", target_os = "linux"))] - &ControlMessage::AlgSetAeadAssoclen(len) => { + ControlMessage::AlgSetAeadAssoclen(len) => { len as *const _ as *const u8 }, }; @@ -756,24 +755,24 @@ impl<'a> ControlMessage<'a> { /// The size of the payload, excluding its cmsghdr fn len(&self) -> usize { - match self { - &ControlMessage::ScmRights(fds) => { + match *self { + ControlMessage::ScmRights(fds) => { mem::size_of_val(fds) }, #[cfg(any(target_os = "android", target_os = "linux"))] - &ControlMessage::ScmCredentials(creds) => { + ControlMessage::ScmCredentials(creds) => { mem::size_of_val(creds) } #[cfg(any(target_os = "android", target_os = "linux"))] - &ControlMessage::AlgSetIv(iv) => { + ControlMessage::AlgSetIv(iv) => { mem::size_of::() + iv.len() }, #[cfg(any(target_os = "android", target_os = "linux"))] - &ControlMessage::AlgSetOp(op) => { + ControlMessage::AlgSetOp(op) => { mem::size_of_val(op) }, #[cfg(any(target_os = "android", target_os = "linux"))] - &ControlMessage::AlgSetAeadAssoclen(len) => { + ControlMessage::AlgSetAeadAssoclen(len) => { mem::size_of_val(len) }, } @@ -781,33 +780,32 @@ impl<'a> ControlMessage<'a> { /// Returns the value to put into the `cmsg_level` field of the header. fn cmsg_level(&self) -> libc::c_int { - match self { - &ControlMessage::ScmRights(_) => libc::SOL_SOCKET, + match *self { + ControlMessage::ScmRights(_) => libc::SOL_SOCKET, #[cfg(any(target_os = "android", target_os = "linux"))] - &ControlMessage::ScmCredentials(_) => libc::SOL_SOCKET, + ControlMessage::ScmCredentials(_) => libc::SOL_SOCKET, #[cfg(any(target_os = "android", target_os = "linux"))] - &ControlMessage::AlgSetIv(_) | &ControlMessage::AlgSetOp(_) | &ControlMessage::AlgSetAeadAssoclen(_) => { - libc::SOL_ALG - }, + ControlMessage::AlgSetIv(_) | ControlMessage::AlgSetOp(_) | + ControlMessage::AlgSetAeadAssoclen(_) => libc::SOL_ALG , } } /// Returns the value to put into the `cmsg_type` field of the header. fn cmsg_type(&self) -> libc::c_int { - match self { - &ControlMessage::ScmRights(_) => libc::SCM_RIGHTS, + match *self { + ControlMessage::ScmRights(_) => libc::SCM_RIGHTS, #[cfg(any(target_os = "android", target_os = "linux"))] - &ControlMessage::ScmCredentials(_) => libc::SCM_CREDENTIALS, + ControlMessage::ScmCredentials(_) => libc::SCM_CREDENTIALS, #[cfg(any(target_os = "android", target_os = "linux"))] - &ControlMessage::AlgSetIv(_) => { + ControlMessage::AlgSetIv(_) => { libc::ALG_SET_IV }, #[cfg(any(target_os = "android", target_os = "linux"))] - &ControlMessage::AlgSetOp(_) => { + ControlMessage::AlgSetOp(_) => { libc::ALG_SET_OP }, #[cfg(any(target_os = "android", target_os = "linux"))] - &ControlMessage::AlgSetAeadAssoclen(_) => { + ControlMessage::AlgSetAeadAssoclen(_) => { libc::ALG_SET_AEAD_ASSOCLEN }, } @@ -1231,7 +1229,7 @@ pub unsafe fn sockaddr_storage_to_addr( return Err(Error::Sys(Errno::ENOTCONN)); } - match addr.ss_family as c_int { + match c_int::from(addr.ss_family) { libc::AF_INET => { assert!(len as usize == mem::size_of::()); let ret = *(addr as *const _ as *const sockaddr_in); diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index a996010018..1271f6459c 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -423,7 +423,7 @@ struct SetStruct<'a, T: 'static> { unsafe impl<'a, T> Set<'a, T> for SetStruct<'a, T> { fn new(ptr: &'a T) -> SetStruct<'a, T> { - SetStruct { ptr: ptr } + SetStruct { ptr } } fn ffi_ptr(&self) -> *const c_void { diff --git a/src/sys/time.rs b/src/sys/time.rs index 3ad57543b1..606bbd9d9b 100644 --- a/src/sys/time.rs +++ b/src/sys/time.rs @@ -191,7 +191,7 @@ impl ops::Mul for TimeSpec { type Output = TimeSpec; fn mul(self, rhs: i32) -> TimeSpec { - let usec = self.num_nanoseconds().checked_mul(rhs as i64) + let usec = self.num_nanoseconds().checked_mul(i64::from(rhs)) .expect("TimeSpec multiply out of bounds"); TimeSpec::nanoseconds(usec) @@ -202,7 +202,7 @@ impl ops::Div for TimeSpec { type Output = TimeSpec; fn div(self, rhs: i32) -> TimeSpec { - let usec = self.num_nanoseconds() / rhs as i64; + let usec = self.num_nanoseconds() / i64::from(rhs); TimeSpec::nanoseconds(usec) } } @@ -386,7 +386,7 @@ impl ops::Mul for TimeVal { type Output = TimeVal; fn mul(self, rhs: i32) -> TimeVal { - let usec = self.num_microseconds().checked_mul(rhs as i64) + let usec = self.num_microseconds().checked_mul(i64::from(rhs)) .expect("TimeVal multiply out of bounds"); TimeVal::microseconds(usec) @@ -397,7 +397,7 @@ impl ops::Div for TimeVal { type Output = TimeVal; fn div(self, rhs: i32) -> TimeVal { - let usec = self.num_microseconds() / rhs as i64; + let usec = self.num_microseconds() / i64::from(rhs); TimeVal::microseconds(usec) } } diff --git a/src/sys/wait.rs b/src/sys/wait.rs index c54f7ec579..7b749990e4 100644 --- a/src/sys/wait.rs +++ b/src/sys/wait.rs @@ -222,7 +222,7 @@ pub fn waitpid>>(pid: P, options: Option) -> Re let res = unsafe { libc::waitpid( - pid.into().unwrap_or(Pid::from_raw(-1)).into(), + pid.into().unwrap_or_else(|| Pid::from_raw(-1)).into(), &mut status as *mut c_int, option_bits, ) diff --git a/src/unistd.rs b/src/unistd.rs index f422f09198..10999651ab 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -45,12 +45,12 @@ impl Uid { } /// Returns true if the `Uid` represents privileged user - root. (If it equals zero.) - pub fn is_root(&self) -> bool { - *self == ROOT + pub fn is_root(self) -> bool { + self == ROOT } /// Get the raw `uid_t` wrapped by `self`. - pub fn as_raw(&self) -> uid_t { + pub fn as_raw(self) -> uid_t { self.0 } } @@ -94,7 +94,7 @@ impl Gid { } /// Get the raw `gid_t` wrapped by `self`. - pub fn as_raw(&self) -> gid_t { + pub fn as_raw(self) -> gid_t { self.0 } } @@ -135,7 +135,7 @@ impl Pid { } /// Get the raw `pid_t` wrapped by `self`. - pub fn as_raw(&self) -> pid_t { + pub fn as_raw(self) -> pid_t { self.0 } } @@ -168,8 +168,8 @@ impl ForkResult { /// Return `true` if this is the child process of the `fork()` #[inline] - pub fn is_child(&self) -> bool { - match *self { + pub fn is_child(self) -> bool { + match self { ForkResult::Child => true, _ => false } @@ -177,7 +177,7 @@ impl ForkResult { /// Returns `true` if this is the parent process of the `fork()` #[inline] - pub fn is_parent(&self) -> bool { + pub fn is_parent(self) -> bool { !self.is_child() } } @@ -590,8 +590,10 @@ fn chown_raw_ids(owner: Option, group: Option) -> (libc::uid_t, libc:: // According to the POSIX specification, -1 is used to indicate that owner and group // are not to be changed. Since uid_t and gid_t are unsigned types, we have to wrap // around to get -1. - let uid = owner.map(Into::into).unwrap_or((0 as uid_t).wrapping_sub(1)); - let gid = group.map(Into::into).unwrap_or((0 as gid_t).wrapping_sub(1)); + let uid = owner.map(Into::into) + .unwrap_or_else(|| (0 as uid_t).wrapping_sub(1)); + let gid = group.map(Into::into) + .unwrap_or_else(|| (0 as gid_t).wrapping_sub(1)); (uid, gid) } @@ -1199,7 +1201,7 @@ pub fn chroot(path: &P) -> Result<()> { target_os = "netbsd", target_os = "openbsd" ))] -pub fn sync() -> () { +pub fn sync() { unsafe { libc::sync() }; } From 9e360145be630275a9b8a73dc32462ef406d20f6 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Mon, 19 Aug 2019 16:19:24 -0600 Subject: [PATCH 2/6] Clippy: remove unnecessary mem::transmute --- src/sys/socket/addr.rs | 46 +++++++++++++++++++++++++++++++++--------- src/sys/socket/mod.rs | 20 ++++++++++++------ 2 files changed, 51 insertions(+), 15 deletions(-) diff --git a/src/sys/socket/addr.rs b/src/sys/socket/addr.rs index 1c6f1b545d..cbec71f75b 100644 --- a/src/sys/socket/addr.rs +++ b/src/sys/socket/addr.rs @@ -768,26 +768,54 @@ impl SockAddr { /// a sockaddr * need to take the size of the underlying type as well and then internally cast it back. pub unsafe fn as_ffi_pair(&self) -> (&libc::sockaddr, libc::socklen_t) { match *self { - SockAddr::Inet(InetAddr::V4(ref addr)) => (mem::transmute(addr), mem::size_of::() as libc::socklen_t), - SockAddr::Inet(InetAddr::V6(ref addr)) => (mem::transmute(addr), mem::size_of::() as libc::socklen_t), - SockAddr::Unix(UnixAddr(ref addr, len)) => (mem::transmute(addr), (len + offset_of!(libc::sockaddr_un, sun_path)) as libc::socklen_t), + SockAddr::Inet(InetAddr::V4(ref addr)) => ( + &*(addr as *const libc::sockaddr_in as *const libc::sockaddr), + mem::size_of_val(addr) as libc::socklen_t + ), + SockAddr::Inet(InetAddr::V6(ref addr)) => ( + &*(addr as *const libc::sockaddr_in6 as *const libc::sockaddr), + mem::size_of_val(addr) as libc::socklen_t + ), + SockAddr::Unix(UnixAddr(ref addr, len)) => ( + &*(addr as *const libc::sockaddr_un as *const libc::sockaddr), + (len + offset_of!(libc::sockaddr_un, sun_path)) as libc::socklen_t + ), #[cfg(any(target_os = "android", target_os = "linux"))] - SockAddr::Netlink(NetlinkAddr(ref sa)) => (mem::transmute(sa), mem::size_of::() as libc::socklen_t), + SockAddr::Netlink(NetlinkAddr(ref sa)) => ( + &*(sa as *const libc::sockaddr_nl as *const libc::sockaddr), + mem::size_of_val(sa) as libc::socklen_t + ), #[cfg(any(target_os = "android", target_os = "linux"))] - SockAddr::Alg(AlgAddr(ref sa)) => (mem::transmute(sa), mem::size_of::() as libc::socklen_t), + SockAddr::Alg(AlgAddr(ref sa)) => ( + &*(sa as *const libc::sockaddr_alg as *const libc::sockaddr), + mem::size_of_val(sa) as libc::socklen_t + ), #[cfg(any(target_os = "ios", target_os = "macos"))] - SockAddr::SysControl(SysControlAddr(ref sa)) => (mem::transmute(sa), mem::size_of::() as libc::socklen_t), + SockAddr::SysControl(SysControlAddr(ref sa)) => ( + &*(sa as *const libc::sockaddr_ctl as *const libc::sockaddr), + mem::size_of_val(sa) as libc::socklen_t + + ), #[cfg(any(target_os = "android", target_os = "linux"))] - SockAddr::Link(LinkAddr(ref ether_addr)) => (mem::transmute(ether_addr), mem::size_of::() as libc::socklen_t), + SockAddr::Link(LinkAddr(ref addr)) => ( + &*(addr as *const libc::sockaddr_ll as *const libc::sockaddr), + mem::size_of_val(addr) as libc::socklen_t + ), #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "ios", target_os = "macos", target_os = "netbsd", target_os = "openbsd"))] - SockAddr::Link(LinkAddr(ref ether_addr)) => (mem::transmute(ether_addr), mem::size_of::() as libc::socklen_t), + SockAddr::Link(LinkAddr(ref addr)) => ( + &*(addr as *const libc::sockaddr_dl as *const libc::sockaddr), + mem::size_of_val(addr) as libc::socklen_t + ), #[cfg(target_os = "linux")] - SockAddr::Vsock(VsockAddr(ref sa)) => (mem::transmute(sa), mem::size_of::() as libc::socklen_t), + SockAddr::Vsock(VsockAddr(ref sa)) => ( + &*(sa as *const libc::sockaddr_vm as *const libc::sockaddr), + mem::size_of_val(sa) as libc::socklen_t + ), } } } diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 0bb7b2f331..8ea7fb9f5f 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -1074,7 +1074,7 @@ pub fn recv(sockfd: RawFd, buf: &mut [u8], flags: MsgFlags) -> Result { /// [Further reading](http://pubs.opengroup.org/onlinepubs/9699919799/functions/recvfrom.html) pub fn recvfrom(sockfd: RawFd, buf: &mut [u8]) -> Result<(usize, SockAddr)> { unsafe { - let addr: sockaddr_storage = mem::zeroed(); + let mut addr: sockaddr_storage = mem::zeroed(); let mut len = mem::size_of::() as socklen_t; let ret = Errno::result(libc::recvfrom( @@ -1082,7 +1082,7 @@ pub fn recvfrom(sockfd: RawFd, buf: &mut [u8]) -> Result<(usize, SockAddr)> { buf.as_ptr() as *mut c_void, buf.len() as size_t, 0, - mem::transmute(&addr), + &mut addr as *mut libc::sockaddr_storage as *mut libc::sockaddr, &mut len as *mut socklen_t))?; sockaddr_storage_to_addr(&addr, len as usize) @@ -1188,10 +1188,14 @@ pub fn setsockopt(fd: RawFd, opt: O, val: &O::Val) -> Result<()> /// [Further reading](http://pubs.opengroup.org/onlinepubs/9699919799/functions/getpeername.html) pub fn getpeername(fd: RawFd) -> Result { unsafe { - let addr: sockaddr_storage = mem::uninitialized(); + let mut addr: sockaddr_storage = mem::uninitialized(); let mut len = mem::size_of::() as socklen_t; - let ret = libc::getpeername(fd, mem::transmute(&addr), &mut len); + let ret = libc::getpeername( + fd, + &mut addr as *mut libc::sockaddr_storage as *mut libc::sockaddr, + &mut len + ); Errno::result(ret)?; @@ -1204,10 +1208,14 @@ pub fn getpeername(fd: RawFd) -> Result { /// [Further reading](http://pubs.opengroup.org/onlinepubs/9699919799/functions/getsockname.html) pub fn getsockname(fd: RawFd) -> Result { unsafe { - let addr: sockaddr_storage = mem::uninitialized(); + let mut addr: sockaddr_storage = mem::uninitialized(); let mut len = mem::size_of::() as socklen_t; - let ret = libc::getsockname(fd, mem::transmute(&addr), &mut len); + let ret = libc::getsockname( + fd, + &mut addr as *mut libc::sockaddr_storage as *mut libc::sockaddr, + &mut len + ); Errno::result(ret)?; From 060d03d4500ca7d65428235173c27b60326c536c Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Mon, 19 Aug 2019 16:26:24 -0600 Subject: [PATCH 3/6] Clippy: silence a false-positive cast alignment warning --- src/sys/socket/mod.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 8ea7fb9f5f..6c67648b4a 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -543,6 +543,9 @@ impl ControlMessageOwned { /// /// Returns `None` if the data may be unaligned. In that case use /// `ControlMessageOwned::decode_from`. + // Clippy complains about the pointer alignment of `p`, not understanding + // that it's being fed to a function that can handle that. + #[allow(clippy::cast_ptr_alignment)] unsafe fn decode_from(header: &cmsghdr) -> ControlMessageOwned { let p = CMSG_DATA(header); From 64e9e8f05c9b0402f31d6316960a214b64c09527 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Mon, 19 Aug 2019 16:35:30 -0600 Subject: [PATCH 4/6] Remove an obsolete comment It was leftover from internal churn during PR #1020. --- src/sys/socket/mod.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 6c67648b4a..8dc8a5caff 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -540,9 +540,6 @@ impl ControlMessageOwned { /// specified in the header. Normally, the kernel ensures that this is the /// case. "Correct" in this case includes correct length, alignment and /// actual content. - /// - /// Returns `None` if the data may be unaligned. In that case use - /// `ControlMessageOwned::decode_from`. // Clippy complains about the pointer alignment of `p`, not understanding // that it's being fed to a function that can handle that. #[allow(clippy::cast_ptr_alignment)] From 4a8edd6fcdf3cfd40dd47069a96dc60869efc987 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Mon, 19 Aug 2019 16:53:27 -0600 Subject: [PATCH 5/6] Implement Default for FdSet --- CHANGELOG.md | 3 +++ src/sys/select.rs | 6 ++++++ src/sys/socket/mod.rs | 2 ++ 3 files changed, 11 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cace80d7ce..88b014e1da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ This project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] - ReleaseDate ### Added +- Implemented `Default` for `FdSet` + ([#1107](https://github.com/nix-rust/nix/pull/1107)) + - Added `NixPath::is_empty`. ([#1107](https://github.com/nix-rust/nix/pull/1107)) diff --git a/src/sys/select.rs b/src/sys/select.rs index 1b518e29f6..9d60ffaf66 100644 --- a/src/sys/select.rs +++ b/src/sys/select.rs @@ -69,6 +69,12 @@ impl FdSet { } } +impl Default for FdSet { + fn default() -> Self { + Self::new() + } +} + /// Monitors file descriptors for readiness /// /// Returns the total number of ready file descriptors in all sets. The sets are changed so that all diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 8dc8a5caff..662d880353 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -344,6 +344,8 @@ impl CmsgSpace { /// Create a CmsgSpace. The structure is used only for space, so /// the fields are uninitialized. #[deprecated( since="0.14.0", note="Use the cmsg_space! macro instead")] + // It's deprecated anyway; no sense adding Default + #[allow(clippy::new_without_default)] pub fn new() -> Self { // Safe because the fields themselves aren't accessible. unsafe { mem::uninitialized() } From 1c267caf2f9784db47dffc764c5b71b8e918e567 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Thu, 29 Aug 2019 10:05:32 -0600 Subject: [PATCH 6/6] Clippy: remove an unused lifetime parameter --- src/fcntl.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/fcntl.rs b/src/fcntl.rs index 7ccb737670..2cb7f50575 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -189,7 +189,7 @@ fn wrap_readlink_result(v: &mut Vec, res: ssize_t) -> Result { } } -pub fn readlink<'a, P: ?Sized + NixPath>(path: &P) -> Result { +pub fn readlink(path: &P) -> Result { let mut v = Vec::with_capacity(libc::PATH_MAX as usize); let res = path.with_nix_path(|cstr| { unsafe { libc::readlink(cstr.as_ptr(), v.as_mut_ptr() as *mut c_char, v.capacity() as size_t) } @@ -199,7 +199,7 @@ pub fn readlink<'a, P: ?Sized + NixPath>(path: &P) -> Result { } -pub fn readlinkat<'a, P: ?Sized + NixPath>(dirfd: RawFd, path: &P) -> Result { +pub fn readlinkat(dirfd: RawFd, path: &P) -> Result { let mut v = Vec::with_capacity(libc::PATH_MAX as usize); let res = path.with_nix_path(|cstr| { unsafe { libc::readlinkat(dirfd, cstr.as_ptr(), v.as_mut_ptr() as *mut c_char, v.capacity() as size_t) }