github.com/google/syzkaller@v0.0.0-20240517125934-c0f1611a36d6/pkg/image/compression.go (about)

     1  // Copyright 2022 syzkaller project authors. All rights reserved.
     2  // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
     3  
     4  package image
     5  
     6  import (
     7  	"bytes"
     8  	"compress/zlib"
     9  	"encoding/base64"
    10  	"fmt"
    11  	"io"
    12  )
    13  
    14  func Compress(rawData []byte) []byte {
    15  	var buffer bytes.Buffer
    16  	zlibWriter := zlib.NewWriter(&buffer)
    17  
    18  	_, err := zlibWriter.Write(rawData)
    19  	if err != nil {
    20  		panic(fmt.Sprintf("could not compress with zlib: %v", err))
    21  	}
    22  
    23  	err = zlibWriter.Close()
    24  	if err != nil {
    25  		panic(fmt.Sprintf("could not finalize compression with zlib: %v", err))
    26  	}
    27  
    28  	return buffer.Bytes()
    29  }
    30  
    31  func MustDecompress(compressed []byte) (data []byte, dtor func()) {
    32  	if len(compressed) == 0 {
    33  		return nil, func() {}
    34  	}
    35  	return mustDecompress(compressed)
    36  }
    37  
    38  func DecompressCheck(compressed []byte) error {
    39  	return decompressWriter(io.Discard, compressed)
    40  }
    41  
    42  func decompressWriter(w io.Writer, compressed []byte) error {
    43  	if len(compressed) == 0 {
    44  		return nil
    45  	}
    46  	zlibReader, err := zlib.NewReader(bytes.NewReader(compressed))
    47  	if err != nil {
    48  		return fmt.Errorf("could not initialise zlib: %w", err)
    49  	}
    50  
    51  	if _, err := io.Copy(w, zlibReader); err != nil {
    52  		return fmt.Errorf("could not read data with zlib: %w", err)
    53  	}
    54  
    55  	return zlibReader.Close()
    56  }
    57  
    58  func DecodeB64(b64Data []byte) ([]byte, error) {
    59  	decoder := base64.NewDecoder(base64.StdEncoding, bytes.NewReader(b64Data))
    60  	rawData, err := io.ReadAll(decoder)
    61  	if err != nil {
    62  		return nil, fmt.Errorf("could not decode Base64: %w", err)
    63  	}
    64  	return rawData, nil
    65  }
    66  
    67  func EncodeB64(rawData []byte) []byte {
    68  	var buf bytes.Buffer
    69  	encoder := base64.NewEncoder(base64.StdEncoding, &buf)
    70  	_, err := encoder.Write(rawData)
    71  	if err != nil {
    72  		panic(fmt.Sprintf("could not encode Base64: %v", err))
    73  	}
    74  	err = encoder.Close()
    75  	if err != nil {
    76  		panic(fmt.Sprintf("could not finalize encoding to Base64: %v", err))
    77  	}
    78  	return buf.Bytes()
    79  }