乐趣区

关于go:go内存缓存BigCache源码阅读Entry封装

一、介绍
在 bigcache 存储中,数据值存储的模式为 []byte。
咱们通过一个,存储的时候,同时会把 hash 值,key 值,工夫戳,entry 同时存起来。

咱们能够简称为 header + entry
header 的存储大小为 18 字节 [18]byte
通过 wrapEntry()函数封装。

const (
    timestampSizeInBytes = 8                                                       // Number of bytes used for timestamp
    hashSizeInBytes      = 8                                                       // Number of bytes used for hash
    keySizeInBytes       = 2                                                       // Number of bytes used for size of entry key
    headersSizeInBytes   = timestampSizeInBytes + hashSizeInBytes + keySizeInBytes // Number of bytes used for all headers
)

func wrapEntry(timestamp uint64, hash uint64, key string, entry []byte, buffer *[]byte) []byte {keyLength := len(key)
    blobLength := len(entry) + headersSizeInBytes + keyLength

    if blobLength > len(*buffer) {*buffer = make([]byte, blobLength)
    }
    blob := *buffer

    binary.LittleEndian.PutUint64(blob, timestamp)
    binary.LittleEndian.PutUint64(blob[timestampSizeInBytes:], hash)
    binary.LittleEndian.PutUint16(blob[timestampSizeInBytes+hashSizeInBytes:], uint16(keyLength))
    copy(blob[headersSizeInBytes:], key)
    copy(blob[headersSizeInBytes+keyLength:], entry)

    return blob[:blobLength]
}
退出移动版