Changeset

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
parents 10979:5671d51df26c
children 10981:e6c1e92cc7a7
files spec/util_dbuffer_spec.lua util/dbuffer.lua
diffstat 2 files changed, 22 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/spec/util_dbuffer_spec.lua	Sun Jun 28 15:58:47 2020 +0200
+++ b/spec/util_dbuffer_spec.lua	Mon Jun 29 12:51:28 2020 +0100
@@ -21,6 +21,21 @@
 		end);
 	end);
 
+	describe(":read", function ()
+		it("supports optional bytes parameter", function ()
+			-- should return the frontmost chunk
+			local b = dbuffer.new();
+			assert.truthy(b:write("hello"));
+			assert.truthy(b:write(" "));
+			assert.truthy(b:write("world"));
+			assert.equal("h", b:read(1));
+
+			assert.equal("ello", b:read());
+			assert.equal(" ", b:read());
+			assert.equal("world", b:read());
+		end);
+	end);
+
 	describe(":discard", function ()
 		local b = dbuffer.new();
 		it("works", function ()
--- a/util/dbuffer.lua	Sun Jun 28 15:58:47 2020 +0200
+++ b/util/dbuffer.lua	Mon Jun 29 12:51:28 2020 +0100
@@ -24,6 +24,9 @@
 	if not chunk then return; end
 	local chunk_length = #chunk;
 	local remaining_chunk_length = chunk_length - consumed;
+	if not requested_bytes then
+		requested_bytes = remaining_chunk_length;
+	end
 	if remaining_chunk_length <= requested_bytes then
 		self.front_consumed = 0;
 		self._length = self._length - remaining_chunk_length;
@@ -41,12 +44,14 @@
 function dbuffer_methods:read(requested_bytes)
 	local chunks;
 
-	if requested_bytes > self._length then
+	if requested_bytes and requested_bytes > self._length then
 		return nil;
 	end
 
 	local chunk, read_bytes = self:read_chunk(requested_bytes);
-	if chunk then
+	if not requested_bytes then
+		return chunk;
+	elseif chunk then
 		requested_bytes = requested_bytes - read_bytes;
 		if requested_bytes == 0 then -- Already read everything we need
 			return chunk;