block_test.go 2.0 KB

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