github.com/xgzlucario/GigaCache@v0.0.0-20240508025442-54204e9c8a6b/index.go (about) 1 package cache 2 3 import ( 4 "math" 5 ) 6 7 // Key is the key of GigaCache. 8 // +------------------------------------------------+ 9 // | hash(64) | 10 // +------------------------------------------------+ 11 12 type Key uint64 13 14 // Idx is the index of GigaCache. 15 // +-----------------------+-------------------------+ 16 // | start(32) | ttl(uint32) | 17 // +-----------------------+-------------------------+ 18 19 type Idx struct { 20 h, l uint32 21 } 22 23 const ( 24 ttlMask = 0x00000000ffffffff 25 timeCarry = 1e9 26 ) 27 28 func (i Idx) start() int { 29 return int(i.h) 30 } 31 32 func (i Idx) expired() bool { 33 return i.l > noTTL && i.l < GetSec() 34 } 35 36 func (i Idx) setTTL(ts int64) Idx { 37 i.l = convTTL(ts) 38 return i 39 } 40 41 func (i Idx) TTL() int64 { 42 return int64(i.l) * timeCarry 43 } 44 45 func convTTL(ttl int64) uint32 { 46 if ttl < 0 { 47 panic("ttl is negetive") 48 } 49 check(ttl / timeCarry) 50 return uint32(ttl / timeCarry) 51 } 52 53 func check[T int | int64](x T) { 54 if x > math.MaxUint32 { 55 panic("x overflows the limit of uint32") 56 } 57 } 58 59 func newIdx(start int, ttl int64) Idx { 60 check(start) 61 return Idx{h: uint32(start), l: convTTL(ttl)} 62 } 63 64 // newIdxx is more efficient than newIdx. 65 func newIdxx(start int, idx Idx) Idx { 66 check(start) 67 return Idx{h: uint32(start), l: idx.l} 68 }