-- SPDX-FileCopyrightText: © 2022—2026 Vladimir Zorin -- SPDX-License-Identifier: LicenseRef-OWL-1.0-or-later -- Licensed under OWL v1.0+. See LICENSE. --[[ Bounded two-generation cache: `get` promotes hits from the stale generation into the fresh one; once the fresh generation reaches `cap` entries it becomes the stale one and a new table starts. At most 2*cap entries are live, and cold entries age out within two rotations without any per-entry bookkeeping. ]] local put = function(state, key, value) if state.fresh[key] == nil then state.count = state.count + 1 end state.fresh[key] = value if state.count >= state.cap then state.stale = state.fresh state.fresh = {} state.count = 0 end end local get = function(self, key) local state = self.__state local value = state.fresh[key] if value == nil then value = state.stale[key] if value ~= nil then put(state, key, value) end end return value end local set = function(self, key, value) put(self.__state, key, value) end local new = function(cap) return { cfg = { cap = cap }, __state = { fresh = {}, stale = {}, count = 0, cap = cap }, get = get, set = set, } end return { new = new, }