Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions utils/compression/compression.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"errors"
"fmt"
"io"
"strings"
"sync"
)

Expand Down Expand Up @@ -124,17 +125,36 @@
return writer
}

var bufferPool = sync.Pool{New: func() any { return new(bytes.Buffer) }}

func Gzip64Encode(data []byte) (string, error) {
var compressedBuffer bytes.Buffer
gzipWriter := GzipWriter(&compressedBuffer)
compressed := bufferPool.Get().(*bytes.Buffer)
compressed.Reset()
defer bufferPool.Put(compressed)

gzipWriter := GzipWriter(compressed)
defer gzipWriter.Release()
if _, err := gzipWriter.Write(data); err != nil {
return "", fmt.Errorf("writing data with gzip: %w", err)
}
if err := gzipWriter.Close(); err != nil {
return "", fmt.Errorf("closing gzip writer: %w", err)
}
return base64.StdEncoding.EncodeToString(compressedBuffer.Bytes()), nil

// Encode into a Builder pre-grown to the exact output size: the encoder's
// writes never reallocate, and Builder.String() hands over its backing
// array without copying — the returned string is the only allocation that
// scales with the payload.
var encoded strings.Builder
encoded.Grow(base64.StdEncoding.EncodedLen(compressed.Len()))
b64 := base64.NewEncoder(base64.StdEncoding, &encoded)
if _, err := b64.Write(compressed.Bytes()); err != nil {
return "", fmt.Errorf("base64-encoding compressed data: %w", err)

Check warning on line 152 in utils/compression/compression.go

View check run for this annotation

Codecov / codecov/patch

utils/compression/compression.go#L152

Added line #L152 was not covered by tests
}
if err := b64.Close(); err != nil {
return "", fmt.Errorf("closing base64 encoder: %w", err)

Check warning on line 155 in utils/compression/compression.go

View check run for this annotation

Codecov / codecov/patch

utils/compression/compression.go#L155

Added line #L155 was not covered by tests
}
return encoded.String(), nil
}

func Gzip64Decode(data string) ([]byte, error) {
Expand Down
Loading