Skip to content

Instantly share code, notes, and snippets.

@coyove
Created December 12, 2018 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coyove/97abfcd45a5885b97c55dbd883b46740 to your computer and use it in GitHub Desktop.
Save coyove/97abfcd45a5885b97c55dbd883b46740 to your computer and use it in GitHub Desktop.
package main
import (
_ "image/png"
"log"
"net/http"
"strconv"
)
type nodeManager struct {
root *node
minimalNodeSize int
}
type node struct {
start, size int
occupied bool
left *node
right *node
}
func (m *nodeManager) findNode(size int) *node {
if size == 0 {
return nil
}
var _find func(current *node) *node
_find = func(current *node) *node {
if current == nil {
return nil
}
if current.occupied && current.left == nil && current.right == nil {
return nil
}
if !current.occupied {
if size > current.size {
return nil
}
if size > current.size/2 {
current.occupied = true
return current
}
if current.size < m.minimalNodeSize*2 {
current.occupied = true
return current
}
current.split()
}
l := _find(current.left)
if l != nil {
return l
}
return _find(current.right)
}
return _find(m.root)
}
func (n *node) split() {
if n.left != nil || n.right != nil {
panic("already splitted")
}
n.left = &node{
start: n.start,
size: n.size / 2,
}
n.right = &node{
start: n.start + n.size/2,
size: n.size / 2,
}
n.occupied = true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment