...
1
2
3
4
5 package packet
6
7 import (
8 "compress/bzip2"
9 "compress/flate"
10 "compress/zlib"
11 "golang.org/x/crypto/openpgp/errors"
12 "io"
13 "strconv"
14 )
15
16
17
18 type Compressed struct {
19 Body io.Reader
20 }
21
22 const (
23 NoCompression = flate.NoCompression
24 BestSpeed = flate.BestSpeed
25 BestCompression = flate.BestCompression
26 DefaultCompression = flate.DefaultCompression
27 )
28
29
30 type CompressionConfig struct {
31
32
33
34
35
36
37
38
39 Level int
40 }
41
42 func (c *Compressed) parse(r io.Reader) error {
43 var buf [1]byte
44 _, err := readFull(r, buf[:])
45 if err != nil {
46 return err
47 }
48
49 switch buf[0] {
50 case 1:
51 c.Body = flate.NewReader(r)
52 case 2:
53 c.Body, err = zlib.NewReader(r)
54 case 3:
55 c.Body = bzip2.NewReader(r)
56 default:
57 err = errors.UnsupportedError("unknown compression algorithm: " + strconv.Itoa(int(buf[0])))
58 }
59
60 return err
61 }
62
63
64
65
66
67 type compressedWriteCloser struct {
68 sh io.Closer
69 c io.WriteCloser
70 }
71
72 func (cwc compressedWriteCloser) Write(p []byte) (int, error) {
73 return cwc.c.Write(p)
74 }
75
76 func (cwc compressedWriteCloser) Close() (err error) {
77 err = cwc.c.Close()
78 if err != nil {
79 return err
80 }
81
82 return cwc.sh.Close()
83 }
84
85
86
87
88
89
90 func SerializeCompressed(w io.WriteCloser, algo CompressionAlgo, cc *CompressionConfig) (literaldata io.WriteCloser, err error) {
91 compressed, err := serializeStreamHeader(w, packetTypeCompressed)
92 if err != nil {
93 return
94 }
95
96 _, err = compressed.Write([]byte{uint8(algo)})
97 if err != nil {
98 return
99 }
100
101 level := DefaultCompression
102 if cc != nil {
103 level = cc.Level
104 }
105
106 var compressor io.WriteCloser
107 switch algo {
108 case CompressionZIP:
109 compressor, err = flate.NewWriter(compressed, level)
110 case CompressionZLIB:
111 compressor, err = zlib.NewWriterLevel(compressed, level)
112 default:
113 s := strconv.Itoa(int(algo))
114 err = errors.UnsupportedError("Unsupported compression algorithm: " + s)
115 }
116 if err != nil {
117 return
118 }
119
120 literaldata = compressedWriteCloser{compressed, compressor}
121
122 return
123 }
124
View as plain text