Comparison

util/httpstream.lua @ 3496:9408d1e10e17

util.httpstream: Refactored and simplified code to improve readability.
author Waqas Hussain <waqas20@gmail.com>
date Fri, 17 Sep 2010 03:52:11 +0500
parent 3495:bd7699a6d536
child 3562:98f9dca3eb94
comparison
equal deleted inserted replaced
3495:bd7699a6d536 3496:9408d1e10e17
7 7
8 module("httpstream") 8 module("httpstream")
9 9
10 local function parser(data, success_cb) 10 local function parser(data, success_cb)
11 local function readline() 11 local function readline()
12 if not data then coroutine.yield("Unexpected EOF"); end 12 local pos = data:find("\r\n", nil, true);
13 local pos, line = (data:find("\r\n", nil, true)); 13 while not pos do
14 if not pos then 14 data = data..coroutine.yield();
15 local newdata = coroutine.yield(); 15 pos = data:find("\r\n", nil, true);
16 if not newdata then data = nil; coroutine.yield("Unexpected EOF"); end
17 data = data..newdata;
18 return readline();
19 end 16 end
20 line, data = data:sub(1, pos-1), data:sub(pos+2); 17 local r = data:sub(1, pos-1);
21 return line; 18 data = data:sub(pos+2);
19 return r;
22 end 20 end
23 local function readlength(n) 21 local function readlength(n)
24 if not data then coroutine.yield("Unexpected EOF"); end
25 while #data < n do 22 while #data < n do
26 local newdata = coroutine.yield(); 23 data = data..coroutine.yield();
27 if not newdata then data = nil; coroutine.yield("Unexpected EOF"); end
28 data = data..newdata;
29 end 24 end
30 local r = data:sub(1, n); 25 local r = data:sub(1, n);
31 data = data:sub(n + 1); 26 data = data:sub(n + 1);
32 return r; 27 return r;
33 end 28 end
66 61
67 function new(success_cb, error_cb) 62 function new(success_cb, error_cb)
68 local co = coroutine.create(parser); 63 local co = coroutine.create(parser);
69 return { 64 return {
70 feed = function(self, data) 65 feed = function(self, data)
66 if not data then
67 co = deadroutine;
68 return error_cb();
69 end
71 local success, result = coroutine.resume(co, data, success_cb); 70 local success, result = coroutine.resume(co, data, success_cb);
72 if result then 71 if result then
73 if result.method then 72 co = deadroutine;
74 success_cb(result); 73 return error_cb(result);
75 else -- error
76 error_cb(result);
77 co = deadroutine;
78 end
79 end 74 end
80 end; 75 end;
81 }; 76 };
82 end 77 end
83 78