Skip to content

Instantly share code, notes, and snippets.

@lskbr
Last active March 30, 2022 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lskbr/acb8634d6c69c6de1cfce7cc7346b8e6 to your computer and use it in GitHub Desktop.
Save lskbr/acb8634d6c69c6de1cfce7cc7346b8e6 to your computer and use it in GitHub Desktop.
Inkey function
extern crate epoll;
extern crate libc;
extern crate termion;
use std::io;
use std::io::{Read, Write};
use std::os::unix::io::AsRawFd;
use termion::raw::IntoRawMode;
/// Waits for a key press timeout milisseconds
/// 0 - no wait
/// <0 - wait until a key is pressed
/// >0 wait for an event or timeout millisecods for an event.
fn inkey(timeout: i32) -> bool {
let input = io::stdin();
let _output = io::stdout().into_raw_mode().unwrap();
let fd = input.as_raw_fd();
let pool = epoll::create(true).unwrap();
let e = epoll::Event {
events: epoll::Events::EPOLLIN.bits(),
data: 0,
};
epoll::ctl(pool, epoll::ControlOptions::EPOLL_CTL_ADD, fd, e);
let mut v = [e];
let wresult = epoll::wait(pool, timeout, &mut v).unwrap();
unsafe {
libc::close(pool);
}
return wresult == 1;
}
fn main() {
let mut buffer: [u8; 1] = [0; 1];
let mut x = 0;
loop {
if inkey(0) {
let result = io::stdin().read(&mut buffer);
println!("{:?} {:?}", result, buffer);
if buffer[0] == 3 {
break;
}
}
if x % 1000 == 0 {
print!(".");
}
io::stdout().flush();
x += 1;
}
}
@alexzanderr
Copy link

fn inkey(timeout: i32) -> bool { this is so wrong. i can pass only seconds, i either wait 0 seconds or 1 second or N seconds, but i cant wait 10 milliseconds for example.

@lskbr
Copy link
Author

lskbr commented Mar 30, 2022

fn inkey(timeout: i32) -> bool { this is so wrong. i can pass only seconds, i either wait 0 seconds or 1 second or N seconds, but i cant wait 10 milliseconds for example.
Can you elaborate? You mean the parameter should be in seconds or you don't find any use to be in milliseconds?

@alexzanderr
Copy link

i mean that i cannot pass the timeout as milliseconds, if I call inkey(100) like this, it will wait for 100 seconds instead of 100 milliseconds

@alexzanderr
Copy link

the parameter should be in milliseconds and its not, i've tried it, just 10 as in inkey(10) and you will see that the function will wait 10 seconds instead of 10 milliseconds

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment