-
Notifications
You must be signed in to change notification settings - Fork 1
/
compress.go
106 lines (85 loc) · 1.83 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
package cypress
import (
"bufio"
"bytes"
"compress/zlib"
"io"
"github.com/golang/snappy"
)
// No compression is applied
var NONE = StreamHeader_NONE
// Snappy compression is used
var SNAPPY = StreamHeader_SNAPPY
// ZLib compression is used
var ZLIB = StreamHeader_ZLIB
const defaultSnappyChunkBuffer = 1024 * 10
type snappyWriter struct {
*snappy.Writer
chunkBuffer int
buf bytes.Buffer
}
func (s *snappyWriter) Write(data []byte) (int, error) {
n, err := s.buf.Write(data)
if err != nil {
return 0, err
}
if s.buf.Len() < s.chunkBuffer {
return n, nil
}
_, err = s.Writer.Write(s.buf.Bytes())
if err != nil {
return 0, err
}
s.buf.Reset()
return n, nil
}
func (s *snappyWriter) Flush() error {
if s.buf.Len() > 0 {
_, err := s.Writer.Write(s.buf.Bytes())
s.buf.Reset()
return err
}
return nil
}
func (s *snappyWriter) Close() error {
return s.Flush()
}
type bufWriter struct {
*bufio.Writer
}
func (b *bufWriter) Close() error {
return b.Flush()
}
// Given a compression level, return a wrapped Writer
func WriteCompressed(w io.WriteCloser, comp StreamHeader_Compression) io.WriteCloser {
switch comp {
case StreamHeader_NONE:
return &bufWriter{bufio.NewWriter(w)}
case StreamHeader_SNAPPY:
return &snappyWriter{
Writer: snappy.NewWriter(w),
chunkBuffer: defaultSnappyChunkBuffer,
}
case StreamHeader_ZLIB:
return zlib.NewWriter(w)
default:
panic("unknown compression requested")
}
}
// Given a compression level, return a wrapped Reader
func ReadCompressed(r io.Reader, comp StreamHeader_Compression) io.Reader {
switch comp {
case StreamHeader_NONE:
return r
case StreamHeader_SNAPPY:
return snappy.NewReader(r)
case StreamHeader_ZLIB:
zw, err := zlib.NewReader(r)
if err != nil {
panic(err)
}
return zw
default:
panic("unknown compression requested")
}
}