example_test.go 1.2 KB

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