Skip to content

Instantly share code, notes, and snippets.

@husio
Created January 30, 2015 16:53
Show Gist options
  • Save husio/c657265f7a9eee30bbfe to your computer and use it in GitHub Desktop.
Save husio/c657265f7a9eee30bbfe to your computer and use it in GitHub Desktop.
package main
import (
"container/list"
)
type Lru struct {
maxsize int
order *list.List
elems map[string]*list.Element
}
type lruitem struct {
key string
value interface{}
}
func NewLru(size int) *Lru {
return &Lru{
maxsize: size,
order: list.New(),
elems: make(map[string]*list.Element),
}
}
func (lru *Lru) Add(key string, value interface{}) {
if elem, ok := lru.elems[key]; ok {
lru.order.MoveToFront(elem)
elem.Value = &lruitem{key: key, value: value}
return
}
elem := lru.order.PushFront(&lruitem{key: key, value: value})
lru.elems[key] = elem
if len(lru.elems) > lru.maxsize {
value := lru.order.Remove(lru.order.Back())
delete(lru.elems, value.(*lruitem).key)
}
}
func (lru *Lru) Delete(key string) bool {
elem, ok := lru.elems[key]
if ok {
lru.order.Remove(elem)
delete(lru.elems, key)
}
return ok
}
func (lru *Lru) Get(key string) (value interface{}, ok bool) {
if elem, ok := lru.elems[key]; ok {
lru.order.MoveToFront(elem)
value = elem.Value.(*lruitem).value
return value, true
}
return nil, false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment