block_test.go 2.0 KB

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