gcompress_zlib.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. // Package gcompress provides kinds of compression algorithms for binary/bytes data.
  7. package gcompress
  8. import (
  9. "bytes"
  10. "compress/zlib"
  11. "io"
  12. )
  13. // Zlib compresses <data> with zlib algorithm.
  14. func Zlib(data []byte) ([]byte, error) {
  15. if data == nil || len(data) < 13 {
  16. return data, nil
  17. }
  18. var in bytes.Buffer
  19. var err error
  20. w := zlib.NewWriter(&in)
  21. if _, err = w.Write(data); err != nil {
  22. return nil, err
  23. }
  24. if err = w.Close(); err != nil {
  25. return in.Bytes(), err
  26. }
  27. return in.Bytes(), nil
  28. }
  29. // UnZlib decompresses <data> with zlib algorithm.
  30. func UnZlib(data []byte) ([]byte, error) {
  31. if data == nil || len(data) < 13 {
  32. return data, nil
  33. }
  34. b := bytes.NewReader(data)
  35. var out bytes.Buffer
  36. var err error
  37. r, err := zlib.NewReader(b)
  38. if err != nil {
  39. return nil, err
  40. }
  41. if _, err = io.Copy(&out, r); err != nil {
  42. return nil, err
  43. }
  44. return out.Bytes(), nil
  45. }