token_test.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package flate
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "testing"
  6. )
  7. type testFatal interface {
  8. Fatal(args ...interface{})
  9. }
  10. // loadTestTokens will load test tokens.
  11. // First block from enwik9, varint encoded.
  12. func loadTestTokens(t testFatal) *tokens {
  13. b, err := ioutil.ReadFile("testdata/tokens.bin")
  14. if err != nil {
  15. t.Fatal(err)
  16. }
  17. var tokens tokens
  18. err = tokens.FromVarInt(b)
  19. if err != nil {
  20. t.Fatal(err)
  21. }
  22. return &tokens
  23. }
  24. func Test_tokens_EstimatedBits(t *testing.T) {
  25. tok := loadTestTokens(t)
  26. // The estimated size, update if method changes.
  27. const expect = 221057
  28. n := tok.EstimatedBits()
  29. var buf bytes.Buffer
  30. wr := newHuffmanBitWriter(&buf)
  31. wr.writeBlockDynamic(tok, true, nil, true)
  32. if wr.err != nil {
  33. t.Fatal(wr.err)
  34. }
  35. wr.flush()
  36. t.Log("got:", n, "actual:", buf.Len()*8, "(header not part of estimate)")
  37. if n != expect {
  38. t.Error("want:", expect, "bits, got:", n)
  39. }
  40. }
  41. func Benchmark_tokens_EstimatedBits(b *testing.B) {
  42. tok := loadTestTokens(b)
  43. b.ResetTimer()
  44. // One "byte", one token iteration.
  45. b.SetBytes(1)
  46. for i := 0; i < b.N; i++ {
  47. _ = tok.EstimatedBits()
  48. }
  49. }