feat(img): add for_each_chunk to vim.image.Image class

Add `for_each_chunk()` for instances of `vim.img.Image`. This method streamlines chunked iteration of image bytes, which is important when working with ssh or tmux and a protocol that supports chunked image rendering such as `iterm2` or `kitty`.
This commit is contained in:
Chip Senkbeil 2024-11-30 14:50:08 -06:00
parent c50d7747a5
commit 2ad8324092
No known key found for this signature in database
GPG Key ID: 35EF1F8EC72A4131

View File

@ -33,6 +33,37 @@ function M:size()
return string.len(self.data or '')
end
---Iterates over the chunks of the image, invoking `f` per chunk.
---@param f fun(chunk:string, pos:integer, has_more:boolean)
---@param opts? {size?:integer}
function M:for_each_chunk(f, opts)
opts = opts or {}
-- Chunk size, defaulting to 4k
local chunk_size = opts.size or 4096
local data = self.data
if not data then
return
end
local pos = 1
local len = string.len(data)
while pos <= len do
-- Get our next chunk from [pos, pos + chunk_size)
local end_pos = pos + chunk_size - 1
local chunk = data:sub(pos, end_pos)
-- If we have a chunk available, invoke our callback
if string.len(chunk) > 0 then
local has_more = end_pos + 1 <= len
pcall(f, chunk, pos, has_more)
end
pos = end_pos + 1
end
end
---Displays the image within the terminal used by neovim.
---@param opts? vim.img.Opts
function M:show(opts)