Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use rustix instead of libc #878

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ keywords = ["event", "color", "cli", "input", "terminal"]
exclude = ["target", "Cargo.lock"]
readme = "README.md"
edition = "2021"
rust-version = "1.58.0"
rust-version = "1.63.0"
categories = ["command-line-interface", "command-line-utilities"]

[lib]
Expand Down Expand Up @@ -44,6 +44,7 @@ events = [
"dep:signal-hook-mio",
] # Enables reading input/events from the system.
serde = ["dep:serde", "bitflags/serde"] # Enables 'serde' for various types.
rustix = ["dep:rustix"] # On Unix, enables using rustix as the underlying interface.

#
# Shared dependencies
Expand Down Expand Up @@ -71,13 +72,14 @@ crossterm_winapi = { version = "0.9.1", optional = true }
# UNIX dependencies
#
[target.'cfg(unix)'.dependencies]
libc = "0.2"
signal-hook = { version = "0.3.17", optional = true }
filedescriptor = { version = "0.8", optional = true }
libc = { version = "0.2", default-features = false }
mio = { version = "0.8", features = ["os-poll"], optional = true }
signal-hook-mio = { version = "0.2.3", features = [
"support-v0_8",
], optional = true }
rustix = { version = "0.38.0", default-features = false, features = ["std", "stdio", "termios"], optional = true }

#
# Dev dependencies (examples, ...)
Expand Down
1 change: 0 additions & 1 deletion src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1150,7 +1150,6 @@ pub(crate) enum InternalEvent {
#[cfg(test)]
mod tests {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

use super::*;
use KeyCode::*;
Expand Down
2 changes: 0 additions & 2 deletions src/event/sys/unix/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -863,8 +863,6 @@ pub(crate) fn parse_utf8_char(buffer: &[u8]) -> io::Result<Option<char>> {

#[cfg(test)]
mod tests {
use crate::event::{KeyEventState, KeyModifiers, MouseButton, MouseEvent};

use super::*;

#[test]
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,8 @@ pub mod tty;
pub mod ansi_support;
mod command;
pub(crate) mod macros;
#[cfg(unix)]
mod sys;

#[cfg(all(windows, not(feature = "windows")))]
compile_error!("Compiling on Windows with \"windows\" feature disabled. Feature \"windows\" should only be disabled when project will never be compiled on Windows.");
Expand Down
5 changes: 1 addition & 4 deletions src/style/types/color.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
use std::{
convert::{AsRef, TryFrom},
str::FromStr,
};
use std::str::FromStr;

#[cfg(feature = "serde")]
use std::fmt;
Expand Down
12 changes: 12 additions & 0 deletions src/sys.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//! Interface to the C system library.
//!
//! This uses either rustix or libc.

#[cfg(feature = "rustix")]
pub(crate) use rustix::*;

#[cfg(not(feature = "rustix"))]
mod minirustix;

#[cfg(not(feature = "rustix"))]
pub(crate) use minirustix::*;
94 changes: 94 additions & 0 deletions src/sys/minirustix.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
//! Emulates rustix's interface using libc.

pub(crate) mod io {
use super::cvt;
use std::io::Result;
use std::os::unix::io::{AsFd, AsRawFd};

pub(crate) fn read(f: impl AsFd, buf: &mut [u8]) -> Result<usize> {
unsafe {
cvt(libc::read(
f.as_fd().as_raw_fd(),
buf.as_mut_ptr().cast(),
buf.len() as _,
) as i32)
.map(|x| x as usize)
}
}
}

pub(crate) mod stdio {
use std::os::unix::io::BorrowedFd;

pub(crate) fn stdin() -> BorrowedFd<'static> {
unsafe { BorrowedFd::borrow_raw(libc::STDIN_FILENO) }
}

pub(crate) fn stdout() -> BorrowedFd<'static> {
unsafe { BorrowedFd::borrow_raw(libc::STDOUT_FILENO) }
}
}

pub(crate) mod termios {
use super::cvt;
use std::io::Result;
use std::mem::MaybeUninit;
use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd};

pub(crate) type Termios = libc::termios;
pub(crate) type Winsize = libc::winsize;

#[repr(u32)]
pub(crate) enum OptionalActions {
Now = 0,
// All others are unused by crossterm.
}

pub(crate) fn isatty(fd: BorrowedFd<'_>) -> bool {
unsafe { libc::isatty(fd.as_raw_fd()) != 0 }
}

pub(crate) fn tcgetwinsize(fd: impl AsFd) -> Result<Winsize> {
unsafe {
let mut buf = MaybeUninit::<Winsize>::uninit();
cvt(libc::ioctl(
fd.as_fd().as_raw_fd(),
libc::TIOCGWINSZ,
buf.as_mut_ptr(),
))?;
Ok(buf.assume_init())
}
}

pub(crate) fn tcgetattr(fd: impl AsFd) -> Result<Termios> {
unsafe {
let mut buf = MaybeUninit::<Termios>::uninit();
cvt(libc::tcgetattr(fd.as_fd().as_raw_fd(), buf.as_mut_ptr()))?;
Ok(buf.assume_init())
}
}

pub(crate) fn tcsetattr(
fd: impl AsFd,
optional: OptionalActions,
termios: &Termios,
) -> Result<()> {
unsafe {
cvt(libc::tcsetattr(
fd.as_fd().as_raw_fd(),
optional as _,
termios,
))?;

Ok(())
}
}
}

fn cvt(res: i32) -> std::io::Result<i32> {
if res < 0 {
Err(std::io::Error::last_os_error())
} else {
Ok(res)
}
}
78 changes: 26 additions & 52 deletions src/terminal/sys/file_descriptor.rs
Original file line number Diff line number Diff line change
@@ -1,65 +1,42 @@
use std::{
fs, io,
os::unix::{
io::{IntoRawFd, RawFd},
prelude::AsRawFd,
},
};

use libc::size_t;
use crate::sys;
use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, OwnedFd, RawFd};
use std::{fs, io};

/// A file descriptor wrapper.
///
/// It allows to retrieve raw file descriptor, write to the file descriptor and
/// mainly it closes the file descriptor once dropped.
#[derive(Debug)]
pub struct FileDesc {
fd: RawFd,
close_on_drop: bool,
pub enum FileDesc {
Owned(OwnedFd),
Static(BorrowedFd<'static>),
}

impl FileDesc {
/// Constructs a new `FileDesc` with the given `RawFd`.
///
/// # Arguments
///
/// * `fd` - raw file descriptor
/// * `close_on_drop` - specify if the raw file descriptor should be closed once the `FileDesc` is dropped
pub fn new(fd: RawFd, close_on_drop: bool) -> FileDesc {
FileDesc { fd, close_on_drop }
}

pub fn read(&self, buffer: &mut [u8]) -> io::Result<usize> {
let result = unsafe {
libc::read(
self.fd,
buffer.as_mut_ptr() as *mut libc::c_void,
buffer.len() as size_t,
)
let fd = match self {
Self::Owned(fd) => fd.as_fd(),
Self::Static(fd) => fd.as_fd(),
};

if result < 0 {
Err(io::Error::last_os_error())
} else {
Ok(result as usize)
}
let result = sys::io::read(fd, buffer)?;
Ok(result)
}

/// Returns the underlying file descriptor.
pub fn raw_fd(&self) -> RawFd {
self.fd
match self {
Self::Owned(fd) => fd.as_raw_fd(),
Self::Static(fd) => fd.as_raw_fd(),
}
}
}

impl Drop for FileDesc {
fn drop(&mut self) {
if self.close_on_drop {
// Note that errors are ignored when closing a file descriptor. The
// reason for this is that if an error occurs we don't actually know if
// the file descriptor was closed or not, and if we retried (for
// something like EINTR), we might close another valid file descriptor
// opened after we closed ours.
let _ = unsafe { libc::close(self.fd) };
impl AsFd for FileDesc {
fn as_fd(&self) -> BorrowedFd<'_> {
match self {
Self::Owned(fd) => fd.as_fd(),
Self::Static(fd) => fd.as_fd(),
}
}
}
Expand All @@ -72,18 +49,15 @@ impl AsRawFd for FileDesc {

/// Creates a file descriptor pointing to the standard input or `/dev/tty`.
pub fn tty_fd() -> io::Result<FileDesc> {
let (fd, close_on_drop) = if unsafe { libc::isatty(libc::STDIN_FILENO) == 1 } {
(libc::STDIN_FILENO, false)
if sys::termios::isatty(sys::stdio::stdin()) {
Ok(FileDesc::Static(sys::stdio::stdin()))
} else {
(
Ok(FileDesc::Owned(
fs::OpenOptions::new()
.read(true)
.write(true)
.open("/dev/tty")?
.into_raw_fd(),
true,
)
};

Ok(FileDesc::new(fd, close_on_drop))
.into(),
))
}
}
Loading