github.com/geniusesgroup/libgo@v0.0.0-20220713101832-828057a9d3d4/compress/flate/compressor.go (about)

     1  /* For license and copyright information please see LEGAL file in repository */
     2  
     3  package flate
     4  
     5  import (
     6  	"bytes"
     7  	"compress/flate"
     8  	"io"
     9  
    10  	compress ".."
    11  	"../../protocol"
    12  )
    13  
    14  type Compressor struct {
    15  	source         protocol.Codec
    16  	options        protocol.CompressOptions
    17  	compressedData []byte
    18  }
    19  
    20  func (d *Compressor) init() {
    21  	var b bytes.Buffer
    22  	b.Grow(d.source.Len())
    23  	var def, _ = flate.NewWriter(&b, int(d.options.CompressLevel))
    24  	def.Write(d.source.Marshal())
    25  	def.Close()
    26  	d.compressedData = b.Bytes()
    27  }
    28  
    29  /*
    30  ********** protocol.Codec interface **********
    31   */
    32  
    33  func (d *Compressor) MediaType() protocol.MediaType       { return d.source.MediaType() }
    34  func (d *Compressor) CompressType() protocol.CompressType { return &Deflate }
    35  
    36  func (d *Compressor) Decode(reader protocol.Reader) (err protocol.Error) {
    37  	err = compress.ErrSourceNotChangeable
    38  	return
    39  }
    40  func (d *Compressor) Encode(writer protocol.Writer) (err protocol.Error) {
    41  	var _, goErr = d.WriteTo(writer)
    42  	if goErr != nil {
    43  		// err =
    44  	}
    45  	return
    46  }
    47  func (d *Compressor) Marshal() (data []byte) {
    48  	if d.compressedData == nil {
    49  		d.init()
    50  	}
    51  	return d.compressedData
    52  }
    53  func (d *Compressor) MarshalTo(data []byte) []byte {
    54  	if d.compressedData == nil {
    55  		d.init()
    56  	}
    57  	return append(data, d.compressedData...)
    58  }
    59  func (d *Compressor) Unmarshal(data []byte) (err protocol.Error) {
    60  	err = compress.ErrSourceNotChangeable
    61  	return
    62  }
    63  func (d *Compressor) UnmarshalFrom(data []byte) (remaining []byte, err protocol.Error) {
    64  	err = compress.ErrSourceNotChangeable
    65  	return
    66  }
    67  
    68  // Len return length of compressed data
    69  func (d *Compressor) Len() (ln int) {
    70  	if d.compressedData == nil {
    71  		d.init()
    72  	}
    73  	return len(d.compressedData)
    74  }
    75  
    76  /*
    77  ********** io package interfaces **********
    78   */
    79  
    80  func (d *Compressor) ReadFrom(reader io.Reader) (n int64, err error) {
    81  	err = compress.ErrSourceNotChangeable
    82  	return
    83  }
    84  func (d *Compressor) WriteTo(w io.Writer) (totalWrite int64, err error) {
    85  	var def, _ = flate.NewWriter(w, int(d.options.CompressLevel))
    86  	var writeLen int
    87  	writeLen, err = def.Write(d.source.Marshal())
    88  	def.Close()
    89  	totalWrite = int64(writeLen)
    90  	return
    91  }