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.

44 lines
701 B

  1. package mem
  2. import "sync"
  3. var pools []*sync.Pool
  4. const (
  5. min_size = 1024
  6. )
  7. func bitCount(size int) (count int) {
  8. for ; size > min_size; count++ {
  9. size = size >> 1
  10. }
  11. return
  12. }
  13. func init() {
  14. // 1KB ~ 256MB
  15. pools = make([]*sync.Pool, bitCount(1024*1024*256))
  16. for i := 0; i < len(pools); i++ {
  17. slotSize := 1024 << i
  18. pools[i] = &sync.Pool{
  19. New: func() interface{} {
  20. buffer := make([]byte, slotSize)
  21. return &buffer
  22. },
  23. }
  24. }
  25. }
  26. func getSlotPool(size int) *sync.Pool {
  27. index := bitCount(size)
  28. return pools[index]
  29. }
  30. func Allocate(size int) []byte {
  31. slab := *getSlotPool(size).Get().(*[]byte)
  32. return slab[:size]
  33. }
  34. func Free(buf []byte) {
  35. getSlotPool(cap(buf)).Put(&buf)
  36. }