This commit is contained in:
2026-06-07 21:27:18 +03:00
parent 776a341c57
commit 964fe4b4a8
14 changed files with 2415 additions and 2283 deletions

View File

@@ -1,102 +1,440 @@
package enc
import (
"log"
"math"
"gordenko.dev/dima/qb/bin"
bin "gordenko.dev/dima/bin/little"
"gordenko.dev/dima/qb"
)
type ReverseCumulativeDeltaDecompressor struct {
buf []byte
pos int
bound int
firstValue float64
lastValue float64
length uint16
coef float64
idxOf8 uint
s8 byte
// 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)
*/
type CumulativeDeltaCompressor struct {
buf []byte
coef float64
pos int
baseValue float64
lastDelta uint64
h byte
state *CumulativeDeltaCapturedState
}
func NewReverseCumulativeDeltaDecompressor(buf []byte, fracDigits byte) *ReverseCumulativeDeltaDecompressor {
// Після відновлення із снапшота
func NewCumulativeDeltaCompressor(buf []byte, payloadSize int, fracDigits byte) *CumulativeDeltaCompressor {
var coef float64 = 1
if fracDigits > 0 {
coef = math.Pow(10, float64(fracDigits))
}
return &ReverseCumulativeDeltaDecompressor{
s := &CumulativeDeltaCompressor{
buf: buf,
pos: payloadSize, // перший вільний байт
coef: coef,
pos: len(buf),
}
if payloadSize > 0 {
u64, _, err := bin.GetVarUint64(buf)
if err != nil {
log.Fatalf("bug: get base value: %s", err)
}
s.baseValue = float64(u64) / s.coef
s.pos--
s.h = s.buf[s.pos]
var n int
s.lastDelta, n, err = bin.ReverseGetVarUint64(s.buf[:s.pos])
if err != nil {
log.Fatalf("bug: get last delta: %s", err)
}
s.pos -= n
}
return s
}
// func (s *CumulativeDeltaCompressor) Size() int {
// return s.pos
// }
func (s *CumulativeDeltaCompressor) Evaluate(value float64) (compressionWay int, requiredSpace int) {
var (
delta = uint64((value-s.baseValue)*s.coef + eps)
)
if s.pos > 0 {
if s.h < 128 {
// run
if delta == s.lastDelta && s.h < 127 {
compressionWay = incrementRun
requiredSpace += bin.CountVarUint64(uint64(s.lastDelta)) + // current delta
hSize
} else {
compressionWay = endSeries
requiredSpace += bin.CountVarUint64(uint64(s.lastDelta)) + // previous delta
hSize + // h - end of run
bin.CountVarUint64(uint64(delta)) + // new literal
hSize // new h
}
} else {
// literal
if delta != s.lastDelta {
if s.h < 255 {
compressionWay = incrementLiteral
requiredSpace += bin.CountVarUint64(uint64(s.lastDelta)) + // previous delta
bin.CountVarUint64(uint64(delta)) + // new delta
hSize
} else {
compressionWay = endSeries
requiredSpace += bin.CountVarUint64(uint64(s.lastDelta)) + // previous delta
hSize + // h - end of literal
bin.CountVarUint64(uint64(delta)) + // new literal
hSize // new h
}
} else {
compressionWay = startRun
if s.h > 128 {
requiredSpace += hSize // h - end of literal
}
requiredSpace += bin.CountVarUint64(uint64(delta)) + // new delta
hSize // new h
}
}
} else {
// encode base value
compressionWay = addBaseValue
requiredSpace = bin.CountVarUint64(uint64(value*s.coef)) + // base value
bin.CountVarUint64(uint64(delta)) + // new delta
+hSize // new h
}
return
}
func (s *CumulativeDeltaCompressor) Compress(compressionWay int, value float64) {
delta := uint64((value-s.baseValue)*s.coef + eps)
switch compressionWay {
case incrementRun:
s.h++
case incrementLiteral:
// write previous delta and increment counter
n, _ := bin.ReversePutVarUint64(s.buf[s.pos:], uint64(s.lastDelta))
s.pos += n
s.lastDelta = delta
s.h++
case endSeries:
n, _ := bin.ReversePutVarUint64(s.buf[s.pos:], uint64(s.lastDelta))
s.pos += n
// write h - end of run
s.buf[s.pos] = s.h
s.pos++
// start new literal (length=1)
s.lastDelta = delta
s.h = 128
case startRun:
if s.h > 128 {
// write h - end of literal (because length > 1)
s.h--
s.buf[s.pos] = s.h
s.pos++
}
// start new run (length=2)
s.h = 0
case addBaseValue:
// start new literal (length=1)
n, _ := bin.PutVarUint64(s.buf[s.pos:], uint64(value*s.coef))
s.pos += n
s.baseValue = value
// start new literal (length=1)
s.lastDelta = 0
s.h = 128
}
}
func (s *ReverseCumulativeDeltaDecompressor) NextValue() (value float64, done bool) {
if s.length > 0 {
s.length--
return s.lastValue, false
func (s *CumulativeDeltaCompressor) DeleteLast() {
}
type CumulativeDeltaCapturedState struct {
H byte
LastDelta uint64
Payload []byte
}
func (s *CumulativeDeltaCompressor) CaptureState() {
if s.state != nil {
qb.Abort(qb.RepeatableLock, nil)
}
if s.pos < s.bound {
// позиція посувається вліво, отже може перескочити на попередній chunk
s.state = &CumulativeDeltaCapturedState{
H: s.h,
LastDelta: s.lastDelta,
Payload: s.buf[:s.pos],
}
}
// fix - повернути в Pool буфери
func (s *CumulativeDeltaCompressor) ForgetCapturedState() {
s.state = nil
}
func (s *CumulativeDeltaCompressor) Offset() int {
// if s.state != nil {
// return s.state.Pos
// }
return 0
}
// Snapshot - для створення снапшота.
func (s *CumulativeDeltaCompressor) Snapshot() (left []byte, right []byte) {
if s.state == nil {
left = s.buf[:s.pos]
right = s.encodeTail(s.lastDelta, s.h)
} else {
left = s.state.Payload
right = s.encodeTail(s.state.LastDelta, s.state.H)
}
return
}
func (s *CumulativeDeltaCompressor) encodeTail(lastDelta uint64, h byte) []byte {
tail := make([]byte, 10) // max var uint64 + h
n, _ := bin.PutVarUint64(tail, lastDelta)
tail[n] = h
return tail[:n+1]
}
func (s *CumulativeDeltaCompressor) Rotate(newbuf []byte) (payloadSize int) {
n, _ := bin.PutVarUint64(s.buf[s.pos:], s.lastDelta)
s.pos += n
s.buf[s.pos] = s.h
s.pos++
payloadSize = s.pos
// УВАГА!
// state не чіпаємо
s.buf = newbuf
s.pos = 0
s.baseValue = 0
s.lastDelta = 0
s.h = 0
return
}
func (s *CumulativeDeltaCompressor) CreateDecompressor() qb.ValueDecompressor {
var (
h = s.h
lastDelta = s.lastDelta
payload = s.buf[:s.pos]
)
if s.state != nil {
h = s.state.H
lastDelta = s.state.LastDelta
payload = s.state.Payload
}
return NewCumulativeDeltaDecompressorFromState(CumulativeDeltaDecompressorFromStateOptions{
Coef: s.coef,
H: h,
LastDelta: lastDelta,
Payload: payload,
})
}
func (s *CumulativeDeltaCompressor) Chunks() []byte {
return s.buf
}
// DECOMPRESSOR
type CumulativeDeltaDecompressor struct {
buf []byte
coef float64
pos int
bound int
baseValue float64
lastValue float64
isRun bool
pending int
done bool
}
func NewCumulativeDeltaDecompressor(buf []byte, fracDigits byte) *CumulativeDeltaDecompressor {
var coef float64 = 1
if fracDigits > 0 {
coef = math.Pow(10, float64(fracDigits))
}
u64, n, err := bin.GetVarUint64(buf)
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)
s := &CumulativeDeltaDecompressor{
buf: buf,
coef: coef,
pos: len(buf), // first free
baseValue: float64(u64) / coef,
bound: n,
}
// читаю заголовок наступної серії
s.readHeader()
s.readValue()
return s
}
type CumulativeDeltaDecompressorFromStateOptions struct {
Coef float64
H byte
LastDelta uint64
Payload []byte
}
func NewCumulativeDeltaDecompressorFromState(opt CumulativeDeltaDecompressorFromStateOptions) *CumulativeDeltaDecompressor {
u64, n, err := bin.GetVarUint64(opt.Payload)
if err != nil {
log.Fatalf("bug: get base value: %s", err)
}
//fmt.Printf("baseValue: %.2f, bound: %d, pos: %d\n", float64(u64)/opt.Coef, n, size)
s := &CumulativeDeltaDecompressor{
buf: opt.Payload,
coef: opt.Coef,
pos: len(opt.Payload), // first free
baseValue: float64(u64) / opt.Coef,
bound: n,
}
s.lastValue = s.baseValue + float64(opt.LastDelta)/s.coef
s.decodeHeaderByte(opt.H)
//fmt.Printf("payload: %d\n", opt.Payload)
//fmt.Printf("restore from state: bound=%d, isRun=%t, pending=%d, baseValue=%v, lastValue=%v\n",
// n, s.isRun, s.pending, s.baseValue, s.lastValue)
return s
}
func (s *CumulativeDeltaDecompressor) 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
}
if s.pos == len(s.buf) {
u64, n, err := bin.GetVarUint64(s.buf)
if err != nil {
panic(err)
// метод працює як do while - спочатку значення, а потім перевірка умови
value = s.lastValue
s.pending--
if s.pending > 0 {
// якщо в серії залишаються елементи
if !s.isRun {
s.readValue()
}
s.firstValue = float64(u64) / s.coef
s.bound = n
s.pos--
s.idxOf8 = uint(8 - s.buf[s.pos])
s.pos--
s.s8 = s.buf[s.pos]
s.pos--
s.readVar()
if s.length > 0 {
s.length--
}
return s.lastValue, false
}
if s.idxOf8 == 0 {
s.s8 = s.buf[s.pos]
s.pos--
}
s.readVar()
if s.length > 0 {
s.length--
}
return s.lastValue, false
}
func (s *ReverseCumulativeDeltaDecompressor) readVar() {
u64, n, err := bin.ReverseGetVarUint64(s.buf[:s.pos+1])
if err != nil {
panic(err)
}
s.pos -= n
s.lastValue = s.firstValue + float64(u64)/s.coef
var flag byte = 1 << s.idxOf8
if (s.s8 & flag) == flag {
s.decodeLength()
}
if s.idxOf8 == 7 {
s.idxOf8 = 0
} else if s.pos > s.bound {
// в серії більше немає елементів, отже перевіряє чи є ще дані в буфері.
// дані є - читаю заголовок наступної серії
s.readHeader()
s.readValue()
} else {
s.idxOf8++
s.done = true
}
// серія завершена - перевіряю чи є ще серії
return value, false
}
func (s *ReverseCumulativeDeltaDecompressor) decodeLength() {
b1 := s.buf[s.pos]
func (s *CumulativeDeltaDecompressor) readHeader() {
//fmt.Println("read from pos:", s.pos)
s.pos--
if b1 < 128 {
s.length = uint16(b1)
} else {
b2 := s.buf[s.pos]
s.pos--
s.length = uint16(b1&127) | (uint16(b2) << 7)
}
s.length += 2
h := s.buf[s.pos]
s.decodeHeaderByte(h)
// fmt.Println("h:", h)
// fmt.Println("isRun:", s.isRun)
// fmt.Println("pending:", s.pending)
}
func (s *CumulativeDeltaDecompressor) readValue() {
u64, n, err := bin.ReverseGetVarUint64(s.buf[:s.pos])
if err != nil {
log.Fatalln(err)
}
// fmt.Println()
// fmt.Println("read from pos:", s.pos)
// fmt.Println("read delta:", u64)
// fmt.Println("read delta n:", n)
// fmt.Println()
s.pos -= n
s.lastValue = s.baseValue + float64(u64)/s.coef
//fmt.Println(s.baseValue, float64(u64)/s.coef)
}
func (s *CumulativeDeltaDecompressor) decodeHeaderByte(h byte) {
s.isRun = h < 128
if s.isRun {
s.pending = int(h) + 2
} else {
s.pending = int(h&127) + 1
}
}
//
// func (s *CumulativeDeltaCompressor) Append(value float64) {
// if s.pos == 0 {
// // base value
// n, _ := bin.PutVarUint64(s.buf[s.pos:], uint64(value*s.coef))
// s.pos += n
// s.baseValue = value
// s.appendNewLiteral(0)
// } else {
// delta := uint64((value-s.baseValue)*s.coef + eps)
// if delta == s.lastDelta {
// if s.h < 128 {
// // run блок - отже треба збільшити лічильник
// if s.h < 127 {
// // increase counter
// s.h++
// s.buf[s.pos-1] = s.h
// } else {
// // не можу збільшити - буде переповнення. Додаю новий literal блок
// // counter overflow
// s.appendNewLiteral(delta)
// }
// } else {
// // literal блок.
// // Якщо в ньому лише одне значення - перетворюю його на run блок.
// // Інакше забираю останнє значення із literal блока і додаю новий run блок.
// q := s.h & 127
// if q == 0 { // 1 кодується як 0
// s.convertLiteralToRun()
// } else {
// // забираю останнє значення із literal блоку щоб зробити run блок
// s.convertLastFromLiteralToRun()
// }
// }
// } else {
// 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)
// }
// }
// }
// }
// }

View File

@@ -1,3 +1,18 @@
package enc
const eps = 0.000001
const (
flagLiteral = 128
hSize = 1
// append scripts
addBaseValue = 0 // cumulative and instant only
addUnixtime = 0 // time only
incrementRun = 1
incrementLiteral = 2
endSeries = 3
startRun = 4
add1stDelta = 5 // time only
)

1005
enc/enc_test.go Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,130 +1,496 @@
package enc
import (
"fmt"
"log"
"math"
octopus "gordenko.dev/dima/qb"
"gordenko.dev/dima/qb/bin"
bin "gordenko.dev/dima/bin/little"
"gordenko.dev/dima/qb"
)
type ReverseInstantDeltaDecompressor struct {
buf []byte
pos int
bound int
firstValue float64
lastValue float64
length uint16
coef float64
idxOf8 uint
s8 byte
type InstantDeltaCompressor struct {
buf []byte
coef float64
pos int
baseValue float64
lastDelta int64
h byte
state *InstantDeltaCapturedState
}
func NewReverseInstantDeltaDecompressor(buf []byte, fracDigits byte) *ReverseInstantDeltaDecompressor {
func NewInstantDeltaCompressor(buf []byte, payloadSize int, fracDigits byte) *InstantDeltaCompressor {
var coef float64 = 1
if fracDigits > 0 {
coef = math.Pow(10, float64(fracDigits))
}
return &ReverseInstantDeltaDecompressor{
s := &InstantDeltaCompressor{
buf: buf,
pos: payloadSize,
coef: coef,
pos: len(buf),
}
if payloadSize > 0 {
u64, _, err := bin.GetVarInt64(buf)
if err != nil {
log.Fatalf("bug: get base value: %s", err)
}
s.baseValue = float64(u64) / s.coef
s.pos--
s.h = s.buf[s.pos]
var n int
s.lastDelta, n, err = bin.ReverseGetVarInt64(s.buf[:s.pos])
if err != nil {
log.Fatalf("bug: get last delta: %s", err)
}
s.pos -= n
}
return s
}
// func (s *InstantDeltaCompressor) Size() int {
// return s.pos
// }
func (s *InstantDeltaCompressor) Evaluate(value float64) (compressionWay int, requiredSpace int) {
tmp := (value - s.baseValue) * s.coef
if tmp > 0 {
tmp += eps
} else {
tmp -= eps
}
delta := int64(tmp)
if s.pos > 0 {
if s.h < 128 {
// run
if delta == s.lastDelta && s.h < 127 {
compressionWay = incrementRun
requiredSpace += bin.CountVarInt64(s.lastDelta) + // current delta
hSize
} else {
compressionWay = endSeries
requiredSpace += bin.CountVarInt64(s.lastDelta) + // previous delta
hSize + // h - end of run
bin.CountVarInt64(delta) + // new literal
hSize // new h
}
} else {
// literal
if delta != s.lastDelta {
if s.h < 255 {
compressionWay = incrementLiteral
requiredSpace += bin.CountVarInt64(s.lastDelta) + // previous delta
bin.CountVarInt64(delta) + // new delta
hSize
} else {
compressionWay = endSeries
requiredSpace += bin.CountVarInt64(s.lastDelta) + // previous delta
hSize + // h - end of literal
bin.CountVarInt64(delta) + // new literal
hSize // new h
}
} else {
compressionWay = startRun
if s.h > 128 {
requiredSpace += hSize // h - end of literal
}
requiredSpace += bin.CountVarInt64(delta) + // new delta
hSize // new h
}
}
} else {
// encode base value
compressionWay = addBaseValue
requiredSpace = bin.CountVarInt64(int64(value*s.coef)) + // base value
bin.CountVarInt64(delta) + // new delta
+hSize // new h
}
return
}
func (s *InstantDeltaCompressor) Compress(compressionWay int, value float64) {
tmp := (value - s.baseValue) * s.coef
if tmp > 0 {
tmp += eps
} else {
tmp -= eps
}
delta := int64(tmp)
switch compressionWay {
case incrementRun:
s.h++
case incrementLiteral:
// write previous delta and increment counter
n, _ := bin.ReversePutVarInt64(s.buf[s.pos:], s.lastDelta)
s.pos += n
s.lastDelta = delta
s.h++
case endSeries:
n, _ := bin.ReversePutVarInt64(s.buf[s.pos:], s.lastDelta)
s.pos += n
// write h - end of run
s.buf[s.pos] = s.h
s.pos++
// start new literal (length=1)
s.lastDelta = delta
s.h = 128
case startRun:
if s.h > 128 {
// write h - end of literal (because length > 1)
s.h--
s.buf[s.pos] = s.h
s.pos++
}
// start new run (length=2)
s.h = 0
case addBaseValue:
// start new literal (length=1)
n, _ := bin.PutVarInt64(s.buf[s.pos:], int64(value*s.coef))
s.pos += n
s.baseValue = value
// start new literal (length=1)
s.lastDelta = 0
s.h = 128
}
}
func (s *ReverseInstantDeltaDecompressor) NextValue() (value float64, done bool) {
if s.length > 0 {
s.length--
return s.lastValue, false
func (s *InstantDeltaCompressor) DeleteLast() {}
type InstantDeltaCapturedState struct {
H byte
LastDelta int64
Payload []byte
}
func (s *InstantDeltaCompressor) CaptureState() {
if s.state != nil {
qb.Abort(qb.RepeatableLock, nil)
}
if s.pos < s.bound {
// позиція посувається вліво, отже може перескочити на попередній chunk
s.state = &InstantDeltaCapturedState{
H: s.h,
LastDelta: s.lastDelta,
Payload: s.buf[:s.pos],
}
}
// fix - повернути в Pool буфери
func (s *InstantDeltaCompressor) ForgetCapturedState() {
s.state = nil
}
func (s *InstantDeltaCompressor) Offset() int {
// if s.state != nil {
// return s.state.Pos
// }
return 0
}
// Snapshot - для створення снапшота.
func (s *InstantDeltaCompressor) Snapshot() (left []byte, right []byte) {
if s.state == nil {
left = s.buf[:s.pos]
right = s.encodeTail(s.lastDelta, s.h)
} else {
left = s.state.Payload
right = s.encodeTail(s.state.LastDelta, s.state.H)
}
return
}
func (s *InstantDeltaCompressor) encodeTail(lastDelta int64, h byte) []byte {
tail := make([]byte, 10) // max var uint64 + h
n, _ := bin.PutVarInt64(tail, lastDelta)
tail[n] = h
return tail[:n+1]
}
func (s *InstantDeltaCompressor) Rotate(newbuf []byte) (payloadSize int) {
n, _ := bin.PutVarInt64(s.buf[s.pos:], s.lastDelta)
s.pos += n
s.buf[s.pos] = s.h
s.pos++
payloadSize = s.pos
// УВАГА!
// state не чіпаємо
s.buf = newbuf
s.pos = 0
s.baseValue = 0
s.lastDelta = 0
s.h = 0
return
}
func (s *InstantDeltaCompressor) CreateDecompressor() qb.ValueDecompressor {
var (
h = s.h
lastDelta = s.lastDelta
payload = s.buf[:s.pos]
)
if s.state != nil {
h = s.state.H
lastDelta = s.state.LastDelta
payload = s.state.Payload
}
return NewInstantDeltaDecompressorFromState(InstantDeltaDecompressorFromStateOptions{
Coef: s.coef,
H: h,
LastDelta: lastDelta,
Payload: payload,
})
}
func (s *InstantDeltaCompressor) Chunks() []byte {
return s.buf
}
// DECOMPRESSOR
type InstantDeltaDecompressor struct {
buf []byte
coef float64
pos int
bound int
baseValue float64
lastValue float64
isRun bool
pending int
done bool
}
func NewInstantDeltaDecompressor(buf []byte, fracDigits byte) *InstantDeltaDecompressor {
var coef float64 = 1
if fracDigits > 0 {
coef = math.Pow(10, float64(fracDigits))
}
i64, n, err := bin.GetVarInt64(buf)
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)
s := &InstantDeltaDecompressor{
buf: buf,
coef: coef,
pos: len(buf), // first free
baseValue: float64(i64) / coef,
bound: n,
}
s.readHeader()
s.readValue()
return s
}
type InstantDeltaDecompressorFromStateOptions struct {
Coef float64
H byte
LastDelta int64
Payload []byte
}
func NewInstantDeltaDecompressorFromState(opt InstantDeltaDecompressorFromStateOptions) *InstantDeltaDecompressor {
i64, n, err := bin.GetVarInt64(opt.Payload)
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)
s := &InstantDeltaDecompressor{
buf: opt.Payload,
coef: opt.Coef,
pos: len(opt.Payload), // first free
baseValue: float64(i64) / opt.Coef,
bound: n,
}
s.lastValue = s.baseValue + float64(opt.LastDelta)/s.coef
s.decodeHeaderByte(opt.H)
//fmt.Printf("restore from bound: isRun=%t, pending=%d\n", s.isRun, s.pending)
return s
}
func (s *InstantDeltaDecompressor) 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
}
if s.pos == len(s.buf) {
u64, n, err := bin.GetVarInt64(s.buf)
if err != nil {
panic(err)
// метод працює як do while - спочатку значення, а потім перевірка умови
value = s.lastValue
s.pending--
if s.pending > 0 {
// якщо в серії залишаються елементи
if !s.isRun {
s.readValue()
}
s.firstValue = float64(u64) / s.coef
s.bound = n
s.pos--
s.idxOf8 = uint(8 - s.buf[s.pos])
s.pos--
s.s8 = s.buf[s.pos]
s.pos--
s.readVar()
if s.length > 0 {
s.length--
}
return s.lastValue, false
}
if s.idxOf8 == 0 {
s.s8 = s.buf[s.pos]
s.pos--
}
s.readVar()
if s.length > 0 {
s.length--
}
return s.lastValue, false
}
func (s *ReverseInstantDeltaDecompressor) readVar() {
i64, n, err := bin.ReverseGetVarInt64(s.buf[:s.pos+1])
if err != nil {
panic(err)
}
s.pos -= n
s.lastValue = s.firstValue + float64(i64)/s.coef
var flag byte = 1 << s.idxOf8
if (s.s8 & flag) == flag {
s.decodeLength()
}
if s.idxOf8 == 7 {
s.idxOf8 = 0
} else if s.pos > s.bound {
// в серії більше немає елементів, отже перевіряє чи є ще дані в буфері.
// дані є - читаю заголовок наступної серії
s.readHeader()
s.readValue()
} else {
s.idxOf8++
s.done = true
}
return value, false
}
func (s *ReverseInstantDeltaDecompressor) decodeLength() {
b1 := s.buf[s.pos]
func (s *InstantDeltaDecompressor) readHeader() {
s.pos--
if b1 < 128 {
s.length = uint16(b1)
h := s.buf[s.pos]
s.decodeHeaderByte(h)
// fmt.Println("h:", h)
// fmt.Println("isRun:", s.isRun)
// fmt.Println("pending:", s.pending)
}
func (s *InstantDeltaDecompressor) readValue() {
i64, n, err := bin.ReverseGetVarInt64(s.buf[:s.pos])
if err != nil {
log.Fatalln(err)
}
// fmt.Println()
// fmt.Println("read from pos:", s.pos)
// fmt.Println("read delta:", u64)
// fmt.Println("read delta n:", n)
// fmt.Println()
s.pos -= n
s.lastValue = s.baseValue + float64(i64)/s.coef
}
func (s *InstantDeltaDecompressor) decodeHeaderByte(h byte) {
s.isRun = h < 128
if s.isRun {
s.pending = int(h&127) + 2
} else {
b2 := s.buf[s.pos]
s.pos--
s.length = uint16(b1&127) | (uint16(b2) << 7)
}
s.length += 2
}
func GetValueBounds(valuesBuf []byte, metricType octopus.MetricType, fracDigits byte) (sinceValue, untilValue float64) {
var decompressor octopus.ValueDecompressor
switch metricType {
case octopus.Instant:
decompressor = NewReverseInstantDeltaDecompressor(valuesBuf, fracDigits)
case octopus.Cumulative:
decompressor = NewReverseCumulativeDeltaDecompressor(valuesBuf, fracDigits)
default:
panic(fmt.Sprintf("unknown metricType %d", metricType))
}
value, done := decompressor.NextValue()
if done {
return
}
sinceValue = value
untilValue = value
for {
value, done = decompressor.NextValue()
if done {
return
}
sinceValue = value
s.pending = int(h&127) + 1
}
}
// DECOMPRESSOR
// type ReverseInstantDeltaDecompressor struct {
// buf *conbuf.ContinuousBuffer
// pos int
// bound int
// baseValue float64
// lastValue float64
// coef float64
// isRun bool
// pending int
// }
// func NewReverseInstantDeltaDecompressor(buf *conbuf.ContinuousBuffer, size int, fracDigits byte) *ReverseInstantDeltaDecompressor {
// var coef float64 = 1
// if fracDigits > 0 {
// coef = math.Pow(10, float64(fracDigits))
// }
// u64, n, err := buf.GetVarInt64(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)
// return &ReverseInstantDeltaDecompressor{
// buf: buf,
// coef: coef,
// pos: size - 1, // last elem
// baseValue: float64(u64) / coef,
// bound: n,
// }
// }
// func (s *ReverseInstantDeltaDecompressor) NextValue() (value float64, done bool) {
// //fmt.Printf("NextValue(): bound: %d, pos: %d, pending: %d\n", s.bound, s.pos, s.pending)
// if s.pending > 0 {
// // якщо в серії залишаються елементи
// if !s.isRun {
// s.readValue()
// }
// s.pending--
// return s.lastValue, false
// }
// if s.pos > s.bound {
// // читаю заголовок наступної серії
// s.readHeader()
// s.readValue()
// s.pending--
// return s.lastValue, false
// }
// // серія завершена - перевіряю чи є ще серії
// return 0, true
// }
// func (s *ReverseInstantDeltaDecompressor) readHeader() {
// h := s.buf.GetByte(s.pos)
// s.pos--
// s.isRun = h < 128
// if s.isRun {
// s.pending = int(h&127) + 2
// } else {
// s.pending = int(h&127) + 1
// }
// // fmt.Println("h:", h)
// // fmt.Println("isRun:", s.isRun)
// // fmt.Println("pending:", s.pending)
// }
// func (s *ReverseInstantDeltaDecompressor) readValue() {
// i64, n, err := s.buf.ReverseGetVarInt64(s.pos)
// if err != nil {
// log.Fatalln(err)
// }
// // fmt.Println()
// // fmt.Println("read from pos:", s.pos)
// // fmt.Println("read delta:", u64)
// // fmt.Println("read delta n:", n)
// // fmt.Println()
// s.pos -= n
// s.lastValue = s.baseValue + float64(i64)/s.coef
// }
// func (s *InstantDeltaCompressor) Append(value float64) {
// if s.pos == 0 {
// // base value
// n, _ := bin.PutVarInt64(s.buf[s.pos:], int64(value*s.coef))
// s.pos += n
// s.baseValue = value
// s.appendNewLiteral(0)
// } else {
// tmp := (value - s.baseValue) * s.coef
// if tmp > 0 {
// tmp += eps
// } else {
// tmp -= eps
// }
// delta := int64(tmp)
// if delta == s.lastDelta {
// if s.h < 128 {
// // run блок - отже треба збільшити лічильник
// if s.h < 127 {
// // increase counter
// s.h++
// s.buf[s.pos-1] = s.h
// } else {
// // не можу збільшити - буде переповнення. Додаю новий literal блок
// // counter overflow
// // fix encode delta
// s.appendNewLiteral(delta)
// }
// } else {
// // literal блок.
// // Якщо в ньому лише одне значення - перетворюю його на run блок.
// // Інакше забираю останнє значення із literal блока і додаю новий run блок.
// q := s.h & 127
// if q == 0 { // 1 кодується як 0
// s.convertLiteralToRun()
// } else {
// s.convertLastFromLiteralToRun()
// }
// }
// } else {
// if s.h < 127 {
// // 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)
// }
// }
// }
// }
// }

377
enc/time_delta.go Normal file
View File

@@ -0,0 +1,377 @@
package enc
import (
"log"
bin "gordenko.dev/dima/bin/little"
"gordenko.dev/dima/qb"
)
/*
Payload data файла має таку структуру:
vvvvvvvv-> <-ttttttt
де v - це values, які додаються зліва направо, а читаються справа наліво;
t - це timestamps, які додаються справа наліво, а читаються зліва направо.
Timestamps читаються звичайними методами Get*, а писатись мають типу ByRightBound
*/
type TimeDeltaCompressor struct {
buf []byte
// останній записаний байт, якщо рахувати справа наліво
pos int
lastUnixtime uint32
lastDelta uint32
h byte
state *TimeDeltaCapturedState
}
// Кодує значення справа наліво футнкціями TailPut*. Читає значення зліва направо функціями Get*
func NewTimeDeltaCompressor(buf []byte, payloadSize int) *TimeDeltaCompressor {
s := &TimeDeltaCompressor{
buf: buf,
pos: len(buf) - payloadSize,
}
if payloadSize > 0 {
var err error
s.lastUnixtime, err = bin.GetUint32(s.buf[s.pos:])
if err != nil {
log.Fatalf("bug: get last unixtime: %s", err)
}
s.pos += 4
if s.pos < len(buf) {
s.h = s.buf[s.pos]
s.pos++
u64, n, err := bin.GetVarUint64(s.buf[s.pos:])
if err != nil {
log.Fatalf("bug: get last delta: %s", err)
}
s.lastDelta = uint32(u64)
s.pos += n
}
}
return s
}
// func (s *TimeDeltaCompressor) Size() int {
// return len(s.buf) - s.pos
// }
// retrun
func (s *TimeDeltaCompressor) Evaluate(unixtime uint32) (compressionWay int, requiredSpace int) {
requiredSpace = 4 // last unixtime
if s.lastUnixtime > 0 {
delta := unixtime - s.lastUnixtime
if s.lastDelta > 0 {
// 3rd value
if s.h < 128 {
// run
if delta == s.lastDelta && s.h < 127 {
compressionWay = incrementRun
requiredSpace += bin.CountVarUint64(uint64(s.lastDelta)) + // current delta
hSize
} else {
compressionWay = endSeries
requiredSpace += bin.CountVarUint64(uint64(s.lastDelta)) + // previous delta
hSize + // h - end of run
bin.CountVarUint64(uint64(delta)) + // new literal
hSize // new h
}
} else {
// literal
if delta != s.lastDelta {
if s.h < 255 {
compressionWay = incrementLiteral
requiredSpace += bin.CountVarUint64(uint64(s.lastDelta)) + // previous delta
bin.CountVarUint64(uint64(delta)) + // new delta
hSize
} else {
compressionWay = endSeries
requiredSpace += bin.CountVarUint64(uint64(s.lastDelta)) + // previous delta
hSize + // h - end of literal
bin.CountVarUint64(uint64(delta)) + // new literal
hSize // new h
}
} else {
compressionWay = startRun
if s.h > 128 {
requiredSpace += hSize // h - end of literal
}
requiredSpace += bin.CountVarUint64(uint64(delta)) + // new delta
hSize // new h
}
}
} else {
compressionWay = add1stDelta
requiredSpace += bin.CountVarUint64(uint64(delta)) + // new literal
hSize // new h
}
} else {
compressionWay = addUnixtime
}
return
}
func (s *TimeDeltaCompressor) Compress(compressionWay int, unixtime uint32) {
delta := unixtime - s.lastUnixtime
switch compressionWay {
case incrementRun:
s.h++
case incrementLiteral:
// write previous delta and increment counter
n, _ := bin.TailPutVarUint64(s.buf[:s.pos], uint64(s.lastDelta))
s.pos -= n
s.lastDelta = delta
s.h++
case endSeries:
n, _ := bin.TailPutVarUint64(s.buf[:s.pos], uint64(s.lastDelta))
s.pos -= n
// write h - end of run
s.pos--
s.buf[s.pos] = s.h
// start new literal (length=1)
s.lastDelta = delta
s.h = 128
case startRun:
if s.h > 128 {
// write h - end of literal (because length > 1)
s.h--
s.pos--
s.buf[s.pos] = s.h
}
// start new run (length=2)
s.h = 0
case add1stDelta:
// start new literal (length=1)
s.lastDelta = delta
s.h = 128
}
// 1st value or update after every update
// do not write immediatelly because of update after every update
s.lastUnixtime = unixtime
}
func (s *TimeDeltaCompressor) DeleteLast() {
}
// FIX - check methods
type TimeDeltaCapturedState struct {
H byte
LastUnixtime uint32
LastDelta uint32
Payload []byte
}
// delta h
func (s *TimeDeltaCompressor) CaptureState() {
if s.state != nil {
qb.Abort(qb.RepeatableLock, nil)
}
// позиція посувається вліво, отже може перескочити на попередній chunk
s.state = &TimeDeltaCapturedState{
H: s.h,
LastUnixtime: s.lastUnixtime,
LastDelta: s.lastDelta,
Payload: s.buf[s.pos:],
}
}
// fix - повернути в Pool буфери
func (s *TimeDeltaCompressor) ForgetCapturedState() {
s.state = nil
}
// fix
func (s *TimeDeltaCompressor) Offset() int {
// if s.state != nil {
// return s.state.Pos
// }
return 0
}
// Snapshot - для створення снапшота.
func (s *TimeDeltaCompressor) Snapshot() (left []byte, right []byte) {
if s.state == nil {
left = s.encodeTail(s.lastUnixtime, s.lastDelta, s.h)
right = s.buf[s.pos:]
} else {
left = s.encodeTail(s.state.LastUnixtime, s.state.LastDelta, s.state.H)
right = s.state.Payload
}
return
}
func (s *TimeDeltaCompressor) encodeTail(lastUnixtime, lastDelta uint32, h byte) []byte {
tail := make([]byte, 9)
bin.PutUint32(tail, lastUnixtime)
tail[4] = h
n, _ := bin.PutVarUint64(tail[5:], uint64(lastDelta))
return tail[:n+5]
}
func (s *TimeDeltaCompressor) Rotate(newbuf []byte) (payloadSize int) {
var n int
n, _ = bin.TailPutVarUint64(s.buf[:s.pos], uint64(s.lastDelta))
s.pos -= n
s.pos--
s.buf[s.pos] = s.h
n, _ = bin.TailPutVarUint64(s.buf[:s.pos], uint64(s.lastUnixtime))
s.pos -= n
payloadSize = len(s.buf) - s.pos
// УВАГА!
// state не чіпаємо
s.buf = newbuf
s.pos = len(s.buf)
s.lastUnixtime = 0
s.lastDelta = 0
s.h = 0
return
}
func (s *TimeDeltaCompressor) CreateDecompressor() qb.TimestampDecompressor {
var (
h = s.h
lastUnixtime = s.lastUnixtime
lastDelta = s.lastDelta
payload = s.buf[s.pos:]
)
if s.state != nil {
h = s.state.H
lastUnixtime = s.state.LastUnixtime
lastDelta = s.state.LastDelta
payload = s.state.Payload
}
return NewTimeDeltaDecompressorFromState(TimeDeltaDecompressorFromStateOptions{
H: h,
LastUnixtime: lastUnixtime,
LastDelta: lastDelta,
Payload: payload,
})
}
func (s *TimeDeltaCompressor) Chunks() []byte {
return s.buf
}
// DECOMPRESSOR
type TimeDeltaDecompressor struct {
buf []byte
pos int
lastDelta uint32
lastUnixtime uint32
isRun bool
pending int
done bool
}
func NewTimeDeltaDecompressor(buf []byte) *TimeDeltaDecompressor {
s := &TimeDeltaDecompressor{
buf: buf,
}
if s.pos < len(s.buf) {
var err error
s.lastUnixtime, err = bin.GetUint32(s.buf)
if err != nil {
log.Fatalf("bug: get last unixtime: %s", err)
}
s.pos += 4
//fmt.Println("restored last unixtime", s.lastUnixtime)
} else {
s.done = true
}
return s
}
type TimeDeltaDecompressorFromStateOptions struct {
H byte
LastUnixtime uint32
LastDelta uint32
Payload []byte
}
func NewTimeDeltaDecompressorFromState(opt TimeDeltaDecompressorFromStateOptions) *TimeDeltaDecompressor {
s := &TimeDeltaDecompressor{
buf: opt.Payload,
lastUnixtime: opt.LastUnixtime,
}
if opt.LastDelta > 0 {
s.lastDelta = opt.LastDelta
s.decodeHeaderByte(opt.H)
}
//fmt.Println("-------------------")
//fmt.Printf("restore from bound: isRun=%t, pending=%d, lastUnix=%d, lastDelta=%d\n",
//s.isRun, s.pending, s.lastUnixtime, s.lastDelta)
//fmt.Printf("buf: %d\n", s.buf)
return s
}
func (s *TimeDeltaDecompressor) NextValue() (value uint32, done bool) {
//fmt.Printf("NextValue(): pos: %d, isRegular: %t, pending: %d\n", s.pos, s.isRegular, s.pending)
if s.done {
return 0, true
}
// повертаю значення, що було прочитано в методі RestoreFromBound/RestoreFromEnd
value = s.lastUnixtime
if s.lastDelta > 0 {
s.lastUnixtime -= s.lastDelta
s.pending--
//fmt.Printf("lastUnix: %d, s.pending: %d\n", s.lastUnixtime, s.pending)
if s.pending > 0 {
// якщо в серії залишаються елементи
if !s.isRun {
s.readDelta()
}
} else if s.pos < len(s.buf) {
// в серії більше немає елементів, отже перевіряє чи є ще дані в буфері.
// дані є - читаю заголовок наступної серії
s.readHeader()
s.readDelta()
} else {
//s.done = true
s.lastDelta = 0
}
} else {
// був закодований лише last unixtime
s.done = true
}
return value, false
}
func (s *TimeDeltaDecompressor) readHeader() {
h := s.buf[s.pos]
s.pos++
s.decodeHeaderByte(h)
// fmt.Println()
// fmt.Println("read from pos:", s.pos)
// fmt.Println("h:", h)
// fmt.Println("isRun:", s.isRun)
// fmt.Println("pending:", s.pending)
// fmt.Println()
}
func (s *TimeDeltaDecompressor) decodeHeaderByte(h byte) {
s.isRun = h < 128
if s.isRun {
s.pending = int(h) + 2
} else {
s.pending = int(h&127) + 1
}
}
func (s *TimeDeltaDecompressor) readDelta() {
u64, n, err := bin.GetVarUint64(s.buf[s.pos:])
if err != nil {
log.Fatalln(err)
}
// fmt.Println()
// fmt.Println("read from pos:", s.pos)
// fmt.Println("read delta:", u64)
// fmt.Println("read delta n:", n)
// fmt.Println()
s.pos += n
s.lastDelta = uint32(u64)
}

View File

@@ -1,145 +0,0 @@
package enc
import (
"gordenko.dev/dima/qb/bin"
)
// REVERSE
const (
lastUnixtimeIdx = 0
baseDeltaIdx = 4
)
type ReverseTimeDeltaOfDeltaDecompressor struct {
step byte
buf []byte
pos int
bound int
lastUnixtime uint32
baseDelta uint32
lastDeltaOfDelta int64
length uint16
idxOf8 uint
s8 byte
}
func NewReverseTimeDeltaOfDeltaDecompressor(buf []byte) *ReverseTimeDeltaOfDeltaDecompressor {
return &ReverseTimeDeltaOfDeltaDecompressor{
buf: buf,
pos: len(buf),
}
}
func (s *ReverseTimeDeltaOfDeltaDecompressor) NextValue() (value uint32, done bool) {
if s.step == 0 {
if s.pos == 0 {
return 0, true
}
s.lastUnixtime = bin.GetUint32(s.buf[lastUnixtimeIdx:])
s.step = 1
return s.lastUnixtime, false
}
if s.step == 1 {
if s.pos == baseDeltaIdx {
return 0, true
}
u64, n, err := bin.GetVarUint64(s.buf[baseDeltaIdx:])
if err != nil {
panic("EOF")
}
s.bound = baseDeltaIdx + n
s.baseDelta = uint32(u64)
s.pos--
s.idxOf8 = uint(8 - s.buf[s.pos])
s.pos--
s.s8 = s.buf[s.pos]
s.pos--
s.readVar()
if s.length > 0 {
s.length--
}
s.step = 2
return s.lastUnixtime, false
}
if s.length > 0 {
s.length--
delta := int64(s.baseDelta) + s.lastDeltaOfDelta
s.lastUnixtime = uint32(int64(s.lastUnixtime) - delta)
return s.lastUnixtime, false
}
if s.pos < s.bound {
return 0, true
}
if s.idxOf8 == 0 {
s.s8 = s.buf[s.pos]
s.pos--
}
s.readVar()
if s.length > 0 {
s.length--
}
return s.lastUnixtime, false
}
func GetTimeRange(timestampsBuf []byte) (since, until uint32) {
decompressor := NewReverseTimeDeltaOfDeltaDecompressor(timestampsBuf)
value, done := decompressor.NextValue()
if done {
return
}
since = value
until = value
for {
value, done = decompressor.NextValue()
if done {
return
}
since = value
}
}
func (s *ReverseTimeDeltaOfDeltaDecompressor) readVar() {
var (
n int
err error
)
s.lastDeltaOfDelta, n, err = bin.ReverseGetVarInt64(s.buf[:s.pos+1])
if err != nil {
panic(err)
}
s.pos -= n
delta := int64(s.baseDelta) + s.lastDeltaOfDelta
s.lastUnixtime = uint32(int64(s.lastUnixtime) - delta)
var flag byte = 1 << s.idxOf8
if (s.s8 & flag) == flag {
s.decodeLength()
}
if s.idxOf8 == 7 {
s.idxOf8 = 0
} else {
s.idxOf8++
}
}
func (s *ReverseTimeDeltaOfDeltaDecompressor) decodeLength() {
b1 := s.buf[s.pos]
s.pos--
if b1 < 128 {
s.length = uint16(b1)
} else {
b2 := s.buf[s.pos]
s.pos--
s.length = uint16(b1&127) | (uint16(b2) << 7)
}
s.length += 2
}