Lindenii Project Forge
Login

hare-ev

Temporary fork of hare-ev for... reasons
Commit info
ID
9f4703c1044da3967d2c4e0bd1cb0eb4422e5438
Author
Drew DeVault <sir@cmpwn.com>
Author date
Wed, 30 Nov 2022 13:25:20 +0100
Committer
Drew DeVault <sir@cmpwn.com>
Committer date
Wed, 30 Nov 2022 13:25:55 +0100
Actions
filemod: add EPOLLONESHOT

We might not always want this; in the future we might want to disable
this by default for things like accept(2), or let the user disable it to
reuse buffers and auto-queue new reads.
use errors;
use io;
use rt;

export type op = enum {
	NONE,
	READV,
	WRITEV,
};

export type file = struct {
	fd: io::file,
	ev: *loop,
	// Pending operation on this file object
	op: op,
	cb: nullable *void,

	// Operation-specific data
	vbuf: rt::iovec,
	union {
		vec: []rt::iovec,
	},
};

// Registers a file descriptor with an event loop.
export fn register(
	loop: *loop,
	fd: io::file,
) (*file | errors::error) = {
	const file = alloc(file {
		fd = fd,
		ev = loop,
		op = op::NONE,
		...
	});

	let ev = rt::epoll_event {
		events = 0,
		...
	};
	ev.data.ptr = file;
	match (rt::epoll_ctl(loop.fd, rt::EPOLL_CTL_ADD, fd, &ev)) {
	case void =>
		yield;
	case let err: rt::errno =>
		return errors::errno(err);
	};

	return file;
};

// Unregisters a file object with an event loop and frees resources associated
// with it. Does not close the underlying file descriptor.
export fn unregister(loop: *loop, file: *file) void = {
	// The only way that this could fail is in the event of a use-after-free
	// or if the user fucks around and constructs a custom [[file]] which
	// was never registered, so assert on error.
	rt::epoll_ctl(loop.fd, rt::EPOLL_CTL_DEL, file.fd, null)!;
	free(file);
};

// Modifies the epoll events for a given file. For internal use.
fn filemod(file: *file, events: u32) void = {
	let ev = rt::epoll_event {
		events = events,
		events = events | rt::EPOLLONESHOT,
		...
	};
	ev.data.ptr = file;
	// This can only fail under conditions associated with EPOLLEXCLUSIVE,
	// which we do not support.
	rt::epoll_ctl(file.ev.fd, rt::EPOLL_CTL_MOD, file.fd, &ev)!;
};