robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1--- Module for private utility functions 2 3--- @alias vim.func.MemoObj { _hash: (fun(...): any), _weak: boolean?, _cache: table<any, any> } 4 5--- @param argc integer? 6--- @return fun(...): any 7local function concat_hash ( argc ) 8return function ( ... ) 9return table . concat ( { ... } , '%%' , 1 , argc ) 10end 11end 12 13--- @param idx integer 14--- @return fun(...): any 15local function idx_hash ( idx ) 16return function ( ... ) 17return select ( idx , ... ) 18end 19end 20 21--- @param hash integer|string|fun(...): any 22--- @return fun(...): any 23local function resolve_hash ( hash ) 24if type ( hash ) == 'number' then 25hash =idx_hash ( hash ) 26elseif type ( hash ) == 'string' then 27if hash == 'concat' then 28hash =concat_hash () 29else 30local c =hash : match ( '^concat%-(%d+)' ) 31if c then 32hash =concat_hash ( vim . _assert_integer ( c )) 33else 34error ( 'invalid value for hash: ' .. hash ) 35end 36end 37end 38--- @cast hash -integer 39return hash 40end 41 42--- @param weak boolean? 43--- @return table 44local create_cache =function ( weak ) 45return setmetatable ( {} , { 46__mode =weak ~= false and 'kv' , 47} ) 48end 49 50--- @generic F: function 51--- @param hash integer|string|fun(...): any 52--- @param fn F 53--- @param weak? boolean 54--- @return F 55return function ( hash , fn , weak ) 56vim . validate ( 'hash' , hash , { 'number' , 'string' , 'function' } ) 57vim . validate ( 'fn' , fn , 'function' ) 58vim . validate ( 'weak' , weak , 'boolean' , true ) 59 60--- @type vim.func.MemoObj 61local obj ={ 62_cache =create_cache ( weak ), 63_hash =resolve_hash ( hash ), 64_weak =weak , 65--- @param self vim.func.MemoObj 66clear =function ( self , ... ) 67if select ( '#' , ... ) == 0 then 68self . _cache =create_cache ( self . _weak ) 69return 70end 71local key =self . _hash ( ... ) 72self . _cache [ key ] =nil 73end , 74} 75 76return setmetatable ( obj , { 77--- @param self vim.func.MemoObj 78__call =function ( self , ... ) 79local key =self . _hash ( ... ) 80local cache =self . _cache 81if cache [ key ] == nil then 82cache [ key ] =vim . F . pack_len ( fn ( ... )) 83end 84return vim . F . unpack_len ( cache [ key ]) 85end , 86} ) 87end