(* 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. *) module Cache = Git.Cache (* A cache of strings, each weighing its length. *) let cache budget = Cache.v ~budget ~weight:String.length let kept c keys = List.filter_map (fun k -> Option.map (fun v -> (k, v)) (Cache.find c k)) keys (* Adding past the budget evicts the oldest entries first, until the weight is at most the budget: the newest stay. Catches a cache that evicts the newest, or evicts nothing. *) let test_oldest_first () = let c = cache 10 in List.iter (fun (k, v) -> Cache.add c k v) [ (1, "aaaa"); (2, "bbbb"); (3, "cccc") ]; Alcotest.(check (list (pair int string))) "the two newest" [ (2, "bbbb"); (3, "cccc") ] (kept c [ 1; 2; 3 ]); Alcotest.(check int) "their weight" 8 (Cache.weight c) (* A key already kept is left as it is: its value, its weight and its place in the eviction order. *) let test_key_kept () = let c = cache 10 in Cache.add c 1 "aaaa"; Cache.add c 2 "bb"; Cache.add c 1 "zzzzzz"; Alcotest.(check (option string)) "the first value" (Some "aaaa") (Cache.find c 1); Alcotest.(check int) "its weight" 6 (Cache.weight c); Cache.add c 3 "cccccc"; Alcotest.(check (list (pair int string))) "the oldest, still 1, evicted" [ (2, "bb"); (3, "cccccc") ] (kept c [ 1; 2; 3 ]) (* A value heavier than the whole budget is not kept and evicts nothing; one exactly the budget is kept alone. *) let test_heavier () = let c = cache 4 in Cache.add c 1 "ab"; Cache.add c 2 "abcde"; Alcotest.(check (list (pair int string))) "only the light one" [ (1, "ab") ] (kept c [ 1; 2 ]); Cache.add c 3 "abcd"; Alcotest.(check (list (pair int string))) "the one of the budget alone" [ (3, "abcd") ] (kept c [ 1; 2; 3 ]); Alcotest.(check int) "the budget" 4 (Cache.weight c) (* A budget of zero keeps nothing but values of no weight. *) let test_empty_budget () = let c = cache 0 in Cache.add c 1 "a"; Cache.add c 2 ""; Alcotest.(check (list (pair int string))) "the weightless one" [ (2, "") ] (kept c [ 1; 2 ]); Alcotest.(check int) "no weight" 0 (Cache.weight c) let suite = ( "cache", [ Alcotest.test_case "oldest first" `Quick test_oldest_first; Alcotest.test_case "a key kept is left" `Quick test_key_kept; Alcotest.test_case "heavier than the budget" `Quick test_heavier; Alcotest.test_case "an empty budget" `Quick test_empty_budget; ] )