Example #1
0
// NewDeflater creates a new io.WriteCloser that satisfies writes by compressing data written to w.
// It is the caller's responsibility to call Close on the WriteCloser when done.
// level is the compression level, which can be DefaultCompression, NoCompression,
// or any integer value between BestSpeed and BestCompression (inclusive).
func NewDeflaterLevel(w io.Writer, level int) (io.WriteCloser, os.Error) {
	z := new(writer)
	// ZLIB has a two-byte header (as documented in RFC 1950).
	// The first four bits is the CINFO (compression info), which is 7 for the default deflate window size.
	// The next four bits is the CM (compression method), which is 8 for deflate.
	z.scratch[0] = 0x78
	// The next two bits is the FLEVEL (compression level). The four values are:
	// 0=fastest, 1=fast, 2=default, 3=best.
	// The next bit, FDICT, is unused, in this implementation.
	// The final five FCHECK bits form a mod-31 checksum.
	switch level {
	case 0, 1:
		z.scratch[1] = 0x01
	case 2, 3, 4, 5:
		z.scratch[1] = 0x5e
	case 6, -1:
		z.scratch[1] = 0x9c
	case 7, 8, 9:
		z.scratch[1] = 0xda
	default:
		return nil, os.NewError("level out of range")
	}
	_, err := w.Write(z.scratch[0:2])
	if err != nil {
		return nil, err
	}
	z.w = w
	z.deflater = flate.NewDeflater(w, level)
	z.digest = adler32.New()
	return z, nil
}
Example #2
0
func (z *Deflater) Write(p []byte) (int, os.Error) {
	if z.err != nil {
		return 0, z.err
	}
	var n int
	// Write the GZIP header lazily.
	if z.deflater == nil {
		z.buf[0] = gzipID1
		z.buf[1] = gzipID2
		z.buf[2] = gzipDeflate
		z.buf[3] = 0
		if z.Extra != nil {
			z.buf[3] |= 0x04
		}
		if z.Name != "" {
			z.buf[3] |= 0x08
		}
		if z.Comment != "" {
			z.buf[3] |= 0x10
		}
		put4(z.buf[4:8], z.Mtime)
		if z.level == BestCompression {
			z.buf[8] = 2
		} else if z.level == BestSpeed {
			z.buf[8] = 4
		} else {
			z.buf[8] = 0
		}
		z.buf[9] = z.OS
		n, z.err = z.w.Write(z.buf[0:10])
		if z.err != nil {
			return n, z.err
		}
		if z.Extra != nil {
			z.err = z.writeBytes(z.Extra)
			if z.err != nil {
				return n, z.err
			}
		}
		if z.Name != "" {
			z.err = z.writeString(z.Name)
			if z.err != nil {
				return n, z.err
			}
		}
		if z.Comment != "" {
			z.err = z.writeString(z.Comment)
			if z.err != nil {
				return n, z.err
			}
		}
		z.deflater = flate.NewDeflater(z.w, z.level)
	}
	z.size += uint32(len(p))
	z.digest.Write(p)
	n, z.err = z.deflater.Write(p)
	return n, z.err
}
Example #3
0
func TestRead(t *testing.T) {
	b := make([]byte, 4e6)
	n, err := Read(b)
	if n != len(b) || err != nil {
		t.Fatalf("Read(buf) = %d, %s", n, err)
	}

	var z bytes.Buffer
	f := flate.NewDeflater(&z, 5)
	f.Write(b)
	f.Close()
	if z.Len() < len(b)*99/100 {
		t.Fatalf("Compressed %d -> %d", len(b), z.Len())
	}
}