block_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. //+build go1.9
  2. package lz4_test
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "reflect"
  7. "testing"
  8. lz4 "github.com/pierrec/lz4/v2"
  9. )
  10. type testcase struct {
  11. file string
  12. compressible bool
  13. src []byte
  14. }
  15. var rawFiles = []testcase{
  16. // {"testdata/207326ba-36f8-11e7-954a-aca46ba8ca73.png", true, nil},
  17. {"testdata/e.txt", true, nil},
  18. {"testdata/gettysburg.txt", true, nil},
  19. {"testdata/Mark.Twain-Tom.Sawyer.txt", true, nil},
  20. {"testdata/pg1661.txt", true, nil},
  21. {"testdata/pi.txt", true, nil},
  22. {"testdata/random.data", false, nil},
  23. {"testdata/repeat.txt", true, nil},
  24. }
  25. func TestCompressUncompressBlock(t *testing.T) {
  26. type compressor func(s, d []byte) (int, error)
  27. run := func(tc testcase, compress compressor) int {
  28. t.Helper()
  29. src := tc.src
  30. // Compress the data.
  31. zbuf := make([]byte, lz4.CompressBlockBound(len(src)))
  32. n, err := compress(src, zbuf)
  33. if err != nil {
  34. t.Error(err)
  35. return 0
  36. }
  37. zbuf = zbuf[:n]
  38. // Make sure that it was actually compressed unless not compressible.
  39. if !tc.compressible {
  40. return 0
  41. }
  42. if n == 0 || n >= len(src) {
  43. t.Errorf("data not compressed: %d/%d", n, len(src))
  44. return 0
  45. }
  46. // Uncompress the data.
  47. buf := make([]byte, len(src))
  48. n, err = lz4.UncompressBlock(zbuf, buf)
  49. if err != nil {
  50. t.Fatal(err)
  51. }
  52. buf = buf[:n]
  53. if !reflect.DeepEqual(src, buf) {
  54. t.Error("uncompressed compressed data not matching initial input")
  55. return 0
  56. }
  57. return len(zbuf)
  58. }
  59. for _, tc := range rawFiles {
  60. src, err := ioutil.ReadFile(tc.file)
  61. if err != nil {
  62. t.Fatal(err)
  63. }
  64. tc.src = src
  65. var n, nhc int
  66. t.Run("", func(t *testing.T) {
  67. tc := tc
  68. t.Run(tc.file, func(t *testing.T) {
  69. t.Parallel()
  70. n = run(tc, func(src, dst []byte) (int, error) {
  71. var ht [1 << 16]int
  72. return lz4.CompressBlock(src, dst, ht[:])
  73. })
  74. })
  75. t.Run(fmt.Sprintf("%s HC", tc.file), func(t *testing.T) {
  76. t.Parallel()
  77. nhc = run(tc, func(src, dst []byte) (int, error) {
  78. return lz4.CompressBlockHC(src, dst, -1)
  79. })
  80. })
  81. })
  82. fmt.Printf("%-40s: %8d / %8d / %8d\n", tc.file, n, nhc, len(src))
  83. }
  84. }