! Copyright (C) 2017 John Benediktsson ! See https://factorcode.org/license.txt for BSD license USING: accessors assocs deques dlists kernel linked-assocs linked-assocs.private math sequences.private ; IN: lru-cache TUPLE: lru-cache < linked-assoc max-size ; : ( max-size exemplar -- assoc ) dupd new-assoc rot lru-cache boa ; : ( max-size -- assoc ) H{ } ; M: lru-cache at* [ assoc>> at* ] [ dlist>> dup ] bi '[ [ [ _ delete-node ] [ _ push-node-back ] [ obj>> second-unsafe ] tri ] when ] keep ; M: lru-cache set-at [ call-next-method ] keep dup max-size>> [ over assoc>> assoc-size < [ [ dlist>> pop-front first-unsafe ] [ assoc>> ] [ dlist>> ] tri (delete-at) ] [ drop ] if ] [ drop ] if* ; M: lru-cache clone [ assoc>> clone ] [ dlist>> clone ] [ max-size>> ] tri lru-cache boa ; TUPLE: fifo-cache < linked-assoc max-size ; : ( max-size exemplar -- assoc ) dupd new-assoc rot fifo-cache boa ; : ( max-size -- assoc ) H{ } ; M: fifo-cache set-at [ call-next-method ] keep dup max-size>> [ over assoc>> assoc-size < [ [ dlist>> pop-front first-unsafe ] [ assoc>> ] [ dlist>> ] tri (delete-at) ] [ drop ] if ] [ drop ] if* ; M: fifo-cache clone [ assoc>> clone ] [ dlist>> clone ] [ max-size>> ] tri fifo-cache boa ; TUPLE: lifo-cache < linked-assoc max-size ; : ( max-size exemplar -- assoc ) dupd new-assoc rot lifo-cache boa ; : ( max-size -- assoc ) H{ } ; M: lifo-cache set-at dup max-size>> [ over assoc>> assoc-size <= [ dup [ dlist>> pop-back first-unsafe ] [ assoc>> ] [ dlist>> ] tri (delete-at) ] when ] when* call-next-method ; M: lifo-cache clone [ assoc>> clone ] [ dlist>> clone ] [ max-size>> ] tri lifo-cache boa ;