Skip to content

Commit

Permalink
optimize #[cfg] (#244)
Browse files Browse the repository at this point in the history
* optimize #[cfg]

* add doc

* fix offset

* fix fd
  • Loading branch information
loongs-zhang authored Feb 26, 2024
1 parent 0f8b724 commit a258e59
Show file tree
Hide file tree
Showing 21 changed files with 241 additions and 240 deletions.
11 changes: 7 additions & 4 deletions examples/uds.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
//! A example to show how to use UnixStream.
use local_sync::oneshot::channel;
use monoio::{
io::{AsyncReadRent, AsyncWriteRentExt},
net::{UnixListener, UnixStream},
#[cfg(unix)]
use {
local_sync::oneshot::channel,
monoio::{
io::{AsyncReadRent, AsyncWriteRentExt},
net::{UnixListener, UnixStream},
},
};

const ADDRESS: &str = "/tmp/monoio-unix-test.sock";
Expand Down
16 changes: 8 additions & 8 deletions monoio/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ use std::{io, marker::PhantomData};

#[cfg(all(target_os = "linux", feature = "iouring"))]
use crate::driver::IoUringDriver;
#[cfg(all(unix, feature = "legacy"))]
#[cfg(feature = "legacy")]
use crate::driver::LegacyDriver;
#[cfg(all(unix, any(feature = "legacy", feature = "iouring")))]
#[cfg(any(feature = "legacy", feature = "iouring"))]
use crate::utils::thread_id::gen_id;
use crate::{
driver::Driver,
Expand Down Expand Up @@ -80,14 +80,14 @@ macro_rules! direct_build {
direct_build!(IoUringDriver);
#[cfg(all(target_os = "linux", feature = "iouring"))]
direct_build!(TimeDriver<IoUringDriver>);
#[cfg(all(unix, feature = "legacy"))]
#[cfg(feature = "legacy")]
direct_build!(LegacyDriver);
#[cfg(all(unix, feature = "legacy"))]
#[cfg(feature = "legacy")]
direct_build!(TimeDriver<LegacyDriver>);

// ===== builder impl =====

#[cfg(all(unix, feature = "legacy"))]
#[cfg(feature = "legacy")]
impl Buildable for LegacyDriver {
fn build(this: RuntimeBuilder<Self>) -> io::Result<Runtime<LegacyDriver>> {
let thread_id = gen_id();
Expand Down Expand Up @@ -192,7 +192,7 @@ impl RuntimeBuilder<FusionDriver> {
}

/// Build the runtime.
#[cfg(all(unix, not(all(target_os = "linux", feature = "iouring"))))]
#[cfg(not(all(target_os = "linux", feature = "iouring")))]
pub fn build(self) -> io::Result<crate::FusionRuntime<LegacyDriver>> {
let builder = RuntimeBuilder::<LegacyDriver> {
entries: self.entries,
Expand Down Expand Up @@ -248,7 +248,7 @@ impl RuntimeBuilder<TimeDriver<FusionDriver>> {
}

/// Build the runtime.
#[cfg(all(unix, not(all(target_os = "linux", feature = "iouring"))))]
#[cfg(not(all(target_os = "linux", feature = "iouring")))]
pub fn build(self) -> io::Result<crate::FusionRuntime<TimeDriver<LegacyDriver>>> {
let builder = RuntimeBuilder::<TimeDriver<LegacyDriver>> {
entries: self.entries,
Expand Down Expand Up @@ -280,7 +280,7 @@ mod time_wrap {

#[cfg(all(target_os = "linux", feature = "iouring"))]
impl time_wrap::TimeWrapable for IoUringDriver {}
#[cfg(all(unix, feature = "legacy"))]
#[cfg(feature = "legacy")]
impl time_wrap::TimeWrapable for LegacyDriver {}
#[cfg(any(all(target_os = "linux", feature = "iouring"), feature = "legacy"))]
impl time_wrap::TimeWrapable for FusionDriver {}
Expand Down
13 changes: 1 addition & 12 deletions monoio/src/driver/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use std::{
};

#[allow(unreachable_pub)]
#[cfg(all(feature = "legacy", unix))]
#[cfg(feature = "legacy")]
pub use self::legacy::LegacyDriver;
#[cfg(feature = "legacy")]
use self::legacy::LegacyInner;
Expand Down Expand Up @@ -108,10 +108,7 @@ impl Inner {
not(all(target_os = "linux", feature = "iouring"))
))]
_ => {
#[cfg(unix)]
util::feature_panic();
#[cfg(windows)]
unimplemented!();
}
}
}
Expand All @@ -124,8 +121,6 @@ impl Inner {
cx: &mut Context<'_>,
) -> Poll<CompletionMeta> {
match self {
#[cfg(windows)]
_ => unimplemented!(),
#[cfg(all(target_os = "linux", feature = "iouring"))]
Inner::Uring(this) => UringInner::poll_op(this, index, cx),
#[cfg(feature = "legacy")]
Expand All @@ -147,8 +142,6 @@ impl Inner {
cx: &mut Context<'_>,
) -> Poll<CompletionMeta> {
match self {
#[cfg(windows)]
_ => unimplemented!(),
#[cfg(all(target_os = "linux", feature = "iouring"))]
Inner::Uring(this) => UringInner::poll_legacy_op(this, data, cx),
#[cfg(feature = "legacy")]
Expand All @@ -166,8 +159,6 @@ impl Inner {
#[allow(unused)]
fn drop_op<T: 'static>(&self, index: usize, data: &mut Option<T>) {
match self {
#[cfg(windows)]
_ => unimplemented!(),
#[cfg(all(target_os = "linux", feature = "iouring"))]
Inner::Uring(this) => UringInner::drop_op(this, index, data),
#[cfg(feature = "legacy")]
Expand All @@ -185,8 +176,6 @@ impl Inner {
#[allow(unused)]
pub(super) unsafe fn cancel_op(&self, op_canceller: &op::OpCanceller) {
match self {
#[cfg(windows)]
_ => unimplemented!(),
#[cfg(all(target_os = "linux", feature = "iouring"))]
Inner::Uring(this) => UringInner::cancel_op(this, op_canceller.index),
#[cfg(feature = "legacy")]
Expand Down
13 changes: 4 additions & 9 deletions monoio/src/driver/op/connect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,17 +116,16 @@ impl OpAble for Connect {
}
}

#[cfg(unix)]
pub(crate) struct ConnectUnix {
/// Holds a strong ref to the FD, preventing the file from being closed
/// while the operation is in-flight.
pub(crate) fd: SharedFd,
#[cfg(unix)]
socket_addr: Box<(libc::sockaddr_un, libc::socklen_t)>,
}

#[cfg(unix)]
impl Op<ConnectUnix> {
#[cfg(unix)]

/// Submit a request to connect.
pub(crate) fn connect_unix(
socket: SharedFd,
Expand All @@ -140,6 +139,7 @@ impl Op<ConnectUnix> {
}
}

#[cfg(unix)]
impl OpAble for ConnectUnix {
#[cfg(all(target_os = "linux", feature = "iouring"))]
fn uring_op(&mut self) -> io_uring::squeue::Entry {
Expand All @@ -157,7 +157,7 @@ impl OpAble for ConnectUnix {
None
}

#[cfg(all(any(feature = "legacy", feature = "poll-io"), unix))]
#[cfg(any(feature = "legacy", feature = "poll-io"))]
fn legacy_call(&mut self) -> io::Result<u32> {
match crate::syscall_u32!(connect(
self.fd.raw_fd(),
Expand All @@ -168,11 +168,6 @@ impl OpAble for ConnectUnix {
_ => Ok(self.fd.raw_fd() as u32),
}
}

#[cfg(all(any(feature = "legacy", feature = "poll-io"), windows))]
fn legacy_call(&mut self) -> io::Result<u32> {
unimplemented!()
}
}

/// A type with the same memory layout as `libc::sockaddr`. Used in converting Rust level
Expand Down
48 changes: 31 additions & 17 deletions monoio/src/driver/op/read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@ use std::io;

#[cfg(all(target_os = "linux", feature = "iouring"))]
use io_uring::{opcode, types};
#[cfg(all(unix, any(feature = "legacy", feature = "poll-io")))]
use {crate::syscall_u32, std::os::unix::prelude::AsRawFd};
#[cfg(all(windows, any(feature = "legacy", feature = "poll-io")))]
use {
crate::syscall,
std::ffi::c_void,
std::os::windows::io::AsRawSocket,
windows_sys::Win32::Networking::WinSock::{recv, WSAGetLastError, WSARecv, SOCKET_ERROR},
windows_sys::Win32::{
Foundation::TRUE,
Networking::WinSock::{WSAGetLastError, WSARecv, SOCKET_ERROR},
Storage::FileSystem::{ReadFile, SetFilePointer, FILE_CURRENT, INVALID_SET_FILE_POINTER},
},
};
#[cfg(all(unix, any(feature = "legacy", feature = "poll-io")))]
use {crate::syscall_u32, std::os::unix::prelude::AsRawFd};

use super::{super::shared_fd::SharedFd, Op, OpAble};
#[cfg(any(feature = "legacy", feature = "poll-io"))]
Expand Down Expand Up @@ -102,20 +104,32 @@ impl<T: IoBufMut> OpAble for Read<T> {

#[cfg(all(any(feature = "legacy", feature = "poll-io"), windows))]
fn legacy_call(&mut self) -> io::Result<u32> {
let fd = self.fd.as_raw_socket();
let fd = self.fd.raw_handle() as _;
let seek_offset = libc::off_t::try_from(self.offset)
.map_err(|_| io::Error::new(io::ErrorKind::Other, "offset too big"))?;
syscall!(
recv(
fd as _,
(self.buf.write_ptr().cast::<c_void>() as usize + seek_offset as usize)
as *mut c_void as *mut _,
self.buf.bytes_total() as i32 - seek_offset,
0
),
PartialOrd::ge,
0
)
let mut bytes_read = 0;
let ret = unsafe {
// see https://learn.microsoft.com/zh-cn/windows/win32/api/fileapi/nf-fileapi-setfilepointer
if seek_offset != 0 {
let r = SetFilePointer(fd, seek_offset, std::ptr::null_mut(), FILE_CURRENT);
if INVALID_SET_FILE_POINTER == r {
return Err(io::Error::last_os_error());
}
}
// see https://learn.microsoft.com/zh-cn/windows/win32/api/fileapi/nf-fileapi-readfile
ReadFile(
fd,
self.buf.write_ptr().cast::<c_void>(),
self.buf.bytes_total() as u32,
&mut bytes_read,
std::ptr::null_mut(),
)
};
if TRUE == ret {
Ok(bytes_read)
} else {
Err(io::Error::last_os_error())
}
}
}

Expand Down
45 changes: 28 additions & 17 deletions monoio/src/driver/op/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@ use std::io;
#[cfg(all(target_os = "linux", feature = "iouring"))]
use io_uring::{opcode, types};
#[cfg(all(windows, any(feature = "legacy", feature = "poll-io")))]
use {
crate::syscall,
std::ffi::c_void,
std::os::windows::io::AsRawSocket,
windows_sys::Win32::Networking::WinSock::{send, WSAGetLastError, WSASend, SOCKET_ERROR},
use windows_sys::Win32::{
Foundation::TRUE,
Networking::WinSock::{WSAGetLastError, WSASend, SOCKET_ERROR},
Storage::FileSystem::{SetFilePointer, WriteFile, FILE_CURRENT, INVALID_SET_FILE_POINTER},
};
#[cfg(all(unix, any(feature = "legacy", feature = "poll-io")))]
use {crate::syscall_u32, std::os::unix::prelude::AsRawFd};
Expand Down Expand Up @@ -89,20 +88,32 @@ impl<T: IoBuf> OpAble for Write<T> {

#[cfg(all(any(feature = "legacy", feature = "poll-io"), windows))]
fn legacy_call(&mut self) -> io::Result<u32> {
let fd = self.fd.as_raw_socket();
let fd = self.fd.raw_handle() as _;
let seek_offset = libc::off_t::try_from(self.offset)
.map_err(|_| io::Error::new(io::ErrorKind::Other, "offset too big"))?;
syscall!(
send(
fd as _,
(self.buf.read_ptr().cast::<c_void>() as usize + seek_offset as usize)
as *mut c_void as *mut _,
self.buf.bytes_init() as i32 - seek_offset,
0
),
PartialOrd::ge,
0
)
let mut bytes_write = 0;
let ret = unsafe {
// see https://learn.microsoft.com/zh-cn/windows/win32/api/fileapi/nf-fileapi-setfilepointer
if seek_offset != 0 {
let r = SetFilePointer(fd, seek_offset, std::ptr::null_mut(), FILE_CURRENT);
if INVALID_SET_FILE_POINTER == r {
return Err(io::Error::last_os_error());
}
}
// see https://learn.microsoft.com/zh-cn/windows/win32/api/fileapi/nf-fileapi-writefile
WriteFile(
fd,
self.buf.read_ptr(),
self.buf.bytes_init() as u32,
&mut bytes_write,
std::ptr::null_mut(),
)
};
if TRUE == ret {
Ok(bytes_write)
} else {
Err(io::Error::last_os_error())
}
}
}

Expand Down
5 changes: 3 additions & 2 deletions monoio/src/driver/poll.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{io, os::fd::AsRawFd, task::Context, time::Duration};
use std::{io, task::Context, time::Duration};

use super::{ready::Direction, scheduled_io::ScheduledIo};
use crate::{driver::op::CompletionMeta, utils::slab::Slab};
Expand Down Expand Up @@ -100,7 +100,8 @@ impl Poll {
}
}

impl AsRawFd for Poll {
#[cfg(unix)]
impl std::os::fd::AsRawFd for Poll {
#[inline]
fn as_raw_fd(&self) -> std::os::fd::RawFd {
self.poll.as_raw_fd()
Expand Down
14 changes: 7 additions & 7 deletions monoio/src/driver/shared_fd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ impl SharedFd {
}

#[cfg(windows)]
pub(crate) fn new(fd: RawSocket) -> io::Result<SharedFd> {
pub(crate) fn new<const FORCE_LEGACY: bool>(fd: RawSocket) -> io::Result<SharedFd> {
const RW_INTERESTS: mio::Interest = mio::Interest::READABLE.add(mio::Interest::WRITABLE);

let mut fd = RawFd::new(fd);
Expand Down Expand Up @@ -272,7 +272,7 @@ impl SharedFd {
let state = CURRENT.with(|inner| match inner {
#[cfg(all(target_os = "linux", feature = "iouring"))]
super::Inner::Uring(_) => State::Uring(UringState::Init),
#[cfg(all(unix, feature = "legacy"))]
#[cfg(feature = "legacy")]
super::Inner::Legacy(_) => State::Legacy(None),
#[cfg(all(
not(feature = "legacy"),
Expand Down Expand Up @@ -320,7 +320,7 @@ impl SharedFd {

#[cfg(windows)]
pub(crate) fn raw_handle(&self) -> RawHandle {
unimplemented!()
self.inner.fd.socket as _
}

#[cfg(unix)]
Expand All @@ -339,10 +339,10 @@ impl SharedFd {
let mut state = unsafe { MaybeUninit::uninit().assume_init() };
std::mem::swap(&mut inner_skip_drop.state, &mut state);

#[cfg(all(unix, feature = "legacy"))]
#[cfg(feature = "legacy")]
let state = unsafe { &*state.get() };

#[cfg(all(unix, feature = "legacy"))]
#[cfg(feature = "legacy")]
#[allow(irrefutable_let_patterns)]
if let State::Legacy(idx) = state {
if CURRENT.is_set() {
Expand Down Expand Up @@ -564,7 +564,7 @@ fn drop_legacy(mut fd: RawFd, idx: Option<usize>) {
}
#[cfg(all(unix, feature = "legacy"))]
let _ = unsafe { std::fs::File::from_raw_fd(fd) };
#[cfg(windows)]
#[cfg(all(windows, feature = "legacy"))]
let _ = unsafe { OwnedSocket::from_raw_socket(fd.socket) };
}

Expand All @@ -573,7 +573,7 @@ fn drop_uring_legacy(fd: RawFd, idx: Option<usize>) {
if CURRENT.is_set() {
CURRENT.with(|inner| {
match inner {
#[cfg(all(unix, feature = "legacy"))]
#[cfg(feature = "legacy")]
super::Inner::Legacy(_) => {
unreachable!("close uring fd with legacy runtime")
}
Expand Down
4 changes: 1 addition & 3 deletions monoio/src/driver/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@ pub(super) fn cstr(p: &Path) -> io::Result<CString> {
Ok(CString::new(p.as_os_str().as_bytes())?)
}
#[cfg(windows)]
{
unimplemented!()
}
Ok(CString::new(p.as_os_str().as_encoded_bytes())?)
}

// Convert Duration to Timespec
Expand Down
Loading

0 comments on commit a258e59

Please sign in to comment.