-
Notifications
You must be signed in to change notification settings - Fork 0
/
compression.go
71 lines (60 loc) · 1.79 KB
/
compression.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
package osrscache
import (
"bytes"
"compress/bzip2"
"compress/gzip"
"fmt"
"io"
)
const (
CompressionNone = 0
CompressionBZIP2 = 1
CompressionGZIP = 2
)
func DecompressData(data []byte) ([]byte, error) {
reader := NewReader(data)
compressionType, err := reader.ReadByte()
if err != nil {
return nil, fmt.Errorf("failed to read compression type: %w", err)
}
compressedLength, err := reader.ReadUint32()
if err != nil {
return nil, fmt.Errorf("failed to read compressed length: %w", err)
}
if compressionType == CompressionNone {
uncompressedData := make([]byte, compressedLength)
_, err := io.ReadFull(reader, uncompressedData)
if err != nil {
return nil, fmt.Errorf("failed to read uncompressed data: %w", err)
}
return uncompressedData, nil
}
uncompressedLength, err := reader.ReadUint32()
if err != nil {
return nil, fmt.Errorf("failed to read uncompressed length: %w", err)
}
if uint32(reader.Len()) < compressedLength {
return nil, fmt.Errorf("archive data shorter than expected: %d < %d", reader.Len(), compressedLength)
}
var decompressor io.Reader
switch compressionType {
case CompressionGZIP:
gzipReader, err := gzip.NewReader(reader)
if err != nil {
return nil, fmt.Errorf("failed to create gzip reader: %w", err)
}
defer gzipReader.Close()
decompressor = gzipReader
case CompressionBZIP2:
bzip2Header := []byte{'B', 'Z', 'h', '1'}
decompressor = bzip2.NewReader(io.MultiReader(bytes.NewReader(bzip2Header), reader))
default:
return nil, fmt.Errorf("unknown compression type: %d", compressionType)
}
uncompressedData := make([]byte, uncompressedLength)
n, err := io.ReadFull(decompressor, uncompressedData)
if err != nil {
return nil, fmt.Errorf("failed to decompress data (read %d bytes): %w", n, err)
}
return uncompressedData, nil
}