Reduced memory usage

This commit is contained in:
2023-09-02 09:19:11 +02:00
parent e5b0eb443a
commit 7070897e70
9 changed files with 95 additions and 84 deletions

36
Tree.go
View File

@ -1,9 +1,5 @@
package router
import (
"strings"
)
// controlFlow tells the main loop what it should do next.
type controlFlow int
@ -16,23 +12,11 @@ const (
// Tree represents a radix tree.
type Tree[T any] struct {
static map[string]T
root treeNode[T]
canBeStatic [2048]bool
root treeNode[T]
}
// Add adds a new element to the tree.
func (tree *Tree[T]) Add(path string, data T) {
if !strings.Contains(path, ":") && !strings.Contains(path, "*") {
if tree.static == nil {
tree.static = map[string]T{}
}
tree.static[path] = data
tree.canBeStatic[len(path)] = true
return
}
// Search tree for equal parts until we can no longer proceed
i := 0
offset := 0
@ -114,11 +98,11 @@ func (tree *Tree[T]) Add(path string, data T) {
}
// Lookup finds the data for the given path.
func (tree *Tree[T]) Lookup(path string) (T, []Parameter) {
var params []Parameter
func (tree *Tree[T]) Lookup(path string) (T, []keyValue) {
var params []keyValue
data := tree.LookupNoAlloc(path, func(key string, value string) {
params = append(params, Parameter{key, value})
params = append(params, keyValue{key, value})
})
return data, params
@ -126,14 +110,6 @@ func (tree *Tree[T]) Lookup(path string) (T, []Parameter) {
// LookupNoAlloc finds the data for the given path without using any memory allocations.
func (tree *Tree[T]) LookupNoAlloc(path string, addParameter func(key string, value string)) T {
if tree.canBeStatic[len(path)] {
handler, found := tree.static[path]
if found {
return handler
}
}
var (
i uint
offset uint
@ -241,8 +217,4 @@ func (tree *Tree[T]) Bind(transform func(T) T) {
tree.root.each(func(node *treeNode[T]) {
node.data = transform(node.data)
})
for key, value := range tree.static {
tree.static[key] = transform(value)
}
}