Comparison

util/dbuffer.lua @ 10980:eaee72c7afbd

util.dbuffer: If no bytes parameter passed to read, return remainder of frontmost chunk
author Matthew Wild <mwild1@gmail.com>
date Mon, 29 Jun 2020 12:51:28 +0100
parent 10973:39991e40d1dc
child 11028:d7a403060946
comparison
equal deleted inserted replaced
10979:5671d51df26c 10980:eaee72c7afbd
22 function dbuffer_methods:read_chunk(requested_bytes) 22 function dbuffer_methods:read_chunk(requested_bytes)
23 local chunk, consumed = self.items:peek(), self.front_consumed; 23 local chunk, consumed = self.items:peek(), self.front_consumed;
24 if not chunk then return; end 24 if not chunk then return; end
25 local chunk_length = #chunk; 25 local chunk_length = #chunk;
26 local remaining_chunk_length = chunk_length - consumed; 26 local remaining_chunk_length = chunk_length - consumed;
27 if not requested_bytes then
28 requested_bytes = remaining_chunk_length;
29 end
27 if remaining_chunk_length <= requested_bytes then 30 if remaining_chunk_length <= requested_bytes then
28 self.front_consumed = 0; 31 self.front_consumed = 0;
29 self._length = self._length - remaining_chunk_length; 32 self._length = self._length - remaining_chunk_length;
30 self.items:pop(); 33 self.items:pop();
31 assert(#chunk:sub(consumed + 1, -1) == remaining_chunk_length); 34 assert(#chunk:sub(consumed + 1, -1) == remaining_chunk_length);
39 end 42 end
40 43
41 function dbuffer_methods:read(requested_bytes) 44 function dbuffer_methods:read(requested_bytes)
42 local chunks; 45 local chunks;
43 46
44 if requested_bytes > self._length then 47 if requested_bytes and requested_bytes > self._length then
45 return nil; 48 return nil;
46 end 49 end
47 50
48 local chunk, read_bytes = self:read_chunk(requested_bytes); 51 local chunk, read_bytes = self:read_chunk(requested_bytes);
49 if chunk then 52 if not requested_bytes then
53 return chunk;
54 elseif chunk then
50 requested_bytes = requested_bytes - read_bytes; 55 requested_bytes = requested_bytes - read_bytes;
51 if requested_bytes == 0 then -- Already read everything we need 56 if requested_bytes == 0 then -- Already read everything we need
52 return chunk; 57 return chunk;
53 end 58 end
54 chunks = {}; 59 chunks = {};