draw

source of pkg::alloy::window::posix

1// The C library's functions the Linux window uses, apart from the2// window's own names.34import std::ffi;5import std::option;67pub extern memfd_create(name: c_string, flags: u32) -> i32;8pub extern ftruncate(fd: i32, length: i64) -> i32;9pub extern mmap(10    address: c_pointer,11    length: c_size,12    protection: i32,13    flags: i32,14    fd: i32,15    offset: i6416) -> c_pointer;17pub extern munmap(address: c_pointer, length: c_size) -> i32;18extern close(fd: i32) -> i32;19pub extern poll(fds: c_pointer, count: u64, timeout: i32) -> i32;2021// A pollfd waiting for the descriptor to be readable (POLLIN); poll22// passes over one with none.23pub fn readable(fd: Option<i32>) -> u64 {24    const polled: i32 = if (fd is ::Some |f|) f else -1;25    return polled as u32 to u64 | (1 to u64 << 32);26}2728// Whether poll found the pollfd's descriptor readable, or closed.29pub fn ready(pollfd: u64) -> bool => pollfd >> 48 != 0;3031extern read(fd: i32, buffer: c_pointer, count: c_size) -> i64;32extern write(fd: i32, buffer: c_pointer, count: c_size) -> i64;33extern eventfd(initial: u32, flags: i32) -> i32;34extern pipe2(fds: c_pointer, flags: i32) -> i32;35extern fcntl(fd: i32, command: i32, argument: i32) -> i32;3637pub fn close_fd(fd: i32) {38    close(fd);39}4041// An eventfd not inherited and never blocking.42pub fn open_eventfd() -> Option<i32> {43    // EFD_CLOEXEC | EFD_NONBLOCK44    const fd = eventfd(0, 0x80800);45    return if (fd >= 0) ::Some(fd) else ::None;46}4748// Adds one to the eventfd's count, making it readable.49pub fn wake_eventfd(fd: i32) {50    var one: u64 = 1;51    write(fd, c_pointer::from(&var one), 8);52}5354// A pipe not inherited, its reading end never blocking: [read, write],55// or none.56pub fn open_pipe() -> Option<[i32 : 2]> {57    var fds: [i32 : 2] = [-1, -1];58    if (pipe2(c_pointer::of(&fds[..]), 0x80000) != 0) {59        return ::None;60    }61    // O_NONBLOCK on the reading end62    fcntl(fds[0], 4, 0x800);63    return ::Some(fds);64}6566// Writes all the bytes, as far as the reader takes them.67pub fn write_all(fd: i32, bytes: &[u8]) {68    var at: u64 = 0;69    while (at < bytes.length()) {70        const written = write(fd, c_pointer::of(&bytes[at..]), (bytes.length() - at) to c_size);71        if (written <= 0) {72            return;73        }74        at += written to u64;75    }76}7778// Reads what is there into the buffer: how many bytes, 0 at the end, -179// when none are there yet (or on an error).80pub fn read_some(fd: i32, buffer: &var [u8]) -> i64 {81    return read(fd, c_pointer::of(&buffer), buffer.length() to c_size);82}8384// Takes the eventfd's count, making it unreadable.85pub fn drain_eventfd(fd: i32) {86    var count: u64 = 0;87    read(fd, c_pointer::from(&var count), 8);88}