Files
qb/chunkenc/cumdelta.go

312 lines
8.6 KiB
Go
Raw Normal View History

2026-02-10 14:02:11 +00:00
package chunkenc
import (
"fmt"
2026-05-10 00:59:47 +00:00
"log"
2026-02-10 14:02:11 +00:00
"math"
"gordenko.dev/dima/qb/conbuf"
)
2026-05-10 00:59:47 +00:00
// COMPRESSOR REVERSE
/*
Формат:
base value (var u64)
delta (var u64)
q (qty of previous deltas; msb=0 - series, msb=1 - non series, low 7 bits - qty 1..128)
delta
delta
delta
q
Дельта рахується від base value.
Декодування у зворотньому порядку.
Після base value слідують run або literal блоки.
Run блок - це delta + header byte в кінці.
Literal блок - це від одної до N дельт + header byte в кінці.
Спочатку створюється literal блок.
Якщо для останної дельти додається дублікат, literal блок модифікується -
лічильник зменшується до 1. А остання дельта переміщюється в новий run блок.
Причому лічильник 0 - означає 2 елементи. Приклад:
До:
v1 v2 v3 h-byte(literal, 3) <- v3
Після:
v1 v2 h-byte(literal, 2) v3 h-byte(run, 2)
*/
2026-02-10 14:02:11 +00:00
type ReverseCumulativeDeltaCompressor struct {
2026-05-10 00:59:47 +00:00
buf *conbuf.ContinuousBuffer
coef float64
pos int
baseValue float64
lastDelta uint64
lastDeltaSize int
h byte
state *CumulativeDeltaBound
2026-02-10 14:02:11 +00:00
}
func NewReverseCumulativeDeltaCompressor(buf *conbuf.ContinuousBuffer, size int, fracDigits byte) *ReverseCumulativeDeltaCompressor {
var coef float64 = 1
if fracDigits > 0 {
coef = math.Pow(10, float64(fracDigits))
}
s := &ReverseCumulativeDeltaCompressor{
buf: buf,
2026-05-10 00:59:47 +00:00
pos: size, // перший вільний байт
2026-02-10 14:02:11 +00:00
coef: coef,
}
if size > 0 {
2026-05-10 00:59:47 +00:00
u64, _, err := s.buf.GetVarUint64(0)
2026-02-10 14:02:11 +00:00
if err != nil {
2026-05-10 00:59:47 +00:00
log.Fatalf("bug: get base value: %s", err)
2026-02-10 14:02:11 +00:00
}
2026-05-10 00:59:47 +00:00
s.baseValue = float64(u64) / s.coef
s.h = s.buf.GetByte(s.pos - 1)
s.lastDelta, s.lastDeltaSize, err = s.buf.ReverseGetVarUint64(s.pos - 2)
if err != nil {
log.Fatalf("bug: get last delta: %s", err)
2026-02-10 14:02:11 +00:00
}
}
2026-05-10 00:59:47 +00:00
return s
2026-02-10 14:02:11 +00:00
}
func (s *ReverseCumulativeDeltaCompressor) Size() int {
return s.pos
}
2026-05-10 00:59:47 +00:00
//func (s *ReverseCumulativeDeltaCompressor) CalcRequiredSpace(value float64) int {
//}
2026-02-10 14:02:11 +00:00
func (s *ReverseCumulativeDeltaCompressor) Append(value float64) {
if s.pos == 0 {
2026-05-10 00:59:47 +00:00
// base value
s.pos += s.buf.PutVarUint64(s.pos, uint64(value*s.coef))
s.baseValue = value
s.appendNewLiteral(0)
2026-02-10 14:02:11 +00:00
} else {
2026-05-10 00:59:47 +00:00
delta := uint64((value-s.baseValue)*s.coef + eps)
2026-02-10 14:02:11 +00:00
if delta == s.lastDelta {
2026-05-10 00:59:47 +00:00
if s.h < 128 {
// run блок - отже треба збільшити лічильник
if s.h < 127 {
// increase counter
s.h++
s.buf.SetByte(s.pos-1, s.h)
} else {
// не можу збільшити - буде переповнення. Додаю новий literal блок
// counter overflow
s.appendNewLiteral(delta)
}
2026-02-10 14:02:11 +00:00
} else {
2026-05-10 00:59:47 +00:00
// literal блок.
// Якщо в ньому лише одне значення - перетворюю його на run блок.
// Інакше забираю останнє значення із literal блока і додаю новий run блок.
q := s.h & 127
if q == 0 { // 1 кодується як 0
s.convertLiteralToRun()
2026-02-10 14:02:11 +00:00
} else {
2026-05-10 00:59:47 +00:00
// забираю останнє значення із literal блоку щоб зробити run блок
s.convertLastFromLiteralToRun()
2026-02-10 14:02:11 +00:00
}
}
} else {
2026-05-10 00:59:47 +00:00
if s.h < 127 { // fix 128?
// end of run
s.appendNewLiteral(delta)
} else {
if s.h < 255 {
// encode value from pos - 1, then append h byte
s.appendDeltaToLiteral(delta)
} else {
// overflowed - encode new
s.appendNewLiteral(delta)
}
}
2026-02-10 14:02:11 +00:00
}
}
}
2026-05-10 00:59:47 +00:00
func (s *ReverseCumulativeDeltaCompressor) convertLastFromLiteralToRun() {
// Зменшую кількість елементів в literal блоці
s.h--
s.pos -= 1 + s.lastDeltaSize
s.buf.SetByte(s.pos, s.h) // закриваю literal блок
s.pos++
s.lastDeltaSize = s.buf.ReversePutVarUint64(s.pos, s.lastDelta)
s.pos += s.lastDeltaSize
s.h = 0 // run блок, довжини 2
s.buf.SetByte(s.pos, s.h)
s.pos++
}
2026-02-10 14:02:11 +00:00
2026-05-10 00:59:47 +00:00
func (s *ReverseCumulativeDeltaCompressor) convertLiteralToRun() {
// Знімаю flagLiteral, а лічильник 0 дорівнює 2 елементам в серії.
s.h = 0
s.buf.SetByte(s.pos-1, s.h)
2026-02-10 14:02:11 +00:00
}
2026-05-10 00:59:47 +00:00
func (s *ReverseCumulativeDeltaCompressor) appendDeltaToLiteral(delta uint64) {
s.h++ // збільшую к-сть дельт
2026-02-10 14:02:11 +00:00
s.lastDelta = delta
2026-05-10 00:59:47 +00:00
s.pos--
s.lastDeltaSize = s.buf.ReversePutVarUint64(s.pos, delta)
s.pos += s.lastDeltaSize
s.buf.SetByte(s.pos, s.h)
2026-02-10 14:02:11 +00:00
s.pos++
}
2026-05-10 00:59:47 +00:00
func (s *ReverseCumulativeDeltaCompressor) appendNewLiteral(delta uint64) {
s.h = flagLiteral
s.lastDelta = delta
s.lastDeltaSize = s.buf.ReversePutVarUint64(s.pos, delta)
s.pos += s.lastDeltaSize
s.buf.SetByte(s.pos, flagLiteral) // literal, length = 1
2026-02-10 14:02:11 +00:00
s.pos++
}
2026-05-10 00:59:47 +00:00
func (s *ReverseCumulativeDeltaCompressor) DeleteLast() {
2026-02-10 14:02:11 +00:00
}
2026-05-10 00:59:47 +00:00
type CumulativeDeltaBound struct {
Pos int
H byte
LastDelta uint64
Chunks [][]byte
}
2026-02-10 14:02:11 +00:00
2026-05-10 00:59:47 +00:00
// delta h
func (s *ReverseCumulativeDeltaCompressor) Lock() {
s.state = &CumulativeDeltaBound{
Pos: s.pos - 1 - s.lastDeltaSize,
H: s.h,
LastDelta: s.lastDelta,
Chunks: s.buf.Chunks(),
2026-02-10 14:02:11 +00:00
}
}
2026-05-10 00:59:47 +00:00
func (s *ReverseCumulativeDeltaCompressor) CreateDecompressor(fracDigits byte) *ReverseCumulativeDeltaDecompressor {
if s.state == nil {
d := NewReverseCumulativeDeltaDecompressor(s.buf, s.Size(), fracDigits)
d.RestoreFromEnd()
return d
}
d := NewReverseCumulativeDeltaDecompressor(s.buf, s.Size(), fracDigits)
d.RestoreFromBound(*s.state)
return d
}
func (s *ReverseCumulativeDeltaCompressor) Unlock() {
s.state = nil
}
// DECOMPRESSOR
2026-02-10 14:02:11 +00:00
type ReverseCumulativeDeltaDecompressor struct {
2026-05-10 00:59:47 +00:00
buf *conbuf.ContinuousBuffer
coef float64
pos int
bound int
baseValue float64
lastValue float64
isRun bool
pending int
done bool
2026-02-10 14:02:11 +00:00
}
func NewReverseCumulativeDeltaDecompressor(buf *conbuf.ContinuousBuffer, size int, fracDigits byte) *ReverseCumulativeDeltaDecompressor {
var coef float64 = 1
if fracDigits > 0 {
coef = math.Pow(10, float64(fracDigits))
}
2026-05-10 00:59:47 +00:00
u64, n, err := buf.GetVarUint64(0)
if err != nil {
log.Fatalf("bug: get base value: %s", err)
}
//fmt.Printf("baseValue: %.2f, bound: %d, pos: %d\n", float64(u64)/coef, n, size)
2026-02-10 14:02:11 +00:00
return &ReverseCumulativeDeltaDecompressor{
2026-05-10 00:59:47 +00:00
buf: buf,
coef: coef,
pos: size - 1, // last elem
baseValue: float64(u64) / coef,
bound: n,
2026-02-10 14:02:11 +00:00
}
}
2026-05-10 00:59:47 +00:00
func (s *ReverseCumulativeDeltaDecompressor) RestoreFromEnd() {
if s.pos > s.bound {
// читаю заголовок наступної серії
s.readHeader()
s.readValue()
} else {
s.done = true
2026-02-10 14:02:11 +00:00
}
2026-05-10 00:59:47 +00:00
}
func (s *ReverseCumulativeDeltaDecompressor) RestoreFromBound(bound CumulativeDeltaBound) {
s.pos = bound.Pos - 1
s.lastValue = s.baseValue + float64(bound.LastDelta)
s.decodeHeaderByte(bound.H)
fmt.Printf("restore from bound: isRun=%t, pending=%d\n", s.isRun, s.pending)
}
func (s *ReverseCumulativeDeltaDecompressor) NextValue() (value float64, done bool) {
//fmt.Printf("NextValue(): bound: %d, pos: %d, pending: %d\n", s.bound, s.pos, s.pending)
if s.done {
return 0, true
2026-02-10 14:02:11 +00:00
}
2026-05-10 00:59:47 +00:00
// повертаю значення, що було прочитано в методі RestoreFromBound/RestoreFromEnd
value = s.lastValue
s.pending--
if s.pending > 0 {
// якщо в серії залишаються елементи
if !s.isRun {
s.readValue()
}
} else if s.pos > s.bound {
// в серії більше немає елементів, отже перевіряє чи є ще дані в буфері.
// дані є - читаю заголовок наступної серії
s.readHeader()
s.readValue()
} else {
s.done = true
2026-02-10 14:02:11 +00:00
}
2026-05-10 00:59:47 +00:00
// серія завершена - перевіряю чи є ще серії
return value, false
2026-02-10 14:02:11 +00:00
}
2026-05-10 00:59:47 +00:00
func (s *ReverseCumulativeDeltaDecompressor) readHeader() {
h := s.buf.GetByte(s.pos)
s.pos--
s.decodeHeaderByte(h)
// fmt.Println("h:", h)
// fmt.Println("isRun:", s.isRun)
// fmt.Println("pending:", s.pending)
}
func (s *ReverseCumulativeDeltaDecompressor) readValue() {
2026-02-10 14:02:11 +00:00
u64, n, err := s.buf.ReverseGetVarUint64(s.pos)
if err != nil {
2026-05-10 00:59:47 +00:00
log.Fatalln(err)
2026-02-10 14:02:11 +00:00
}
2026-05-10 00:59:47 +00:00
// fmt.Println()
// fmt.Println("read from pos:", s.pos)
// fmt.Println("read delta:", u64)
// fmt.Println("read delta n:", n)
// fmt.Println()
2026-02-10 14:02:11 +00:00
s.pos -= n
2026-05-10 00:59:47 +00:00
s.lastValue = s.baseValue + float64(u64)/s.coef
}
2026-02-10 14:02:11 +00:00
2026-05-10 00:59:47 +00:00
func (s *ReverseCumulativeDeltaDecompressor) decodeHeaderByte(h byte) {
s.isRun = h < 128
if s.isRun {
s.pending = int(h&127) + 2
2026-02-10 14:02:11 +00:00
} else {
2026-05-10 00:59:47 +00:00
s.pending = int(h&127) + 1
2026-02-10 14:02:11 +00:00
}
}
2026-05-10 00:59:47 +00:00
//