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.
6 Package zlib implements reading and writing of zlib format compressed data,
7 as specified in RFC 1950.
9 The implementation provides filters that uncompress during reading
10 and compress during writing. For example, to write compressed data
14 w, err := zlib.NewWriter(&b)
15 w.Write([]byte("hello, world\n"))
18 and to read that data back:
20 r, err := zlib.NewReader(&b)
37 var ChecksumError = os.NewError("zlib checksum error")
38 var HeaderError = os.NewError("invalid zlib header")
39 var DictionaryError = os.NewError("invalid zlib dictionary")
43 decompressor io.ReadCloser
49 // NewReader creates a new io.ReadCloser that satisfies reads by decompressing data read from r.
50 // The implementation buffers input and may read more data than necessary from r.
51 // It is the caller's responsibility to call Close on the ReadCloser when done.
52 func NewReader(r io.Reader) (io.ReadCloser, os.Error) {
53 return NewReaderDict(r, nil)
56 // NewReaderDict is like NewReader but uses a preset dictionary.
57 // NewReaderDict ignores the dictionary if the compressed data does not refer to it.
58 func NewReaderDict(r io.Reader, dict []byte) (io.ReadCloser, os.Error) {
60 if fr, ok := r.(flate.Reader); ok {
63 z.r = bufio.NewReader(r)
65 _, err := io.ReadFull(z.r, z.scratch[0:2])
69 h := uint(z.scratch[0])<<8 | uint(z.scratch[1])
70 if (z.scratch[0]&0x0f != zlibDeflate) || (h%31 != 0) {
71 return nil, HeaderError
73 if z.scratch[1]&0x20 != 0 {
74 _, err = io.ReadFull(z.r, z.scratch[0:4])
78 checksum := uint32(z.scratch[0])<<24 | uint32(z.scratch[1])<<16 | uint32(z.scratch[2])<<8 | uint32(z.scratch[3])
79 if checksum != adler32.Checksum(dict) {
80 return nil, DictionaryError
82 z.decompressor = flate.NewReaderDict(z.r, dict)
84 z.decompressor = flate.NewReader(z.r)
86 z.digest = adler32.New()
90 func (z *reader) Read(p []byte) (n int, err os.Error) {
98 n, err = z.decompressor.Read(p)
99 z.digest.Write(p[0:n])
100 if n != 0 || err != os.EOF {
105 // Finished file; check checksum.
106 if _, err := io.ReadFull(z.r, z.scratch[0:4]); err != nil {
110 // ZLIB (RFC 1950) is big-endian, unlike GZIP (RFC 1952).
111 checksum := uint32(z.scratch[0])<<24 | uint32(z.scratch[1])<<16 | uint32(z.scratch[2])<<8 | uint32(z.scratch[3])
112 if checksum != z.digest.Sum32() {
113 z.err = ChecksumError
119 // Calling Close does not close the wrapped io.Reader originally passed to NewReader.
120 func (z *reader) Close() os.Error {
124 z.err = z.decompressor.Close()