decompressor.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 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 compressor
  15. import (
  16. "bytes"
  17. "compress/zlib"
  18. "fmt"
  19. "github.com/lf-edge/ekuiper/internal/conf"
  20. "github.com/lf-edge/ekuiper/pkg/message"
  21. "io"
  22. )
  23. func GetDecompressor(name string) (message.Decompressor, error) {
  24. switch name {
  25. case "zlib":
  26. return &zlibDecompressor{}, nil
  27. default:
  28. return nil, fmt.Errorf("unsupported compressor: %s", name)
  29. }
  30. }
  31. type zlibDecompressor struct {
  32. reader io.ReadCloser
  33. }
  34. func (z *zlibDecompressor) Decompress(data []byte) ([]byte, error) {
  35. if z.reader == nil {
  36. r, err := zlib.NewReader(bytes.NewReader(data))
  37. if err != nil {
  38. return nil, fmt.Errorf("failed to decompress: %v", err)
  39. }
  40. z.reader = r
  41. } else {
  42. err := z.reader.(zlib.Resetter).Reset(bytes.NewReader(data), nil)
  43. if err != nil {
  44. return nil, fmt.Errorf("failed to decompress: %v", err)
  45. }
  46. }
  47. defer func() {
  48. err := z.reader.Close()
  49. if err != nil {
  50. conf.Log.Warnf("failed to close zlib decompressor: %v", err)
  51. }
  52. }()
  53. return io.ReadAll(z.reader)
  54. }