zstd.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2023 carlclone@gmail.com.
  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. "github.com/klauspost/compress/zstd"
  18. )
  19. func newZstdCompressor() (*zstdCompressor, error) {
  20. zstdWriter, err := zstd.NewWriter(nil)
  21. if err != nil {
  22. return nil, err
  23. }
  24. return &zstdCompressor{
  25. writer: zstdWriter,
  26. }, nil
  27. }
  28. type zstdCompressor struct {
  29. writer *zstd.Encoder
  30. buffer bytes.Buffer
  31. }
  32. func (g *zstdCompressor) Compress(data []byte) ([]byte, error) {
  33. g.buffer.Reset()
  34. g.writer.Reset(&g.buffer)
  35. _, err := g.writer.Write(data)
  36. if err != nil {
  37. return nil, err
  38. }
  39. err = g.writer.Close()
  40. if err != nil {
  41. return nil, err
  42. }
  43. return g.buffer.Bytes(), nil
  44. }
  45. func newzstdDecompressor() (*zstdDecompressor, error) {
  46. r, err := zstd.NewReader(nil, zstd.WithDecoderConcurrency(0))
  47. if err != nil {
  48. return nil, err
  49. }
  50. return &zstdDecompressor{decoder: r}, nil
  51. }
  52. type zstdDecompressor struct {
  53. decoder *zstd.Decoder
  54. }
  55. func (z *zstdDecompressor) Decompress(data []byte) ([]byte, error) {
  56. return z.decoder.DecodeAll(data, nil)
  57. }