fast image operations
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
extern crate libc;
use std::fs::File;
use std::mem::MaybeUninit as MU;
use std::ops::Deref;
use std::os::fd::IntoRawFd;

use libc::*;

struct Fd(i32, bool);
impl Drop for Fd {
    fn drop(&mut self) {
        if self.1 {
            // SAFETY: #[allow(clippy::undocumented_unsafe_blocks)]
            unsafe { close(self.0) };
        }
    }
}
impl Fd {
    pub fn new(x: File) -> Self {
        Self(x.into_raw_fd(), true)
    }
}

impl From<i32> for Fd {
    fn from(value: i32) -> Self {
        Self(value, false)
    }
}

impl Deref for Fd {
    type Target = i32;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

pub fn size() -> Option<(u16, u16)> {
    // SAFETY: SYS
    unsafe {
        let mut size = MU::<winsize>::uninit();

        if ioctl(
            *File::open("/dev/tty")
                .map(Fd::new)
                .unwrap_or(Fd::from(STDIN_FILENO)),
            TIOCGWINSZ,
            size.as_mut_ptr(),
        ) != -1
        {
            let winsize { ws_col, ws_row, .. } = size.assume_init();
            return Some((ws_col as _, ws_row as _)).filter(|&(w, h)| w != 0 && h != 0);
        }
        tput("cols").and_then(|w| tput("lines").map(|h| (w, h)))
    }
}

pub fn tput(arg: &'static str) -> Option<u16> {
    let x = std::process::Command::new("tput").arg(arg).output().ok()?;
    String::from_utf8(x.stdout)
        .ok()
        .and_then(|x| x.parse::<u16>().ok())
}

#[test]
fn t() {
    println!("{:?}", size().unwrap());
}