encoding.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package bigcache
  2. import (
  3. "encoding/binary"
  4. )
  5. const (
  6. timestampSizeInBytes = 8 // Number of bytes used for timestamp
  7. hashSizeInBytes = 8 // Number of bytes used for hash
  8. keySizeInBytes = 2 // Number of bytes used for size of entry key
  9. headersSizeInBytes = timestampSizeInBytes + hashSizeInBytes + keySizeInBytes // Number of bytes used for all headers
  10. )
  11. func wrapEntry(timestamp uint64, hash uint64, key string, entry []byte, buffer *[]byte) []byte {
  12. keyLength := len(key)
  13. blobLength := len(entry) + headersSizeInBytes + keyLength
  14. if blobLength > len(*buffer) {
  15. *buffer = make([]byte, blobLength)
  16. }
  17. blob := *buffer
  18. binary.LittleEndian.PutUint64(blob, timestamp)
  19. binary.LittleEndian.PutUint64(blob[timestampSizeInBytes:], hash)
  20. binary.LittleEndian.PutUint16(blob[timestampSizeInBytes+hashSizeInBytes:], uint16(keyLength))
  21. copy(blob[headersSizeInBytes:], key)
  22. copy(blob[headersSizeInBytes+keyLength:], entry)
  23. return blob[:blobLength]
  24. }
  25. func readEntry(data []byte) []byte {
  26. length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:])
  27. // copy on read
  28. dst := make([]byte, len(data)-int(headersSizeInBytes+length))
  29. copy(dst, data[headersSizeInBytes+length:])
  30. return dst
  31. }
  32. func readTimestampFromEntry(data []byte) uint64 {
  33. return binary.LittleEndian.Uint64(data)
  34. }
  35. func readKeyFromEntry(data []byte) string {
  36. length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:])
  37. // copy on read
  38. dst := make([]byte, length)
  39. copy(dst, data[headersSizeInBytes:headersSizeInBytes+length])
  40. return bytesToString(dst)
  41. }
  42. func readHashFromEntry(data []byte) uint64 {
  43. return binary.LittleEndian.Uint64(data[timestampSizeInBytes:])
  44. }
  45. func resetKeyFromEntry(data []byte) {
  46. binary.LittleEndian.PutUint64(data[timestampSizeInBytes:], 0)
  47. }