example_test.go 1.2 KB

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