1 // Copyright 2009 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.
15 // These constants are copied from the flate package, so that code that imports
16 // "compress/zlib" does not also have to import "compress/flate".
18 NoCompression
= flate
.NoCompression
19 BestSpeed
= flate
.BestSpeed
20 BestCompression
= flate
.BestCompression
21 DefaultCompression
= flate
.DefaultCompression
26 compressor io
.WriteCloser
32 // NewWriter calls NewWriterLevel with the default compression level.
33 func NewWriter(w io
.Writer
) (io
.WriteCloser
, os
.Error
) {
34 return NewWriterLevel(w
, DefaultCompression
)
37 // NewWriterLevel creates a new io.WriteCloser that satisfies writes by compressing data written to w.
38 // It is the caller's responsibility to call Close on the WriteCloser when done.
39 // level is the compression level, which can be DefaultCompression, NoCompression,
40 // or any integer value between BestSpeed and BestCompression (inclusive).
41 func NewWriterLevel(w io
.Writer
, level
int) (io
.WriteCloser
, os
.Error
) {
43 // ZLIB has a two-byte header (as documented in RFC 1950).
44 // The first four bits is the CINFO (compression info), which is 7 for the default deflate window size.
45 // The next four bits is the CM (compression method), which is 8 for deflate.
47 // The next two bits is the FLEVEL (compression level). The four values are:
48 // 0=fastest, 1=fast, 2=default, 3=best.
49 // The next bit, FDICT, is unused, in this implementation.
50 // The final five FCHECK bits form a mod-31 checksum.
61 return nil, os
.NewError("level out of range")
63 _
, err
:= w
.Write(z
.scratch
[0:2])
68 z
.compressor
= flate
.NewWriter(w
, level
)
69 z
.digest
= adler32
.New()
73 func (z
*writer
) Write(p
[]byte) (n
int, err os
.Error
) {
80 n
, err
= z
.compressor
.Write(p
)
89 // Calling Close does not close the wrapped io.Writer originally passed to NewWriter.
90 func (z
*writer
) Close() os
.Error
{
94 z
.err
= z
.compressor
.Close()
98 checksum
:= z
.digest
.Sum32()
99 // ZLIB (RFC 1950) is big-endian, unlike GZIP (RFC 1952).
100 z
.scratch
[0] = uint8(checksum
>> 24)
101 z
.scratch
[1] = uint8(checksum
>> 16)
102 z
.scratch
[2] = uint8(checksum
>> 8)
103 z
.scratch
[3] = uint8(checksum
>> 0)
104 _
, z
.err
= z
.w
.Write(z
.scratch
[0:4])