(* Copyright (c) 2026 Thomas Gazagnaire Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) (** Tables bounded by the weight of what they keep. A cache keeps values by key while their weights sum to at most its budget: adding past it evicts the oldest entries first. A miss costs only the computation again, so a tight budget stays correct. *) type ('k, 'v) t (** The type for caches of values ['v] by keys ['k], compared structurally. *) val v : budget:int -> weight:('v -> int) -> ('k, 'v) t (** [v ~budget ~weight] is an empty cache whose values weigh at most [budget] together, each [weight v]. *) val find : ('k, 'v) t -> 'k -> 'v option (** [find t k] is the value [t] keeps for [k], if any. *) val add : ('k, 'v) t -> 'k -> 'v -> unit (** [add t k v] keeps [v] for [k], evicting the oldest entries until the weight of [t] is at most its budget again. A key [t] already keeps is left as it is, and a value heavier than the whole budget is not kept. *) val weight : ('k, 'v) t -> int (** [weight t] is the sum of the weights of the values [t] keeps: at most its budget. *)