Zstd算法Golang應用

 

https://github.com/datadog/zstdgit

 

import (github

「zstd"code

"io"get

)string

type ZstdEncoder struct {
    File *os.File
    ZstdWriter *zstd.Writer
}it

 

//level是壓縮級別:1~19,越大越慢。默認爲3io

func NewZstdEncoder(filename string, level int) (*ZstdEncoder,error) {
    f,err := os.Create(filename)
    if err != nil {
        return nil, err
    }import

    w := zstd.NewWriterLevel(f,level)
    return &ZstdEncoder{File:f,ZstdWriter:w},nil
}file

func (s *ZstdEncoder) Close() {im

    s.ZstdWriter.Close()
    s.File.Close()
}

func ZstdCompressFile(dst,src string, compress_level int) error {
    //log.Println("Zstd ", src, "->", dst)
    s,err := NewZstdEncoder(dst,compress_level)
    defer s.Close()
    if err != nil {
        return err
    }
    src_file,err := os.Open(src)
    if err != nil {
        return err
    }
    defer src_file.Close()
    io.Copy(s.ZstdWriter, src_file)
    
    return nil
}

func ZstdDecompressFile(dst, src string) error {
    //log.Println("Zstd ", src, "->", dst)
    in_file, err := os.Open(src)
    if err != nil {
        return err
    }
    defer in_file.Close()
    out_file, err := os.Create(dst)
    if err != nil {
        return err
    }
    defer out_file.Close()

    zst_reader := zstd.NewReader(in_file)
    io.Copy(out_file, zst_reader)

    return nil }

相關文章
相關標籤/搜索