github.com/GeniusesGroup/libgo@v0.0.0-20220929090155-5ff932cb408e/compress/gzip/compressor.go (about) 1 /* For license and copyright information please see LEGAL file in repository */ 2 3 package gzip 4 5 import ( 6 "bytes" 7 egzip "compress/gzip" 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 (c *Compressor) init() { 21 var b bytes.Buffer 22 b.Grow(c.source.Len()) 23 var gz, _ = egzip.NewWriterLevel(&b, int(c.options.CompressLevel)) 24 gz.Write(c.source.Marshal()) 25 gz.Close() 26 c.compressedData = b.Bytes() 27 } 28 29 /* 30 ********** protocol.Codec interface ********** 31 */ 32 33 func (c *Compressor) MediaType() protocol.MediaType { return c.source.MediaType() } 34 func (c *Compressor) CompressType() protocol.CompressType { return &GZIP } 35 36 func (c *Compressor) Decode(reader protocol.Reader) (err protocol.Error) { 37 err = compress.ErrSourceNotChangeable 38 return 39 } 40 func (c *Compressor) Encode(writer protocol.Writer) (err protocol.Error) { 41 var _, goErr = c.WriteTo(writer) 42 if goErr != nil { 43 // err = 44 } 45 return 46 } 47 func (c *Compressor) Marshal() (data []byte) { 48 if c.compressedData == nil { 49 c.init() 50 } 51 return c.compressedData 52 } 53 func (c *Compressor) MarshalTo(data []byte) []byte { 54 if c.compressedData == nil { 55 c.init() 56 } 57 return append(data, c.compressedData...) 58 } 59 func (c *Compressor) Unmarshal(data []byte) (err protocol.Error) { 60 err = compress.ErrSourceNotChangeable 61 return 62 } 63 func (c *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 (c *Compressor) Len() (ln int) { 70 if c.compressedData == nil { 71 c.init() 72 } 73 return len(c.compressedData) 74 } 75 76 /* 77 ********** io package interfaces ********** 78 */ 79 80 func (c *Compressor) ReadFrom(reader io.Reader) (n int64, err error) { 81 err = compress.ErrSourceNotChangeable 82 return 83 } 84 func (c *Compressor) WriteTo(w io.Writer) (totalWrite int64, err error) { 85 var gz, _ = egzip.NewWriterLevel(w, int(c.options.CompressLevel)) 86 var writeLen int 87 writeLen, err = gz.Write(c.source.Marshal()) 88 gz.Close() 89 totalWrite = int64(writeLen) 90 return 91 }