本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
1.4KB

  1. package match
  2. import (
  3. "sync"
  4. )
  5. type SomePool interface {
  6. Get() []int
  7. Put([]int)
  8. }
  9. var segmentsPools [1024]sync.Pool
  10. func toPowerOfTwo(v int) int {
  11. v--
  12. v |= v >> 1
  13. v |= v >> 2
  14. v |= v >> 4
  15. v |= v >> 8
  16. v |= v >> 16
  17. v++
  18. return v
  19. }
  20. const (
  21. cacheFrom = 16
  22. cacheToAndHigher = 1024
  23. cacheFromIndex = 15
  24. cacheToAndHigherIndex = 1023
  25. )
  26. var (
  27. segments0 = []int{0}
  28. segments1 = []int{1}
  29. segments2 = []int{2}
  30. segments3 = []int{3}
  31. segments4 = []int{4}
  32. )
  33. var segmentsByRuneLength [5][]int = [5][]int{
  34. 0: segments0,
  35. 1: segments1,
  36. 2: segments2,
  37. 3: segments3,
  38. 4: segments4,
  39. }
  40. func init() {
  41. for i := cacheToAndHigher; i >= cacheFrom; i >>= 1 {
  42. func(i int) {
  43. segmentsPools[i-1] = sync.Pool{New: func() interface{} {
  44. return make([]int, 0, i)
  45. }}
  46. }(i)
  47. }
  48. }
  49. func getTableIndex(c int) int {
  50. p := toPowerOfTwo(c)
  51. switch {
  52. case p >= cacheToAndHigher:
  53. return cacheToAndHigherIndex
  54. case p <= cacheFrom:
  55. return cacheFromIndex
  56. default:
  57. return p - 1
  58. }
  59. }
  60. func acquireSegments(c int) []int {
  61. // make []int with less capacity than cacheFrom
  62. // is faster than acquiring it from pool
  63. if c < cacheFrom {
  64. return make([]int, 0, c)
  65. }
  66. return segmentsPools[getTableIndex(c)].Get().([]int)[:0]
  67. }
  68. func releaseSegments(s []int) {
  69. c := cap(s)
  70. // make []int with less capacity than cacheFrom
  71. // is faster than acquiring it from pool
  72. if c < cacheFrom {
  73. return
  74. }
  75. segmentsPools[getTableIndex(c)].Put(s)
  76. }
上海开阖软件有限公司 沪ICP备12045867号-1