Debian Codegraph @

zlib/writer.go

raw
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.
4
5 package zlib
6
7 import (
8 "encoding/binary"
9 "fmt"
10 "hash"
11 "hash/adler32"
12 "io"
13
14 "github.com/klauspost/compress/flate"
15 )
16
17 // These constants are copied from the flate package, so that code that imports
18 // "compress/zlib" does not also have to import "compress/flate".
19 const (
20 NoCompression = flate.NoCompression
21 BestSpeed = flate.BestSpeed
22 BestCompression = flate.BestCompression
23 DefaultCompression = flate.DefaultCompression
24 ConstantCompression = flate.ConstantCompression // Deprecated: Use HuffmanOnly.
25 HuffmanOnly = flate.HuffmanOnly
26 )
27
28 // A Writer takes data written to it and writes the compressed
29 // form of that data to an underlying writer (see NewWriter).
30 type Writer struct {
31 w io.Writer
32 level int
33 dict []byte
34 compressor *flate.Writer
35 digest hash.Hash32
36 err error
37 scratch [4]byte
38 wroteHeader bool
39 }
40
41 // NewWriter creates a new Writer.
42 // Writes to the returned Writer are compressed and written to w.
43 //
44 // It is the caller's responsibility to call Close on the Writer when done.
45 // Writes may be buffered and not flushed until Close.
46 func NewWriter(w io.Writer) *Writer {
47 z, _ := NewWriterLevelDict(w, DefaultCompression, nil)
48 return z
49 }
50
51 // NewWriterLevel is like NewWriter but specifies the compression level instead
52 // of assuming DefaultCompression.
53 //
54 // The compression level can be DefaultCompression, NoCompression, HuffmanOnly
55 // or any integer value between BestSpeed and BestCompression inclusive.
56 // The error returned will be nil if the level is valid.
57 func NewWriterLevel(w io.Writer, level int) (*Writer, error) {
58 return NewWriterLevelDict(w, level, nil)
59 }
60
61 // NewWriterLevelDict is like NewWriterLevel but specifies a dictionary to
62 // compress with.
63 //
64 // The dictionary may be nil. If not, its contents should not be modified until
65 // the Writer is closed.
66 func NewWriterLevelDict(w io.Writer, level int, dict []byte) (*Writer, error) {
67 if level < HuffmanOnly || level > BestCompression {
68 return nil, fmt.Errorf("zlib: invalid compression level: %d", level)
69 }
70 return &Writer{
71 w: w,
72 level: level,
73 dict: dict,
74 }, nil
75 }
76
77 // Reset clears the state of the Writer z such that it is equivalent to its
78 // initial state from NewWriterLevel or NewWriterLevelDict, but instead writing
79 // to w.
80 func (z *Writer) Reset(w io.Writer) {
81 z.w = w
82 // z.level and z.dict left unchanged.
83 if z.compressor != nil {
84 z.compressor.Reset(w)
85 }
86 if z.digest != nil {
87 z.digest.Reset()
88 }
89 z.err = nil
90 z.scratch = [4]byte{}
91 z.wroteHeader = false
92 }
93
94 // writeHeader writes the ZLIB header.
95 func (z *Writer) writeHeader() (err error) {
96 z.wroteHeader = true
97 // ZLIB has a two-byte header (as documented in RFC 1950).
98 // The first four bits is the CINFO (compression info), which is 7 for the default deflate window size.
99 // The next four bits is the CM (compression method), which is 8 for deflate.
100 z.scratch[0] = 0x78
101 // The next two bits is the FLEVEL (compression level). The four values are:
102 // 0=fastest, 1=fast, 2=default, 3=best.
103 // The next bit, FDICT, is set if a dictionary is given.
104 // The final five FCHECK bits form a mod-31 checksum.
105 switch z.level {
106 case -2, 0, 1:
107 z.scratch[1] = 0 << 6
108 case 2, 3, 4, 5:
109 z.scratch[1] = 1 << 6
110 case 6, -1:
111 z.scratch[1] = 2 << 6
112 case 7, 8, 9:
113 z.scratch[1] = 3 << 6
114 default:
115 panic("unreachable")
116 }
117 if z.dict != nil {
118 z.scratch[1] |= 1 << 5
119 }
120 z.scratch[1] += uint8(31 - binary.BigEndian.Uint16(z.scratch[:2])%31)
121 if _, err = z.w.Write(z.scratch[0:2]); err != nil {
122 return err
123 }
124 if z.dict != nil {
125 // The next four bytes are the Adler-32 checksum of the dictionary.
126 binary.BigEndian.PutUint32(z.scratch[:], adler32.Checksum(z.dict))
127 if _, err = z.w.Write(z.scratch[0:4]); err != nil {
128 return err
129 }
130 }
131 if z.compressor == nil {
132 // Initialize deflater unless the Writer is being reused
133 // after a Reset call.
134 z.compressor, err = flate.NewWriterDict(z.w, z.level, z.dict)
135 if err != nil {
136 return err
137 }
138 z.digest = adler32.New()
139 }
140 return nil
141 }
142
143 // Write writes a compressed form of p to the underlying io.Writer. The
144 // compressed bytes are not necessarily flushed until the Writer is closed or
145 // explicitly flushed.
146 func (z *Writer) Write(p []byte) (n int, err error) {
147 if !z.wroteHeader {
148 z.err = z.writeHeader()
149 }
150 if z.err != nil {
151 return 0, z.err
152 }
153 if len(p) == 0 {
154 return 0, nil
155 }
156 n, err = z.compressor.Write(p)
157 if err != nil {
158 z.err = err
159 return
160 }
161 z.digest.Write(p)
162 return
163 }
164
165 // Flush flushes the Writer to its underlying io.Writer.
166 func (z *Writer) Flush() error {
167 if !z.wroteHeader {
168 z.err = z.writeHeader()
169 }
170 if z.err != nil {
171 return z.err
172 }
173 z.err = z.compressor.Flush()
174 return z.err
175 }
176
177 // Close closes the Writer, flushing any unwritten data to the underlying
178 // io.Writer, but does not close the underlying io.Writer.
179 func (z *Writer) Close() error {
180 if !z.wroteHeader {
181 z.err = z.writeHeader()
182 }
183 if z.err != nil {
184 return z.err
185 }
186 z.err = z.compressor.Close()
187 if z.err != nil {
188 return z.err
189 }
190 checksum := z.digest.Sum32()
191 // ZLIB (RFC 1950) is big-endian, unlike GZIP (RFC 1952).
192 binary.BigEndian.PutUint32(z.scratch[:], checksum)
193 _, z.err = z.w.Write(z.scratch[0:4])
194 return z.err
195 }