Home > Backend Development > Golang > Compress one byte slice into another slice in Golang

Compress one byte slice into another slice in Golang

王林
Release: 2024-02-12 16:57:05
forward
1157 people have browsed it

在 Golang 中将一个字节切片压缩到另一个切片中

Question content

I want to achieve the exact opposite effect of the solution given here, compress one byte fragment into another byte fragment -

Convert compressed []byte to decompressed []byte golang code

Similar to -

func ZipBytes(unippedBytes []byte) ([]byte, error) {
// ...
}
Copy after login

[I will upload this compressed file as multi-part form data for post requests]

Solution

You can use bytes.buffer to compress directly into memory .

The following example uses compress/zlib because it is the opposite of the example given in the question. Depending on your use case you can also easily change it to compress/gzip (very similar api).

package data_test

import (
    "bytes"
    "compress/zlib"
    "io"
    "testing"
)

func compress(buf []byte) ([]byte, error) {
    var out bytes.Buffer
    w := zlib.NewWriter(&out)
    if _, err := w.Write(buf); err != nil {
        return nil, err
    }
    if err := w.Close(); err != nil {
        return nil, err
    }
    return out.Bytes(), nil
}

func decompress(buf []byte) (_ []byte, e error) {
    r, err := zlib.NewReader(bytes.NewReader(buf))
    if err != nil {
        return nil, err
    }
    defer func() {
        if err := r.Close(); e == nil {
            e = err
        }
    }()
    return io.ReadAll(r)
}

func TestRoundtrip(t *testing.T) {
    want := []byte("test data")

    zdata, err := compress(want)
    if err != nil {
        t.Fatalf("compress: %v", err)
    }
    got, err := decompress(zdata)
    if err != nil {
        t.Fatalf("decompress: %v", err)
    }
    if !bytes.Equal(want, got) {
        t.Errorf("roundtrip: got = %q; want = %q", got, want)
    }
}
Copy after login

The above is the detailed content of Compress one byte slice into another slice in Golang. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template