coocood/freecache

a big bug?

forezp opened this issue · 4 comments

code:

import (
	"crypto/md5"
	"fmt"
	"github.com/coocood/freecache"
	"strconv"
)

var (
	defaultCache *freecache.Cache
)

func main() {
	Init()
	keyPrefix := "awdwoiejorejfewknr3kjio4jo43jodfnkfnfrkfrnrkfrjireire"
	var keyexist string
	for i := 0; i < 10000000; i++ {
		k := keyPrefix + strconv.Itoa(i)
		kMd5Str := Md5(k)

		SetString(kMd5Str, "1")
		if i == 99 {
			keyexist = kMd5Str
			fmt.Println("keyexist is  exist ? =", Exist(keyexist))
		}
	}
	fmt.Println("keyexist is  exist ? =", Exist(keyexist))
}

func Init() {
	cacheSize := 500 * 1024 * 1024
	c := freecache.NewCache(cacheSize)
	defaultCache = c
}

func SetString(key, value string) {
	defaultCache.Set([]byte(key), []byte(value), 300)
}

func Exist(key string) bool {
	b, err := defaultCache.Get([]byte(key))
	if err != nil {
		return false
	}
	if len(b) > 0 {
		return true
	}
	return false
}

func Get(key string) []byte {
	b, err := defaultCache.Get([]byte(key))
	if err == nil {
		if len(b) > 0 {
			return b
		}
	}
	return nil
}

func GetString(key string) string {
	b := Get(key)
	if len(b) > 0 {
		return string(b)
	}
	return ""
}

func Length() int {
	return int(defaultCache.EntryCount())
}

func Md5(str string) string {
	data := []byte(str)
	has := md5.Sum(data)
	md5str1 := fmt.Sprintf("%x", has) //将[]byte转成16进制
	return md5str1
}

output:

keyexist is  exist ? = true
keyexist is  exist ? = false

The cache is full and the key is evicted.

fmt.Println(defaultCache.EntryCount(), defaultCache.EvacuateCount())

The cache is full and the key is evicted.

fmt.Println(defaultCache.EntryCount(), defaultCache.EvacuateCount())

you are right ,thank you for yourhelp!

Hi @coocood

Can you explain me if it is possible that the get function return no error and nil value when the key is evicted?
If it is, How can I difreneciate an empty value from an evicted value? If set a len 0 slice, the get returns to me a nil value.

Hi @coocood

Can you explain me if it is possible that the get function return no error and nil value when the key is evicted? If it is, How can I difreneciate an empty value from an evicted value? If set a len 0 slice, the get returns to me a nil value.

If the key is not found, ErrorNotFound should be returned.