Skip to content

Commit de9df00

Browse files
committed
Make the sliding window and output buffer one and the same as a string buffer.
1 parent 1d17494 commit de9df00

1 file changed

Lines changed: 16 additions & 25 deletions

File tree

arch/INFLATE.LUA

Lines changed: 16 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -52,31 +52,21 @@ function inflate(r, w, z)
5252

5353
-- op = output position
5454
-- kg = keep going (in a loop)
55-
-- sw = sliding window (32/64KB buffer)
56-
-- wp = window pointer
57-
-- o = output chunk buffer
58-
local op, kg, sw, wp, o = 0, 1, {}, 0, {}
59-
60-
---Flush all unwritten data to the output file
61-
function fl()
62-
if #o > 0 then
63-
w(table.concat(o))
64-
o = {}
65-
end
66-
end
55+
-- o = output buffer that also acts like a sliding window
56+
local op, kg, o = 0, 1, ""
6757

6858
---Appends a decoded byte to the output buffer and updates the sliding window history.
6959
---@param by number The byte value (0-255) to append.
7060
function ab(by)
7161
op = op + 1
62+
o = o .. string.char(by)
63+
if #o > Z + 4096 then -- Flush what has exceeded the sliding window
7264

73-
-- Add to output chunk
74-
o[#o + 1] = string.char(by)
75-
if #o >= 4096 then fl() end
76-
77-
-- Add to history window
78-
sw[wp] = by
79-
wp = (wp + 1) % Z
65+
-- c = cut
66+
local c = #o - Z
67+
w(o:sub(1, c))
68+
o = o:sub(c + 1)
69+
end
8070
end
8171

8272
---Constructs a canonical Huffman decoding table from a list of code lengths.
@@ -280,13 +270,12 @@ function inflate(r, w, z)
280270
print("!Distance", dv, Z, op) os.exit(1)
281271
end
282272

283-
-- Read from window history
273+
-- Read from output history
284274
for _ = 1, l do
285275

286-
-- hi = history
287-
local hi = (wp - dv) % Z
288-
289-
ab(sw[hi] or 0)
276+
-- c = character
277+
local c = o:sub(#o - dv + 1, #o - dv + 1)
278+
ab(c:byte())
290279
end
291280
end
292281
end
@@ -298,5 +287,7 @@ function inflate(r, w, z)
298287
if f == 1 then kg = 0 end
299288
end
300289

301-
fl()
290+
if #o > 0 then -- End of file, flush remaining output to disk
291+
w(o) o = ""
292+
end
302293
end

0 commit comments

Comments
 (0)