github.com/geniusesgroup/libgo@v0.0.0-20220713101832-828057a9d3d4/compress/gzip/decompressor.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 "../../protocol" 11 ) 12 13 type Decompressor struct { 14 sourceMT protocol.MediaType 15 comBuf bytes.Buffer 16 comLen int 17 zr egzip.Reader 18 decompressedData []byte 19 } 20 21 func (c *Decompressor) initByCodec(compressed protocol.Codec) { 22 c.sourceMT = compressed.MediaType() 23 c.comLen = compressed.Len() 24 c.comBuf = *bytes.NewBuffer(compressed.Marshal()) 25 if err := c.zr.Reset(&c.comBuf); err != nil { 26 return 27 } 28 } 29 30 func (c *Decompressor) decompressAll() { 31 // TODO::: which solution? 32 // c.decompressedData, _ = io.ReadAll(gz) 33 var decomBuf bytes.Buffer 34 if c.comLen < 1 { 35 decomBuf.Grow(512) // TODO::: 512 came from io.ReadAll, any suggestion?? 36 } else { 37 decomBuf.Grow(c.comLen) 38 } 39 decomBuf.ReadFrom(&c.zr) 40 c.decompressedData = decomBuf.Bytes() 41 } 42 43 /* 44 ********** protocol.Codec interface ********** 45 */ 46 47 func (c *Decompressor) MediaType() protocol.MediaType { return c.sourceMT } 48 func (c *Decompressor) CompressType() protocol.CompressType { return nil } 49 50 func (c *Decompressor) Decode(reader protocol.Reader) (err protocol.Error) { 51 var goErr = c.zr.Reset(reader) 52 if goErr != nil { 53 // err = 54 } 55 return 56 } 57 func (c *Decompressor) Encode(writer protocol.Writer) (err protocol.Error) { 58 var _, goErr = c.WriteTo(writer) 59 if goErr != nil { 60 // err = 61 } 62 return 63 } 64 func (c *Decompressor) Marshal() (data []byte) { 65 if c.decompressedData == nil { 66 c.decompressAll() 67 } 68 return c.decompressedData 69 } 70 func (c *Decompressor) MarshalTo(data []byte) []byte { 71 if c.decompressedData == nil { 72 c.decompressAll() 73 } 74 return append(data, c.decompressedData...) 75 } 76 func (c *Decompressor) Unmarshal(data []byte) (err protocol.Error) { 77 c.comLen = len(data) 78 c.comBuf = *bytes.NewBuffer(data) 79 var goErr = c.zr.Reset(&c.comBuf) 80 if goErr != nil { 81 // err = 82 } 83 return 84 } 85 func (c *Decompressor) UnmarshalFrom(data []byte) (remaining []byte, err protocol.Error) { 86 err = c.Unmarshal(data) 87 // TODO::: can return any remaining data? 88 return 89 } 90 91 // Len return length of decompressed data 92 func (c *Decompressor) Len() (ln int) { 93 if c.decompressedData == nil { 94 c.decompressAll() 95 } 96 return len(c.decompressedData) 97 } 98 99 func (c *Decompressor) Discard() (err protocol.Error) { 100 // io.Copy(io.Discard, b) 101 return 102 } 103 104 /* 105 ********** io package interfaces ********** 106 */ 107 108 func (c *Decompressor) ReadFrom(reader io.Reader) (n int64, err error) { 109 err = c.zr.Reset(reader) 110 return 111 } 112 func (c *Decompressor) WriteTo(w io.Writer) (totalWrite int64, err error) { 113 return io.Copy(w, &c.zr) 114 }