From 800393067cf97b0f20eb0a3e61506cc6ffc76128 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Cas=C3=ADa?= Date: Sun, 13 Oct 2024 10:58:55 +0200 Subject: [PATCH] refactor: improve buffering in write_file function (#160) Just a better implementation for writing to file in buffers. --- lua/neotest-java/util/write_file.lua | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/lua/neotest-java/util/write_file.lua b/lua/neotest-java/util/write_file.lua index a41732a..ba2aff2 100644 --- a/lua/neotest-java/util/write_file.lua +++ b/lua/neotest-java/util/write_file.lua @@ -1,6 +1,9 @@ local nio = require("nio") local compatible_path = require("neotest-java.util.compatible_path") local Path = require("plenary.path") +local logger = require("neotest-java.logger") + +local BUFFER_SIZE = 500 ---@param filepath string ---@param content string @@ -10,17 +13,16 @@ local function write_file(filepath, content) -- create parent directories if they don't exist nio.fn.mkdir(Path:new(_filepath):parent():absolute(), "p") + logger.debug("writing to file: ", _filepath) + local file = io.open(_filepath, "w") or error("Could not open file for writing: " .. _filepath) - local buffer = "" - for i = 1, #content do - buffer = buffer .. content:sub(i, i) - if i % 500 == 0 then - file:write(buffer) - buffer = "" - end + local pointer = 1 + for i = BUFFER_SIZE, #content, BUFFER_SIZE do + file:write(content:sub(pointer, i)) + pointer = i + 1 end - if buffer ~= "" then - file:write(buffer) + if pointer <= #content then + file:write(content:sub(pointer)) end file:close()