example_test.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package lz4_test
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "strings"
  7. "github.com/pierrec/lz4/v4"
  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. n, err := lz4.CompressBlock(data, buf, nil)
  32. if err != nil {
  33. fmt.Println(err)
  34. }
  35. if n >= len(data) {
  36. fmt.Printf("`%s` is not compressible", s)
  37. }
  38. buf = buf[:n] // compressed data
  39. // Allocated a very large buffer for decompression.
  40. out := make([]byte, 10*len(data))
  41. n, err = lz4.UncompressBlock(buf, out)
  42. if err != nil {
  43. fmt.Println(err)
  44. }
  45. out = out[:n] // uncompressed data
  46. fmt.Println(string(out[:len(s)]))
  47. // Output:
  48. // hello world
  49. }