2018-11-09 13:54:47 +00:00
|
|
|
|
|
|
|
|
2018-11-11 16:44:30 +00:00
|
|
|
package archiver
|
2018-11-09 13:54:47 +00:00
|
|
|
|
|
|
|
|
|
|
|
import "bytes"
|
|
|
|
import "compress/gzip"
|
|
|
|
import "fmt"
|
|
|
|
|
|
|
|
|
2021-11-17 17:50:30 +00:00
|
|
|
import "github.com/foobaz/go-zopfli/zopfli"
|
2021-11-17 19:04:45 +00:00
|
|
|
import brotli "github.com/itchio/go-brotli/enc"
|
2021-11-17 17:50:30 +00:00
|
|
|
|
|
|
|
|
2018-11-09 13:54:47 +00:00
|
|
|
|
|
|
|
|
|
|
|
func Compress (_data []byte, _algorithm string) ([]byte, string, error) {
|
|
|
|
switch _algorithm {
|
|
|
|
case "gz", "gzip" :
|
|
|
|
return CompressGzip (_data)
|
2021-11-17 17:50:30 +00:00
|
|
|
case "zopfli" :
|
|
|
|
return CompressZopfli (_data)
|
2018-11-09 13:54:47 +00:00
|
|
|
case "br", "brotli" :
|
|
|
|
return CompressBrotli (_data)
|
|
|
|
case "", "none", "identity" :
|
|
|
|
return _data, "identity", nil
|
|
|
|
default :
|
|
|
|
return nil, "", fmt.Errorf ("[ea23f966] invalid compression algorithm `%s`", _algorithm)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
func CompressGzip (_data []byte) ([]byte, string, error) {
|
|
|
|
|
|
|
|
_buffer := & bytes.Buffer {}
|
|
|
|
|
|
|
|
var _encoder *gzip.Writer
|
|
|
|
if _encoder_0, _error := gzip.NewWriterLevel (_buffer, gzip.BestCompression); _error == nil {
|
|
|
|
_encoder = _encoder_0
|
|
|
|
} else {
|
|
|
|
return nil, "", _error
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, _error := _encoder.Write (_data); _error != nil {
|
|
|
|
return nil, "", _error
|
|
|
|
}
|
|
|
|
if _error := _encoder.Close (); _error != nil {
|
|
|
|
return nil, "", _error
|
|
|
|
}
|
|
|
|
|
|
|
|
_data = _buffer.Bytes ()
|
|
|
|
return _data, "gzip", nil
|
|
|
|
}
|
|
|
|
|
2021-11-17 17:50:30 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
func CompressZopfli (_data []byte) ([]byte, string, error) {
|
|
|
|
|
|
|
|
_buffer := & bytes.Buffer {}
|
|
|
|
|
|
|
|
_options := zopfli.DefaultOptions ()
|
|
|
|
_options.NumIterations = 15
|
|
|
|
_options.BlockSplitting = true
|
|
|
|
_options.BlockSplittingLast = true
|
|
|
|
_options.BlockSplittingMax = 0
|
|
|
|
_options.BlockType = zopfli.DYNAMIC_BLOCK
|
|
|
|
|
|
|
|
if _error := zopfli.GzipCompress (&_options, _data, _buffer); _error != nil {
|
|
|
|
return nil, "", _error
|
|
|
|
}
|
|
|
|
|
|
|
|
_data = _buffer.Bytes ()
|
|
|
|
return _data, "gzip", nil
|
|
|
|
}
|
|
|
|
|
2021-11-17 19:04:45 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
func CompressBrotli (_data []byte) ([]byte, string, error) {
|
|
|
|
|
|
|
|
_buffer := & bytes.Buffer {}
|
|
|
|
|
|
|
|
_options := brotli.BrotliWriterOptions { Quality : 11, LGWin : 24}
|
|
|
|
|
|
|
|
_encoder := brotli.NewBrotliWriter (_buffer, &_options)
|
|
|
|
|
|
|
|
if _, _error := _encoder.Write (_data); _error != nil {
|
|
|
|
return nil, "", _error
|
|
|
|
}
|
|
|
|
if _error := _encoder.Close (); _error != nil {
|
|
|
|
return nil, "", _error
|
|
|
|
}
|
|
|
|
|
|
|
|
_data = _buffer.Bytes ()
|
|
|
|
return _data, "br", nil
|
|
|
|
}
|
|
|
|
|