use std::mem::zeroed;
use std::os::raw::{c_int, c_ulong, c_ushort};
static STDOUT_FILENO: c_int = 1;
#[cfg(any(target_os = "linux", target_os = "android"))]
static TIOCGWINSZ: c_ulong = 0x5413;
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
static TIOCGWINSZ: c_ulong = 0x40087468;
#[cfg(target_os = "solaris")]
static TIOCGWINSZ: c_ulong = 0x5468;
#[repr(C)]
struct winsize {
ws_row: c_ushort,
ws_col: c_ushort,
ws_xpixel: c_ushort,
ws_ypixel: c_ushort,
}
extern "C" {
fn ioctl(fd: c_int, request: c_ulong, ...) -> c_int;
}
unsafe fn get_dimensions() -> winsize {
let mut window: winsize = zeroed();
let result = ioctl(STDOUT_FILENO, TIOCGWINSZ, &mut window);
if result != -1 {
return window;
}
zeroed()
}
pub fn term_cols() -> Option<usize> {
let winsize { ws_col, .. } = unsafe { get_dimensions() };
if ws_col == 0 {
None
} else {
Some(ws_col as usize)
}
}
#[cfg(test)]
mod test {
#[test]
fn compare_with_stty() {
use std::process::{Command, Stdio};
let output = if cfg!(target_os = "linux") {
Command::new("stty")
.arg("size")
.arg("-F")
.arg("/dev/stderr")
.stderr(Stdio::inherit())
.output()
.unwrap()
} else {
Command::new("stty")
.arg("-f")
.arg("/dev/stderr")
.arg("size")
.stderr(Stdio::inherit())
.output()
.unwrap()
};
assert!(output.status.success());
let stdout = String::from_utf8(output.stdout).unwrap();
println!("stty: {}", stdout);
let mut data = stdout.split_whitespace();
let expected: usize = str::parse(data.nth(1).unwrap()).unwrap();
println!("cols: {}", expected);
if let Some(actual) = super::term_cols() {
assert_eq!(actual, expected);
} else if expected == 0 {
eprintln!("WARN: stty reports cols 0, skipping test");
} else {
panic!("term_cols() return None");
}
}
}