Skip to content

Commit

Permalink
lib.binary_search: cache and reuse generated variants
Browse files Browse the repository at this point in the history
This is to avoid leaking ctypes and memory for generated code when using
binary_search.gen() repeatedly.
  • Loading branch information
eugeneia committed Oct 8, 2019
1 parent 3e73c2f commit daf7bdb
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/lib/binary_search.dasl
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ local function assemble (name, prototype, generator)
return ffi.cast(prototype, mcode)
end

local gencache = {} -- Cache for generated variants (reuse if possible.)
function gen(count, entry_type)
local function gen_binary_search(Dst)
if count == 1 then
Expand Down Expand Up @@ -80,9 +81,19 @@ function gen(count, entry_type)
| mov rax, rdi
| ret
end
return assemble("binary_search_"..count,
ffi.typeof("$*(*)($*, uint32_t)", entry_type, entry_type),
gen_binary_search)
-- Assemble binary search variant and cache it unless it has not been
-- previously generated.
if not gencache[entry_type] then
gencache[entry_type] = {}
end
if not gencache[entry_type][count] then
gencache[entry_type][count] =
assemble("binary_search_"..count,
ffi.typeof("$*(*)($*, uint32_t)", entry_type, entry_type),
gen_binary_search)
end
-- Return (now) cached routine.
return gencache[entry_type][count]
end

function selftest ()
Expand Down

0 comments on commit daf7bdb

Please sign in to comment.