1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
11 "golang.org/x/crypto/openpgp/errors"
16 // Compressed represents a compressed OpenPGP packet. The decompressed contents
17 // will contain more OpenPGP packets. See RFC 4880, section 5.6.
18 type Compressed struct {
23 NoCompression = flate.NoCompression
24 BestSpeed = flate.BestSpeed
25 BestCompression = flate.BestCompression
26 DefaultCompression = flate.DefaultCompression
29 // CompressionConfig contains compressor configuration settings.
30 type CompressionConfig struct {
31 // Level is the compression level to use. It must be set to
32 // between -1 and 9, with -1 causing the compressor to use the
33 // default compression level, 0 causing the compressor to use
34 // no compression and 1 to 9 representing increasing (better,
35 // slower) compression levels. If Level is less than -1 or
36 // more then 9, a non-nil error will be returned during
37 // encryption. See the constants above for convenient common
38 // settings for Level.
42 func (c *Compressed) parse(r io.Reader) error {
44 _, err := readFull(r, buf[:])
51 c.Body = flate.NewReader(r)
53 c.Body, err = zlib.NewReader(r)
55 c.Body = bzip2.NewReader(r)
57 err = errors.UnsupportedError("unknown compression algorithm: " + strconv.Itoa(int(buf[0])))
63 // compressedWriterCloser represents the serialized compression stream
64 // header and the compressor. Its Close() method ensures that both the
65 // compressor and serialized stream header are closed. Its Write()
66 // method writes to the compressor.
67 type compressedWriteCloser struct {
68 sh io.Closer // Stream Header
69 c io.WriteCloser // Compressor
72 func (cwc compressedWriteCloser) Write(p []byte) (int, error) {
76 func (cwc compressedWriteCloser) Close() (err error) {
85 // SerializeCompressed serializes a compressed data packet to w and
86 // returns a WriteCloser to which the literal data packets themselves
87 // can be written and which MUST be closed on completion. If cc is
88 // nil, sensible defaults will be used to configure the compression
90 func SerializeCompressed(w io.WriteCloser, algo CompressionAlgo, cc *CompressionConfig) (literaldata io.WriteCloser, err error) {
91 compressed, err := serializeStreamHeader(w, packetTypeCompressed)
96 _, err = compressed.Write([]byte{uint8(algo)})
101 level := DefaultCompression
106 var compressor io.WriteCloser
109 compressor, err = flate.NewWriter(compressed, level)
110 case CompressionZLIB:
111 compressor, err = zlib.NewWriterLevel(compressed, level)
113 s := strconv.Itoa(int(algo))
114 err = errors.UnsupportedError("Unsupported compression algorithm: " + s)
120 literaldata = compressedWriteCloser{compressed, compressor}