okami.mom/ultraviolet
git clone https://git.nkp.pet/okami.mom/ultraviolet
227cc8b
upstream
1package lru 2 3import ( 4"container/list" 5"fmt" 6) 7 8type LRU [K comparable ,V any ]struct { 9size int 10 11items map [K ]* list.Element 12evict * list.List 13} 14 15type entry [K comparable ,T any ]struct { 16Key K 17Value T 18} 19 20func New [K comparable ,V any ](size int )* LRU [K ,V ] { 21if size < 0 { 22panic (fmt .Sprintf ("lru: negative size given: %d" ,size )) 23 } 24 25return & LRU [K ,V ]{ 26size :size , 27items :make (map [K ]* list.Element ), 28evict :list .New (), 29 } 30} 31 32func (c * LRU [K ,V ])Get (key K ) (V ,bool ) { 33e ,ok := c .items [key ] 34if ! ok { 35var zero V 36 37return zero ,false 38 } 39 40c .evict .MoveToFront (e ) 41 42return e .Value .(entry [K ,V ]).Value ,true 43} 44 45func (c * LRU [K ,V ])Add (key K ,value V ) (evicted bool ) { 46if e ,ok := c .items [key ];ok { 47c .evict .MoveToFront (e ) 48e .Value = value 49 50return false 51 } 52 53e := c .evict .PushFront (key ) 54 55e .Value = entry [K ,V ]{Key :key ,Value :value } 56 57c .items [key ]= e 58 59if c .evict .Len ()<= c .size { 60return false 61 } 62 63if oldest := c .evict .Back ();oldest != nil { 64c .evict .Remove (oldest ) 65delete (c .items ,oldest .Value .(entry [K ,V ]).Key ) 66 } 67 68return true 69}