Skip to content

Instantly share code, notes, and snippets.

@mokiat
Last active August 29, 2015 14:28
Show Gist options
  • Save mokiat/c4828eb9ccf9d319e236 to your computer and use it in GitHub Desktop.
Save mokiat/c4828eb9ccf9d319e236 to your computer and use it in GitHub Desktop.
An example FrameHeap in Go
package main
import "fmt"
import "unsafe"
func NewFrameHeap(size int) *FrameHeap {
buffer := make([]uint8, size)
location := uintptr(unsafe.Pointer(&buffer[0]))
return &FrameHeap{
buffer: buffer, // Store it to prevent GC?
start: location,
current: location,
}
}
type FrameHeap struct {
buffer []uint8
start uintptr
current uintptr
}
func (h *FrameHeap) Allocate(count uintptr) unsafe.Pointer {
result := h.current
h.current += count
return unsafe.Pointer(&result)
}
func (h *FrameHeap) Reset() {
for i := range h.buffer {
h.buffer[i] = 0
}
h.current = h.start
}
type Vector struct {
X, Y, Z float32
}
type Counter struct {
Value int
}
func main() {
heap := NewFrameHeap(64)
vec := *(**Vector)(heap.Allocate(unsafe.Sizeof(Vector{})))
vec.X = 11.0
vec.Y = 22.0
vec.Z = 33.0
cnt := *(**Counter)(heap.Allocate(unsafe.Sizeof(Counter{})))
cnt.Value = 951
fmt.Printf("Vector: %#v\n", vec)
fmt.Printf("Counter: %#v\n", cnt)
fmt.Printf("Heap: %#v\n", heap.buffer)
fmt.Println()
fmt.Println("Clearing heap...")
heap.Reset()
fmt.Println()
fmt.Printf("Vector: %#v\n", vec)
fmt.Printf("Counter: %#v\n", cnt)
fmt.Printf("Heap: %#v\n", heap.buffer)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment