pool.go 616 B

12345678910111213141516171819202122232425262728293031
  1. package rt
  2. import (
  3. "unsafe"
  4. )
  5. type SlicePool struct {
  6. pool unsafe.Pointer
  7. len int
  8. index int
  9. typ uintptr
  10. }
  11. func NewPool(typ *GoType, size int) SlicePool {
  12. return SlicePool{pool: newarray(typ, size), len: size, typ: uintptr(unsafe.Pointer(typ))}
  13. }
  14. func (self *SlicePool) GetSlice(size int) unsafe.Pointer {
  15. // pool is full, fallback to normal alloc
  16. if size > self.Remain() {
  17. return newarray(AsGoType(self.typ), size)
  18. }
  19. ptr := PtrAdd(self.pool, uintptr(self.index)* AsGoType(self.typ).Size)
  20. self.index += size
  21. return ptr
  22. }
  23. func (self *SlicePool) Remain() int {
  24. return self.len - self.index
  25. }