github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/asset-format/main.go (about)

     1  // A memory mappable, zero-copy asset format based on:
     2  //   https://www.youtube.com/watch?v=qZM2B4D7hZs
     3  //
     4  // Warning: using this with mmap is not trivial
     5  //          https://groups.google.com/forum/#!topic/golang-nuts/9iTCLArQmYc
     6  package main
     7  
     8  import (
     9  	"fmt"
    10  	"reflect"
    11  	"runtime"
    12  	"unsafe"
    13  )
    14  
    15  type Ref int32
    16  
    17  func (r *Ref) Lock() {}
    18  
    19  func (r *Ref) Clear() {
    20  	*r = 0
    21  }
    22  func (r *Ref) Set(v unsafe.Pointer) {
    23  	*r = Ref(uintptr(unsafe.Pointer(v)) - uintptr(unsafe.Pointer(r)))
    24  }
    25  func (r *Ref) Get() unsafe.Pointer {
    26  	return unsafe.Pointer(uintptr(unsafe.Pointer(r)) + uintptr(*r))
    27  }
    28  
    29  type Node struct {
    30  	Value  uint32
    31  	_Left  Ref
    32  	_Right Ref
    33  }
    34  
    35  func (n *Node) Left() *Node  { return (*Node)(n._Left.Get()) }
    36  func (n *Node) Right() *Node { return (*Node)(n._Right.Get()) }
    37  
    38  type Stream struct {
    39  	Data [1 << 10]byte
    40  	Head int
    41  }
    42  
    43  func (s *Stream) Write(v interface{}) unsafe.Pointer {
    44  	rv := reflect.ValueOf(v)
    45  	rt := reflect.TypeOf(v)
    46  	size := int(rt.Elem().Size())
    47  
    48  	base := unsafe.Pointer(rv.Pointer())
    49  	data := (*[1 << 10]byte)(base)[:size]
    50  
    51  	p := unsafe.Pointer(&s.Data[s.Head])
    52  	s.Head += copy(s.Data[s.Head:], data)
    53  	return p
    54  }
    55  
    56  func serialize() []byte {
    57  	var stream Stream
    58  	var emptyRef Ref
    59  	index := stream.Write(&emptyRef)
    60  	left := stream.Write(&Node{4129422, 0, 0})
    61  	right := stream.Write(&Node{1238471, 0, 0})
    62  	root := stream.Write(&Node{329501, 0, 0})
    63  
    64  	(*Node)(root)._Left.Set(left)
    65  	(*Node)(root)._Right.Set(right)
    66  	(*Ref)(index).Set(root)
    67  
    68  	return stream.Data[:stream.Head]
    69  }
    70  
    71  func main() {
    72  	data := serialize()
    73  	defer runtime.KeepAlive(data)
    74  
    75  	index := (*Ref)(unsafe.Pointer(&data[0]))
    76  	root := (*Node)(index.Get())
    77  	left := root.Left()
    78  	right := root.Right()
    79  
    80  	fmt.Println(root)
    81  	fmt.Println(left)
    82  	fmt.Println(right)
    83  }