reader_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package flate
  5. import (
  6. "bytes"
  7. "io"
  8. "os"
  9. "runtime"
  10. "strings"
  11. "testing"
  12. )
  13. func TestNlitOutOfRange(t *testing.T) {
  14. // Trying to decode this bogus flate data, which has a Huffman table
  15. // with nlit=288, should not panic.
  16. io.Copy(io.Discard, NewReader(strings.NewReader(
  17. "\xfc\xfe\x36\xe7\x5e\x1c\xef\xb3\x55\x58\x77\xb6\x56\xb5\x43\xf4"+
  18. "\x6f\xf2\xd2\xe6\x3d\x99\xa0\x85\x8c\x48\xeb\xf8\xda\x83\x04\x2a"+
  19. "\x75\xc4\xf8\x0f\x12\x11\xb9\xb4\x4b\x09\xa0\xbe\x8b\x91\x4c")))
  20. }
  21. var suites = []struct{ name, file string }{
  22. // Digits is the digits of the irrational number e. Its decimal representation
  23. // does not repeat, but there are only 10 possible digits, so it should be
  24. // reasonably compressible.
  25. {"Digits", "../testdata/e.txt"},
  26. // Newton is Isaac Newtons's educational text on Opticks.
  27. {"Newton", "testdata/Isaac.Newton-Opticks.txt"},
  28. }
  29. func BenchmarkDecode(b *testing.B) {
  30. doBench(b, func(b *testing.B, buf0 []byte, level, n int) {
  31. b.ReportAllocs()
  32. b.StopTimer()
  33. b.SetBytes(int64(n))
  34. compressed := new(bytes.Buffer)
  35. w, err := NewWriter(compressed, level)
  36. if err != nil {
  37. b.Fatal(err)
  38. }
  39. for i := 0; i < n; i += len(buf0) {
  40. if len(buf0) > n-i {
  41. buf0 = buf0[:n-i]
  42. }
  43. io.Copy(w, bytes.NewReader(buf0))
  44. }
  45. w.Close()
  46. buf1 := compressed.Bytes()
  47. buf0, compressed, w = nil, nil, nil
  48. runtime.GC()
  49. b.StartTimer()
  50. for i := 0; i < b.N; i++ {
  51. io.Copy(io.Discard, NewReader(bytes.NewReader(buf1)))
  52. }
  53. })
  54. }
  55. var levelTests = []struct {
  56. name string
  57. level int
  58. }{
  59. {"Huffman", HuffmanOnly},
  60. {"Speed", BestSpeed},
  61. {"Default", DefaultCompression},
  62. {"Compression", BestCompression},
  63. }
  64. var sizes = []struct {
  65. name string
  66. n int
  67. }{
  68. {"1e4", 1e4},
  69. {"1e5", 1e5},
  70. {"1e6", 1e6},
  71. }
  72. func doBench(b *testing.B, f func(b *testing.B, buf []byte, level, n int)) {
  73. for _, suite := range suites {
  74. buf, err := os.ReadFile(suite.file)
  75. if err != nil {
  76. b.Fatal(err)
  77. }
  78. if len(buf) == 0 {
  79. b.Fatalf("test file %q has no data", suite.file)
  80. }
  81. for _, l := range levelTests {
  82. for _, s := range sizes {
  83. b.Run(suite.name+"/"+l.name+"/"+s.name, func(b *testing.B) {
  84. f(b, buf, l.level, s.n)
  85. })
  86. }
  87. }
  88. }
  89. }