1
0

mask_test.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of
  2. // this source code is governed by a BSD-style license that can be found in the
  3. // LICENSE file.
  4. // Require 1.7 for sub-bencmarks
  5. // +build go1.7,!appengine
  6. package websocket
  7. import (
  8. "fmt"
  9. "testing"
  10. )
  11. func maskBytesByByte(key [4]byte, pos int, b []byte) int {
  12. for i := range b {
  13. b[i] ^= key[pos&3]
  14. pos++
  15. }
  16. return pos & 3
  17. }
  18. func notzero(b []byte) int {
  19. for i := range b {
  20. if b[i] != 0 {
  21. return i
  22. }
  23. }
  24. return -1
  25. }
  26. func TestMaskBytes(t *testing.T) {
  27. key := [4]byte{1, 2, 3, 4}
  28. for size := 1; size <= 1024; size++ {
  29. for align := 0; align < wordSize; align++ {
  30. for pos := 0; pos < 4; pos++ {
  31. b := make([]byte, size+align)[align:]
  32. maskBytes(key, pos, b)
  33. maskBytesByByte(key, pos, b)
  34. if i := notzero(b); i >= 0 {
  35. t.Errorf("size:%d, align:%d, pos:%d, offset:%d", size, align, pos, i)
  36. }
  37. }
  38. }
  39. }
  40. }
  41. func BenchmarkMaskBytes(b *testing.B) {
  42. for _, size := range []int{2, 4, 8, 16, 32, 512, 1024} {
  43. b.Run(fmt.Sprintf("size-%d", size), func(b *testing.B) {
  44. for _, align := range []int{wordSize / 2} {
  45. b.Run(fmt.Sprintf("align-%d", align), func(b *testing.B) {
  46. for _, fn := range []struct {
  47. name string
  48. fn func(key [4]byte, pos int, b []byte) int
  49. }{
  50. {"byte", maskBytesByByte},
  51. {"word", maskBytes},
  52. } {
  53. b.Run(fn.name, func(b *testing.B) {
  54. key := newMaskKey()
  55. data := make([]byte, size+align)[align:]
  56. for i := 0; i < b.N; i++ {
  57. fn.fn(key, 0, data)
  58. }
  59. b.SetBytes(int64(len(data)))
  60. })
  61. }
  62. })
  63. }
  64. })
  65. }
  66. }