...

Source file src/github.com/pierrec/lz4/v4/example_test.go

Documentation: github.com/pierrec/lz4/v4

     1  package lz4_test
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"os"
     7  	"strings"
     8  
     9  	"github.com/pierrec/lz4/v4"
    10  )
    11  
    12  func Example() {
    13  	// Compress and uncompress an input string.
    14  	s := "hello world"
    15  	r := strings.NewReader(s)
    16  
    17  	// The pipe will uncompress the data from the writer.
    18  	pr, pw := io.Pipe()
    19  	zw := lz4.NewWriter(pw)
    20  	zr := lz4.NewReader(pr)
    21  
    22  	go func() {
    23  		// Compress the input string.
    24  		_, _ = io.Copy(zw, r)
    25  		_ = zw.Close() // Make sure the writer is closed
    26  		_ = pw.Close() // Terminate the pipe
    27  	}()
    28  
    29  	_, _ = io.Copy(os.Stdout, zr)
    30  
    31  	// Output:
    32  	// hello world
    33  }
    34  
    35  func ExampleCompressBlock() {
    36  	s := "hello world"
    37  	data := []byte(strings.Repeat(s, 100))
    38  	buf := make([]byte, lz4.CompressBlockBound(len(data)))
    39  
    40  	var c lz4.Compressor
    41  	n, err := c.CompressBlock(data, buf)
    42  	if err != nil {
    43  		fmt.Println(err)
    44  	}
    45  	if n >= len(data) {
    46  		fmt.Printf("`%s` is not compressible", s)
    47  	}
    48  	buf = buf[:n] // compressed data
    49  
    50  	// Allocate a very large buffer for decompression.
    51  	out := make([]byte, 10*len(data))
    52  	n, err = lz4.UncompressBlock(buf, out)
    53  	if err != nil {
    54  		fmt.Println(err)
    55  	}
    56  	out = out[:n] // uncompressed data
    57  
    58  	fmt.Println(string(out[:len(s)]))
    59  
    60  	// Output:
    61  	// hello world
    62  }
    63  

View as plain text