package types import ( "encoding/binary" "math" ) // KeySize is the fixed size in bytes of the composite LSM key. // [BucketID: 4B][MetricID: 8B][Timestamp: 8B] const KeySize = 20 // ValueSize is the fixed size in bytes of the numeric value in the LSM. // [Float64: 8B] const ValueSize = 8 // EncodeKey writes the composite key into the provided 20-byte buffer. // It uses BigEndian encoding to preserve lexicographical sort order. func EncodeKey(buf []byte, b BucketID, m MetricID, ts int64) { _ = buf[19] // BCE (Bounds Check Elimination) hint binary.BigEndian.PutUint32(buf[0:4], uint32(b)) binary.BigEndian.PutUint64(buf[4:12], uint64(m)) binary.BigEndian.PutUint64(buf[12:20], uint64(ts)) } // DecodeKey decodes the composite key from a 20-byte buffer. func DecodeKey(buf []byte) (BucketID, MetricID, int64) { _ = buf[19] // BCE hint b := binary.BigEndian.Uint32(buf[0:4]) m := binary.BigEndian.Uint64(buf[4:12]) ts := binary.BigEndian.Uint64(buf[12:20]) return BucketID(b), MetricID(m), int64(ts) } // EncodeValue encodes a float64 into an 8-byte big-endian slice. func EncodeValue(buf []byte, val float64) { _ = buf[7] // BCE hint binary.BigEndian.PutUint64(buf[0:8], math.Float64bits(val)) } // DecodeValue decodes an 8-byte slice into a float64. func DecodeValue(buf []byte) float64 { _ = buf[7] // BCE hint return math.Float64frombits(binary.BigEndian.Uint64(buf[0:8])) } // BucketBounds computes the half-open byte range [start, end) covering an entire bucket. // Start is [BucketID: 4B, 0x00... (16B)]. // End is [BucketID+1: 4B, 0x00... (16B)]. func BucketBounds(b BucketID) (start, end []byte) { start = make([]byte, KeySize) binary.BigEndian.PutUint32(start[0:4], uint32(b)) end = make([]byte, KeySize) binary.BigEndian.PutUint32(end[0:4], uint32(b+1)) return start, end } // MetricBounds computes the half-open byte range [start, end) for a specific metric inside a bucket. func MetricBounds(b BucketID, m MetricID) (start, end []byte) { start = make([]byte, KeySize) binary.BigEndian.PutUint32(start[0:4], uint32(b)) binary.BigEndian.PutUint64(start[4:12], uint64(m)) end = make([]byte, KeySize) binary.BigEndian.PutUint32(end[0:4], uint32(b)) binary.BigEndian.PutUint64(end[4:12], uint64(m+1)) return start, end }