From ee8c3d42e85515faa0d72623b1d6db007221bdc8 Mon Sep 17 00:00:00 2001 From: HuangJiaLuo <1820799930@qq.com> Date: Sun, 5 Sep 2021 22:48:01 +0800 Subject: [PATCH] Test --- pkg/lru/LRU.go | 117 ++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 91 insertions(+), 26 deletions(-) diff --git a/pkg/lru/LRU.go b/pkg/lru/LRU.go index 001c778..58abec1 100644 --- a/pkg/lru/LRU.go +++ b/pkg/lru/LRU.go @@ -1,45 +1,110 @@ -package lru +package main import ( "container/list" - "gitee.com/timedb/wheatCache/pkg/lru/define" + "fmt" ) -type CacheNode struct { - value int - key string +type Node struct { + Key, Value interface{} } -type Cache struct { - cache map[string]*list.Element +func (*Node) NewCacheNode(k, v interface{}) *Node { + return &Node{k, v} +} + +type LRUCache struct { + maxsize int //最大的长度 li *list.List - size int // LRU的长度 - MaxByte int64 // 允许的最大存储 - NowByte int64 // 目前的存储 + LruMap map[interface{}]*list.Element } -// 创建一个LRU -func NewLRU() *Cache { - return &Cache{ - MaxByte: define.MaxByte, - size: 0, - NowByte: 0, - cache: make(map[string]*list.Element), +// lru初始化 +func NewLRUCache(size int) *LRUCache { + return &LRUCache{ + maxsize: size, + li: list.New(), + LruMap: make(map[interface{}]*list.Element)} +} + +//返回lru的长度 +func (lru *LRUCache) GetSize() int { + return lru.li.Len() +} + +//增 +func (lru *LRUCache) Add(k, v interface{}) error { + + if lru.li == nil { + return nil } + + if PreEle, ok := lru.LruMap[k]; ok { + lru.li.MoveToFront(PreEle) + PreEle.Value.(*Node).Value = v + return nil + } + + newEle := lru.li.PushFront(&Node{k, v}) + lru.LruMap[k] = newEle + + //超过最长就删 + if lru.li.Len() > lru.maxsize { + // 去掉最后一个 + last := lru.li.Back() + if last == nil { + return nil + } + Node := last.Value.(*Node) + delete(lru.LruMap, Node.Key) + lru.li.Remove(last) + } + return nil } -// -func GetLRU() { +//查 +func (lru *LRUCache) Get(k interface{}) (v interface{}, ret bool) { + if lru.LruMap == nil { + return v, false + } + + if PreEle, ok := lru.LruMap[k]; ok { + // 移到最前面 + lru.li.MoveToFront(PreEle) + return PreEle.Value.(*Node).Value, true + } + return v, false } -// -func (c *Cache) AddLRU(key string, value int) { - - c.size += 1 +//删 +func (lru *LRUCache) Remove(k interface{}) bool { + if lru.LruMap == nil { + return false + } + if PreEle, ok := lru.LruMap[k]; ok { + cacheNode := PreEle.Value.(*Node) + delete(lru.LruMap, cacheNode.Key) + lru.li.Remove(PreEle) + return true + } + return false } -//获取链表长度 -func (c *Cache) GetLRULength() int { - return c.size +func main() { + lru := NewLRUCache(3) + lru.Add(10, "test1") + lru.Add(20, "test2") + lru.Add(30, "test3") + v, ret := lru.Get(10) + if ret { + fmt.Println(v) + } + lru.Add(40, "test4") + + v, ret = lru.Get(20) + if ret { + fmt.Println(v) + } + }