-
Notifications
You must be signed in to change notification settings - Fork 7
/
Decompress.go
67 lines (57 loc) · 1.61 KB
/
Decompress.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
package rle
import (
"io"
"github.com/inkyblackness/hacked/ss1"
)
const (
errUndefinedCase ss1.StringError = "undefined case 80 nn C0"
)
// Decompress decompresses from the given reader and writes into the provided output buffer.
// The output buffer must be pre-allocated.
// If it contains non-zero data, this data may be preserved if the compressed data specifies to.
func Decompress(reader io.Reader, output []byte) (err error) {
outIndex := 0
done := false
nextByte := func() byte {
zz := []byte{0x00}
_, err = reader.Read(zz)
return zz[0]
}
for !done && (err == nil) {
first := nextByte()
switch {
case first == 0x00:
nn := nextByte()
zz := nextByte()
outIndex += writeBytesOfValue(output[outIndex:outIndex+int(nn)], func() byte { return zz })
case first < 0x80:
outIndex += writeBytesOfValue(output[outIndex:outIndex+int(first)], nextByte)
case first == 0x80:
control := uint16(nextByte())
control += uint16(nextByte()) << 8
switch {
case control == 0x0000:
done = true
case control < 0x8000:
outIndex += int(control)
case control < 0xC000:
outIndex += writeBytesOfValue(output[outIndex:outIndex+int(control&0x3FFF)], nextByte)
case (control & 0xFF00) == 0xC000:
err = errUndefinedCase
default:
zz := nextByte()
outIndex += writeBytesOfValue(output[outIndex:outIndex+int(control&0x3FFF)], func() byte { return zz })
}
default:
outIndex += int(first & 0x7F)
}
}
return
}
func writeBytesOfValue(buffer []byte, producer func() byte) int {
count := len(buffer)
for i := 0; i < count; i++ {
buffer[i] = producer()
}
return count
}