Repository navigation
Expand file tree
/
Copy pathcompress.go
More file actions
117 lines (95 loc) · 2.08 KB
/
Copy pathcompress.go
File metadata and controls
117 lines (95 loc) · 2.08 KB
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
package lz10
import (
"bytes"
"encoding/binary"
"math"
)
type compressionContext struct {
decompressed *[]byte
position int
index int
length int
}
func (c *compressionContext) Search(length, position *int) {
*length = Threshold
if c.index >= MaxOffset {
c.position = MaxOffset
} else {
c.position = c.index
}
for ; c.position > VRAMCompatible; c.position-- {
for c.length = 0; c.length < MaxCoded; c.length++ {
if c.index+c.length == len(*c.decompressed) {
break
}
if c.index+c.length >= len(*c.decompressed) {
break
}
if (*c.decompressed)[c.index+c.length] != (*c.decompressed)[c.index+c.length-c.position] {
break
}
}
if c.length > *length {
*position = c.position
*length = c.length
if *length == MaxCoded {
break
}
}
}
}
func Compress(data []byte) ([]byte, error) {
compressed := new(bytes.Buffer)
err := binary.Write(compressed, binary.LittleEndian, uint32(FileMagic|len(data)<<8))
if err != nil {
return nil, ErrFailedBufferWrite
}
var ctx compressionContext
ctx.decompressed = &data
var mask int
var flag int
var lenBest int
var posBest int
var lenNext int
var posNext int
var lenPost int
var posPost int
for ctx.index < len(data) {
mask >>= BitShiftCount
if mask == 0 {
compressed.WriteByte(0)
flag = compressed.Len() - 1
mask = DefaultMask
}
ctx.Search(&lenBest, &posBest)
if ctx.index+lenBest < len(data) {
ctx.index += lenBest
ctx.Search(&lenNext, &posNext)
ctx.index -= lenBest - 1
ctx.Search(&lenPost, &posPost)
ctx.index--
if lenNext <= Threshold {
lenNext = 1
}
if lenPost <= Threshold {
lenPost = 1
}
if lenBest+lenNext <= 1+lenPost {
lenBest = 1
}
}
if lenBest > Threshold {
ctx.index += lenBest
compressed.Bytes()[flag] |= byte(mask)
_bytes := []byte{
byte(((lenBest - (Threshold + 1)) << 4) | ((posBest - 1) >> 8)),
byte((posBest - 1) & math.MaxUint8),
}
compressed.Write(_bytes)
} else {
compressed.WriteByte(data[ctx.index])
ctx.index++
}
}
return compressed.Bytes(), nil
}