From f9bb9e3d84b0c86ccbe0209b3d1f9712ee39011e Mon Sep 17 00:00:00 2001 From: siddontang Date: Tue, 8 Jul 2014 14:48:55 +0800 Subject: [PATCH] add arena package --- arena/arena.go | 28 ++++++++++++++++++++++++++++ arena/arena_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 arena/arena.go create mode 100644 arena/arena_test.go diff --git a/arena/arena.go b/arena/arena.go new file mode 100644 index 0000000..ceec084 --- /dev/null +++ b/arena/arena.go @@ -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 +} diff --git a/arena/arena_test.go b/arena/arena_test.go new file mode 100644 index 0000000..607b2a4 --- /dev/null +++ b/arena/arena_test.go @@ -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]) +}