nixio: +performance

This commit is contained in:
Steven Barth 2009-02-14 14:39:12 +00:00
parent aa0cee169f
commit 157cc2b896

View file

@ -12,6 +12,7 @@ http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local table = require "table"
local nixio = require "nixio"
local setmetatable, assert = setmetatable, assert
@ -20,30 +21,53 @@ module "nixio.util"
local BUFFERSIZE = 8096
local socket = nixio.socket_meta
function socket.readall(self, len)
local block, code, msg = self:recv(len)
if not block then
return "", code, msg, len
end
local data, total = {block}, #block
while len > total do
block, code, msg = self:recv(len - total)
if not block then
return data, code, msg, len - #data
end
data[#data+1], total = block, total + #block
end
return (#data > 1 and table.concat(data) or data[1]), nil, nil, 0
end
function socket.sendall(self, data)
local total, block = 0
local sent, code, msg = self:send(data)
if not sent then
return sent, code, msg, data
return total, code, msg, data
end
while sent < #data do
data = data:sub(sent + 1)
sent, code, msg = self:send(data)
while sent < #data do
block, total = data:sub(sent + 1), total + sent
sent, code, msg = self:send(block)
if not sent then
return sent, code, msg, data
return total, code, msg, block
end
end
return true
return total + sent, nil, nil, ""
end
function socket.linesource(self, limit)
limit = limit or BUFFERSIZE
local buffer = ""
return function(flush)
local line, endp, _
local bpos, line, endp, _ = 0
if flush then
line = buffer
@ -52,16 +76,17 @@ function socket.linesource(self, limit)
end
while not line do
_, endp, line = buffer:find("^(.-)\r?\n")
_, endp, line = buffer:find("^(.-)\r?\n", bpos + 1)
if line then
buffer = buffer:sub(endp+1)
bpos = endp
return line
elseif #buffer < limit then
local newblock, code = self:recv(limit - #buffer)
elseif #buffer < limit + bpos then
local newblock, code = self:recv(limit + bpos - #buffer)
if not newblock then
return nil, code
end
buffer = buffer .. newblock
buffer = buffer:sub(bpos + 1) .. newblock
bpos = 0
else
return nil, 0
end