add arena package

This commit is contained in:
siddontang 2014-07-08 14:48:55 +08:00
parent 41fb29162e
commit f9bb9e3d84
2 changed files with 56 additions and 0 deletions

28
arena/arena.go Normal file
View File

@ -0,0 +1,28 @@
package arena
type Arena struct {
buf []byte
size int
}
func NewArena(size int) *Arena {
a := new(Arena)
a.size = size
a.buf = make([]byte, size, size)
return a
}
func (a *Arena) Make(size int) []byte {
if a.size < size {
return make([]byte, size)
} else if len(a.buf) < size {
a.buf = make([]byte, a.size)
}
b := a.buf[0:size]
a.buf = a.buf[size:]
return b
}

28
arena/arena_test.go Normal file
View File

@ -0,0 +1,28 @@
package arena
import (
"fmt"
"testing"
)
func TestArena(t *testing.T) {
a := NewArena(100)
for i := 0; i < 50; i++ {
a.buf[i] = 1
}
for i := 50; i < 100; i++ {
a.buf[i] = 2
}
b1 := a.Make(50)
b2 := a.Make(30)
b3 := a.Make(40)
fmt.Printf("%p %d\n", b1, b1[49])
fmt.Printf("%p %d\n", b2, b2[29])
fmt.Printf("%p %d\n", b3, b3[39])
}