impl: compressContextTakeover

This commit is contained in:
misu 2018-01-24 17:53:38 +09:00
parent 36c43970ee
commit a366cdf616
2 changed files with 18 additions and 11 deletions

View File

@ -53,7 +53,7 @@ func isValidCompressionLevel(level int) bool {
return minCompressionLevel <= level && level <= maxCompressionLevel
}
func compressNoContextTakeover(w io.WriteCloser, level int) io.WriteCloser {
func compressNoContextTakeover(w io.WriteCloser, level int, dict []byte) io.WriteCloser {
p := &flateWriterPools[level-minCompressionLevel]
tw := &truncWriter{w: w}
fw, _ := p.Get().(*flate.Writer)
@ -65,15 +65,14 @@ func compressNoContextTakeover(w io.WriteCloser, level int) io.WriteCloser {
return &flateWriteWrapper{fw: fw, tw: tw, p: p}
}
func compressContextTakeover(w io.WriteCloser, level int) io.WriteCloser {
func compressContextTakeover(w io.WriteCloser, level int, dict []byte) io.WriteCloser {
p := &flateWriterPools[level-minCompressionLevel]
tw := &truncWriter{w: w}
fw, _ := p.Get().(*flate.Writer)
if fw == nil {
fw, _ = flate.NewWriter(tw, level)
} else {
fw.Reset(tw)
}
// WriterDict's Reset just restores the dictionary.
// Initialization is done with New. (If possible get struct from sync.Pool)
fw, _ := flate.NewWriterDict(tw, level, dict)
return &flateWriteWrapper{fw: fw, tw: tw, p: p}
}

14
conn.go
View File

@ -243,7 +243,7 @@ type Conn struct {
enableWriteCompression bool
compressionLevel int
newCompressionWriter func(io.WriteCloser, int) io.WriteCloser
newCompressionWriter func(io.WriteCloser, int, []byte) io.WriteCloser
// Read fields
reader io.ReadCloser // the current reader returned to the application
@ -505,9 +505,14 @@ func (c *Conn) NextWriter(messageType int) (io.WriteCloser, error) {
}
c.writer = mw
if c.newCompressionWriter != nil && c.enableWriteCompression && isData(messageType) {
w := c.newCompressionWriter(c.writer, c.compressionLevel)
mw.compress = true
c.writer = w
switch {
case c.contextTakeover:
c.writer = c.newCompressionWriter(c.writer, c.compressionLevel, c.dict)
// no-context-takeover
default:
c.writer = c.newCompressionWriter(c.writer, c.compressionLevel, nil)
}
}
return c.writer, nil
}
@ -758,6 +763,9 @@ func (c *Conn) WriteMessage(messageType int, data []byte) error {
if _, err = w.Write(data); err != nil {
return err
}
if c.contextTakeover {
c.AddDict(data)
}
return w.Close()
}