Skip to content

Commit

Permalink
cache.lua: add type anotations for function and cache
Browse files Browse the repository at this point in the history
  • Loading branch information
CogentRedTester committed Feb 3, 2025
1 parent 1da3c49 commit 7013ccd
Showing 1 changed file with 26 additions and 5 deletions.
31 changes: 26 additions & 5 deletions modules/cache.lua
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ local utils = require 'mp.utils'
local g = require 'modules.globals'
local fb_utils = require 'modules.utils'

---Returns an array of keys in a table.
---@generic T
---@param t table<T,any>
---@return T[]
local function get_keys(t)
local keys = {}
for key in pairs(t) do
Expand All @@ -17,6 +21,15 @@ local function get_keys(t)
return keys
end

---@class CacheRef
---@field directory string
---@field ref State?

---@class Cache
---@field traversal_stack CacheRef[]
---@field history CacheRef[]
---@field cache table<string,State>
---@field dangling_refs Set<string>
local cache = {
cache = setmetatable({}, {__mode = 'kv'}),
traversal_stack = {},
Expand All @@ -41,16 +54,18 @@ function cache:print_debug_info()
msg.debug(utils.to_string(fb_utils.list.map(self.history, function(ref) return ref.directory end)))
end

function cache:replace_dangling_refs(directory, ref)
---@param directory string
---@param state State
function cache:replace_dangling_refs(directory, state)
for _, v in ipairs(self.traversal_stack) do
if v.directory == directory then
v.ref = ref
v.ref = state
self.dangling_refs[directory] = nil
end
end
for _, v in ipairs(self.history) do
if v.directory == directory then
v.ref = ref
v.ref = state
self.dangling_refs[directory] = nil
end
end
Expand All @@ -71,8 +86,10 @@ function cache:add_current_state()
end
end

-- Creates a reference to the cache of a particular directory to prevent it
-- from being garbage collected.
---Creates a reference to the cache of a particular directory to prevent it
---from being garbage collected.
---@param directory string
---@return CacheRef
function cache:get_cache_ref(directory)
return {
directory = directory,
Expand All @@ -91,10 +108,14 @@ function cache:append_history()
if (history_size + 1) > 100 then table.remove(self.history, 1) end
end

---@param directory string
---@return boolean
function cache:in_cache(directory)
return self.cache[directory] ~= nil
end

---@param directory string
---@return boolean
function cache:apply(directory)
directory = directory or g.state.directory
local t = self.cache[directory]
Expand Down

0 comments on commit 7013ccd

Please sign in to comment.