about summary refs log tree commit diff
path: root/fs.lua
diff options
context:
space:
mode:
Diffstat (limited to 'fs.lua')
-rw-r--r--fs.lua19
1 files changed, 14 insertions, 5 deletions
diff --git a/fs.lua b/fs.lua
index 2e7638f..153e611 100644
--- a/fs.lua
+++ b/fs.lua
@@ -1,5 +1,7 @@
 -- cqueue filesystem with luaposix
 -- TODO: closing files
+-- TODO: error handling. right now it *always* returns errno instead of
+-- throwing it, which may be what we want. code depends on this
 local unistd = require("posix.unistd")
 local cqueues = require("cqueues")
 local dkjson = require("dkjson")
@@ -85,8 +87,9 @@ function try_read(buffer, fd, max)
 	local data, _, errno = unistd.read(fd, max)
 
 	if not data then return nil, errno end
+	if #data == 0 then return nil end
 
-	table.insert(buffer, { data = data, index = 1})
+	table.insert(buffer, { data = data, index = 1 })
 
 	return #data
 end
@@ -96,7 +99,7 @@ function file.read(f, what)
 
 	if (type(what) == "number" and what > 0) then
 		while buffer_length(f.rbuf) < what do
-			if try_read(f.rbuf, f.pollfd, what - buffer_length(f.rbuf)) == 0 then
+			if not try_read(f.rbuf, f.pollfd, what - buffer_length(f.rbuf)) then
 				break
 			end
 		end
@@ -104,13 +107,14 @@ function file.read(f, what)
 		return buffer_get(f.rbuf, math.min(what, buffer_length(f.rbuf)))
 	elseif (type(what) == "number" and what < 0) then
 		while buffer_length(f.rbuf) == 0 do
-			if try_read(f.rbuf, f.pollfd, 0 - what) == 0 then return nil end
+			if not try_read(f.rbuf, f.pollfd, 0 - what) then return nil end
 		end
 		return buffer_get(f.rbuf, math.min(0 - what, buffer_length(f.rbuf)))
 	elseif what == "*l" or what == "*L" then
 		while not buffer_char_index(f.rbuf, "\n") do
 			-- TODO: constantize this
-			if try_read(f.rbuf, f.pollfd, 1024) == 0 then
+			local x = try_read(f.rbuf, f.pollfd, 1024)
+			if not x then
 				break
 			end
 		end
@@ -125,6 +129,7 @@ function file.read(f, what)
 			"\n",
 			(what == "*l" and "" or "\n")
 		)
+
 		return ret
 	else
 		-- TODO
@@ -140,7 +145,7 @@ function file.write(f, data)
 	while index <= #data do
 		cqueues.poll({ pollfd = f.pollfd, events = function () return "w" end })
 		local nb, _, errno = unistd.write(f.pollfd, string.sub(data, index))
-		if nb >= 0 then
+		if nb then
 			index = index + nb
 		else
 			return nil, errno -- TODO?
@@ -150,4 +155,8 @@ function file.write(f, data)
 	return f
 end
 
+function file.close(f)
+	cqueues.cancel(f.pollfd)
+end
+
 return file