Skip to content

Commit a31dfad

Browse files
authored
fix: info size suffix and formatting (#2492)
- Now there is a whitespace between value and unit. - Now values >= 1024 YiB are shown in YiB instead of B. - To reuse same code a new local function was added: round().
1 parent 83b6995 commit a31dfad

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

lua/nvim-tree/utils.lua

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -280,19 +280,38 @@ function M.move_missing_val(src, src_path, src_pos, dst, dst_path, dst_pos, remo
280280
end
281281
end
282282

283+
local function round(value)
284+
-- Amount of digits to round to after floating point.
285+
local digits = 2
286+
local round_number = 10 ^ digits
287+
return math.floor((value * round_number) + 0.5) / round_number
288+
end
289+
283290
function M.format_bytes(bytes)
284291
local units = { "B", "K", "M", "G", "T", "P", "E", "Z", "Y" }
292+
local i = "i" -- bInary
285293

286294
bytes = math.max(bytes, 0)
287295
local pow = math.floor((bytes and math.log(bytes) or 0) / math.log(1024))
288296
pow = math.min(pow, #units)
289297

290-
local value = bytes / (1024 ^ pow)
291-
value = math.floor((value * 10) + 0.5) / 10
298+
local value = round(bytes / (1024 ^ pow))
292299

293300
pow = pow + 1
294301

295-
return (units[pow] == nil) and (bytes .. units[1]) or (value .. units[pow] .. "i" .. units[1])
302+
-- units[pow] == nil when size == 0 B or size >= 1024 YiB
303+
if units[pow] == nil or pow == 1 then
304+
if bytes < 1024 then
305+
return bytes .. " " .. units[1]
306+
else
307+
-- Use the biggest adopted multiple of 2 instead of bytes.
308+
value = round(bytes / (1024 ^ (#units - 1)))
309+
-- For big numbers decimal part is not useful.
310+
return string.format("%.0f %s%s%s", value, units[#units], i, units[1])
311+
end
312+
else
313+
return value .. " " .. units[pow] .. i .. units[1]
314+
end
296315
end
297316

298317
function M.key_by(tbl, key)

0 commit comments

Comments
 (0)