gzip.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright 2023-2023 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package gzip
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "github.com/klauspost/compress/gzip"
  20. "github.com/lf-edge/ekuiper/internal/conf"
  21. )
  22. func NewGzipCompressor() (*gzipCompressor, error) {
  23. return &gzipCompressor{
  24. writer: gzip.NewWriter(nil),
  25. }, nil
  26. }
  27. type gzipCompressor struct {
  28. writer *gzip.Writer
  29. buffer bytes.Buffer
  30. }
  31. func (g *gzipCompressor) Compress(data []byte) ([]byte, error) {
  32. g.buffer.Reset()
  33. g.writer.Reset(&g.buffer)
  34. _, err := g.writer.Write(data)
  35. if err != nil {
  36. return nil, err
  37. }
  38. err = g.writer.Close()
  39. if err != nil {
  40. return nil, err
  41. }
  42. return g.buffer.Bytes(), nil
  43. }
  44. func NewGzipDecompressor() (*gzipDecompressor, error) {
  45. return &gzipDecompressor{}, nil
  46. }
  47. type gzipDecompressor struct {
  48. reader *gzip.Reader
  49. }
  50. func (z *gzipDecompressor) Decompress(data []byte) ([]byte, error) {
  51. if z.reader == nil {
  52. r, err := gzip.NewReader(bytes.NewReader(data))
  53. if err != nil {
  54. return nil, fmt.Errorf("failed to decompress: %v", err)
  55. }
  56. z.reader = r
  57. } else {
  58. err := z.reader.Reset(bytes.NewReader(data))
  59. if err != nil {
  60. return nil, fmt.Errorf("failed to decompress: %v", err)
  61. }
  62. }
  63. defer func() {
  64. err := z.reader.Close()
  65. if err != nil {
  66. conf.Log.Warnf("failed to close gzip decompressor: %v", err)
  67. }
  68. }()
  69. return io.ReadAll(z.reader)
  70. }
  71. func NewReader(r io.Reader) (io.ReadCloser, error) {
  72. return gzip.NewReader(r)
  73. }
  74. func NewWriter(w io.Writer) (io.Writer, error) {
  75. return gzip.NewWriter(w), nil
  76. }