forked from sv/kdbgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compress.go
143 lines (137 loc) · 2.13 KB
/
compress.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package kdb
import (
"bytes"
"encoding/binary"
)
// Compress b using Q IPC compression
func Compress(b []byte) (dst []byte) {
if len(b) <= 17 {
return b
}
i := byte(0)
f, h0, h := byte(0), byte(0), byte(0)
g := false
dst = make([]byte, len(b)/2)
lenbuf := make([]byte, 4)
c := 12
d := c
e := len(dst)
p := int32(0)
q, r, s0 := int32(0), int32(0), int32(0)
s := int32(8)
t := int32(len(b))
a := make([]int32, 256)
copy(dst[:4], b[:4])
dst[2] = 1
binary.LittleEndian.PutUint32(lenbuf, uint32(len(b)))
copy(dst[8:], lenbuf)
for ; s < t; i *= 2 {
if 0 == i {
if d > e-17 {
return b
}
i = 1
dst[c] = f
c = d
d++
f = 0
}
g = (s > t-3)
if !g {
h = b[s] ^ b[s+1]
p = a[h]
g = (0 == p) || (0 != (b[s] ^ b[p]))
}
if 0 < s0 {
a[h0] = s0
s0 = 0
}
if g {
h0 = h
s0 = s
dst[d] = b[s]
d++
s++
} else {
a[h] = s
f |= i
p += 2
s += 2
r = s
q = min32(s+255, t)
for s < q && b[p] == b[s] {
s++
if s < q {
p++
}
}
dst[d] = h
d++
dst[d] = byte(s - r)
d++
}
}
dst[c] = f
binary.LittleEndian.PutUint32(lenbuf, uint32(d))
copy(dst[4:], lenbuf)
return dst[:d:d]
}
func min32(a, b int32) int32 {
if a > b {
return b
}
return a
}
// Uncompress byte array compressed with Q IPC compression
func Uncompress(b []byte) (dst []byte) {
if len(b) < 4+1 {
return b
}
n, r, f, s := int32(0), int32(0), int32(0), int32(8)
p := s
i := int16(0)
var usize int32
binary.Read(bytes.NewReader(b[0:4]), binary.LittleEndian, &usize)
dst = make([]byte, usize)
d := int32(4)
aa := make([]int32, 256)
for int(s) < len(dst) {
if i == 0 {
f = 0xff & int32(b[d])
d++
i = 1
}
if (f & int32(i)) != 0 {
r = aa[0xff&int32(b[d])]
d++
dst[s] = dst[r]
s++
r++
dst[s] = dst[r]
s++
r++
n = 0xff & int32(b[d])
d++
for m := int32(0); m < n; m++ {
dst[s+m] = dst[r+m]
}
} else {
dst[s] = b[d]
s++
d++
}
for p < s-1 {
aa[(0xff&int32(dst[p]))^(0xff&int32(dst[p+1]))] = p
p++
}
if (f & int32(i)) != 0 {
s += n
p = s
}
i *= 2
if i == 256 {
i = 0
}
}
return dst
}