Diff

net/server_event.lua @ 8781:53178b6ba589

net.server: Add watchfd, a simple API for watching file descriptors
author Kim Alvefur <zash@zash.se>
date Wed, 09 May 2018 16:15:40 +0200
parent 8751:469f78fe1c3e
child 8983:23f66f04e216
line wrap: on
line diff
--- a/net/server_event.lua	Mon May 07 22:10:29 2018 +0200
+++ b/net/server_event.lua	Wed May 09 16:15:40 2018 +0200
@@ -834,6 +834,34 @@
 	return event_handle;
 end
 
+local function watchfd(fd, onreadable, onwriteable)
+	local handle = {};
+	function handle:setflags(r,w)
+		if r ~= nil then
+			if r and not self.wantread then
+				self.wantread = base:addevent(fd, EV_READ, function ()
+					onreadable(self);
+				end);
+			elseif not r and self.wantread then
+				self.wantread:close();
+				self.wantread = nil;
+			end
+		end
+		if w ~= nil then
+			if w and not self.wantwrite then
+				self.wantwrite = base:addevent(fd, EV_WRITE, function ()
+					onwriteable(self);
+				end);
+			elseif not r and self.wantread then
+				self.wantwrite:close();
+				self.wantwrite = nil;
+			end
+		end
+	end
+	handle:setflags(onreadable, onwriteable);
+	return handle;
+end
+
 return {
 	cfg = cfg,
 	base = base,
@@ -850,6 +878,7 @@
 	get_backend = get_backend,
 	hook_signal = hook_signal,
 	add_task = add_task,
+	watchfd = watchfd,
 
 	__NAME = SCRIPT_NAME,
 	__DATE = LAST_MODIFIED,