-
Notifications
You must be signed in to change notification settings - Fork 1
/
compression.go
116 lines (92 loc) · 2.4 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
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
package main
import (
"io"
"os"
"strings"
"github.com/golang/snappy"
)
// Compress a file to a snappy archive.
func snap(src *os.File) (string, error) {
// Get file info.
srcInfo, err := src.Stat()
if err != nil {
return "", err
}
srcName := src.Name()
// Make sure existing files are not overwritten.
dstName := concat(srcName, ".sz")
setDstName(&dstName)
print(concat(srcName, " > ", dstName))
// Create the destination file.
dst, err := create(dstName, srcInfo.Mode())
if err != nil {
return "", err
}
defer dst.Close()
// Set up a *passthru writer in order to print progress.
pt := &passthru{
Writer: dst,
nExpected: uint64(srcInfo.Size()),
}
defer pt.Reset()
// Wrap a *snappy.Writer around the *passthru method.
sz := snappy.NewWriter(pt)
defer sz.Reset(nil)
// Write the source file's contents to the new snappy file.
_, err = snapCopy(sz, src)
print()
if err != nil {
return "", err
}
return dstName, nil
}
// SnappyMaxUncompressedChunkLen is a copy of snappy.maxUncompressedChunkLen
const SnappyMaxUncompressedChunkLen = 65536
// Read data from a source file,
// compress the data,
// and write it to a *snappy.Writer destination file.
// Serves as a makeshift snappy replacement for io.Copy
// as long as the source Reader is an *os.File
// and the destination Writer is a *snappy.Writer.
func snapCopy(sz *snappy.Writer, src *os.File) (int64, error) {
buf := make([]byte, SnappyMaxUncompressedChunkLen)
return io.CopyBuffer(sz, src, buf)
// Slow and dangerous. Kept for testing purposes.
// srcContents, err := ioutil.ReadAll(src)
// if err != nil {
// return
// }
// totalWritten, err = sz.Write(srcContents)
// return int64(totalWritten), err
}
// Decompress a snappy archive.
func unsnap(src *os.File) (string, error) {
srcInfo, err := src.Stat()
if err != nil {
return "", err
}
srcName := srcInfo.Name()
// Make sure existing files are not overwritten.
dstName := strings.TrimSuffix(srcName, ".sz")
setDstName(&dstName)
print(concat(srcName, " > ", dstName))
// Create the destination file.
dst, err := create(dstName, srcInfo.Mode())
if err != nil {
return "", err
}
defer dst.Close()
pt := &passthru{
Reader: src,
nExpected: uint64(srcInfo.Size()),
}
defer pt.Reset()
szr := snappy.NewReader(pt)
defer szr.Reset(nil)
defer print()
_, err = io.Copy(dst, szr)
if err != nil {
return "", err
}
return dstName, nil
}