| 1 |
// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley |
| 2 |
// SPDX-License-Identifier: MIT |
| 3 |
|
| 4 |
// Package radix provides a radix tree (prefix tree) implementation optimized for |
| 5 |
// URL path matching with support for parameterized segments. |
| 6 |
// |
| 7 |
// The tree provides O(k) lookup complexity where k is the number of path segments |
| 8 |
// (typically 3-5 for REST APIs), making it ideal for routing and path matching. |
| 9 |
// |
| 10 |
// Example usage: |
| 11 |
// |
| 12 |
// tree := radix.New[*MyHandler]() |
| 13 |
// tree.Insert("/users/{id}", handler1) |
| 14 |
// tree.Insert("/users/{id}/posts", handler2) |
| 15 |
// |
| 16 |
// handler, path, found := tree.Lookup("/users/123/posts") |
| 17 |
// // handler = handler2, path = "/users/{id}/posts", found = true |
| 18 |
package radix |
| 19 |
|
| 20 |
import "strings" |
| 21 |
|
| 22 |
// Tree is a radix tree optimized for URL path matching. |
| 23 |
// It supports both literal path segments and parameterized segments like {id}. |
| 24 |
// T is the type of value stored at leaf nodes. |
| 25 |
type Tree[T any] struct { |
| 26 |
root *node[T] |
| 27 |
size int |
| 28 |
} |
| 29 |
|
| 30 |
// node represents a node in the radix tree. |
| 31 |
type node[T any] struct { |
| 32 |
// children maps literal path segments to child nodes |
| 33 |
children map[string]*node[T] |
| 34 |
|
| 35 |
// paramChild handles parameterized segments like {id} |
| 36 |
// Only one param child is allowed per node |
| 37 |
paramChild *node[T] |
| 38 |
|
| 39 |
// paramName stores the parameter name without braces (e.g., "id" from "{id}") |
| 40 |
paramName string |
| 41 |
|
| 42 |
// leaf contains the stored value and path template for endpoints |
| 43 |
leaf *leafData[T] |
| 44 |
} |
| 45 |
|
| 46 |
// leafData stores the value and original path template for a leaf node. |
| 47 |
type leafData[T any] struct { |
| 48 |
value T |
| 49 |
path string |
| 50 |
} |
| 51 |
|
| 52 |
// New creates a new empty radix tree. |
| 53 |
func New[T any]() *Tree[T] { |
| 54 |
return &Tree[T]{ |
| 55 |
root: &node[T]{ |
| 56 |
children: make(map[string]*node[T]), |
| 57 |
}, |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
// Insert adds a path and its associated value to the tree. |
| 62 |
// The path should use {param} syntax for parameterized segments. |
| 63 |
// Examples: "/users", "/users/{id}", "/users/{userId}/posts/{postId}" |
| 64 |
// |
| 65 |
// Returns true if a new path was inserted, false if an existing path was updated. |
| 66 |
func (t *Tree[T]) Insert(path string, value T) bool { |
| 67 |
if t.root == nil { |
| 68 |
t.root = &node[T]{children: make(map[string]*node[T])} |
| 69 |
} |
| 70 |
|
| 71 |
segments := splitPath(path) |
| 72 |
n := t.root |
| 73 |
isNew := true |
| 74 |
|
| 75 |
for _, seg := range segments { |
| 76 |
if isParam(seg) { |
| 77 |
// Parameter segment |
| 78 |
if n.paramChild == nil { |
| 79 |
n.paramChild = &node[T]{ |
| 80 |
children: make(map[string]*node[T]), |
| 81 |
paramName: extractParamName(seg), |
| 82 |
} |
| 83 |
} |
| 84 |
n = n.paramChild |
| 85 |
} else { |
| 86 |
// Literal segment |
| 87 |
child, exists := n.children[seg] |
| 88 |
if !exists { |
| 89 |
child = &node[T]{children: make(map[string]*node[T])} |
| 90 |
n.children[seg] = child |
| 91 |
} |
| 92 |
n = child |
| 93 |
} |
| 94 |
} |
| 95 |
|
| 96 |
// Check if this is a new path or an update |
| 97 |
if n.leaf != nil { |
| 98 |
isNew = false |
| 99 |
} else { |
| 100 |
t.size++ |
| 101 |
} |
| 102 |
|
| 103 |
// Set the leaf data |
| 104 |
n.leaf = &leafData[T]{ |
| 105 |
value: value, |
| 106 |
path: path, |
| 107 |
} |
| 108 |
|
| 109 |
return isNew |
| 110 |
} |
| 111 |
|
| 112 |
// Lookup finds the value for a given URL path. |
| 113 |
// Returns the value, the matched path template, and whether a match was found. |
| 114 |
// |
| 115 |
// Literal matches take precedence over parameter matches per OpenAPI specification. |
| 116 |
// For example, "/users/admin" will match "/users/admin" before "/users/{id}". |
| 117 |
func (t *Tree[T]) Lookup(urlPath string) (value T, matchedPath string, found bool) { |
| 118 |
var zero T |
| 119 |
if t.root == nil { |
| 120 |
return zero, "", false |
| 121 |
} |
| 122 |
|
| 123 |
segments := splitPath(urlPath) |
| 124 |
leaf := t.lookupRecursive(t.root, segments, 0) |
| 125 |
|
| 126 |
if leaf != nil { |
| 127 |
return leaf.value, leaf.path, true |
| 128 |
} |
| 129 |
return zero, "", false |
| 130 |
} |
| 131 |
|
| 132 |
// lookupRecursive performs the tree traversal. |
| 133 |
// It prioritizes literal matches over parameter matches. |
| 134 |
func (t *Tree[T]) lookupRecursive(n *node[T], segments []string, depth int) *leafData[T] { |
| 135 |
// Base case: consumed all segments |
| 136 |
if depth == len(segments) { |
| 137 |
return n.leaf |
| 138 |
} |
| 139 |
|
| 140 |
seg := segments[depth] |
| 141 |
|
| 142 |
// Try literal match first (higher specificity) |
| 143 |
if child, exists := n.children[seg]; exists { |
| 144 |
if result := t.lookupRecursive(child, segments, depth+1); result != nil { |
| 145 |
return result |
| 146 |
} |
| 147 |
} |
| 148 |
|
| 149 |
// Fall back to parameter match |
| 150 |
if n.paramChild != nil { |
| 151 |
if result := t.lookupRecursive(n.paramChild, segments, depth+1); result != nil { |
| 152 |
return result |
| 153 |
} |
| 154 |
} |
| 155 |
|
| 156 |
return nil |
| 157 |
} |
| 158 |
|
| 159 |
// Size returns the number of paths stored in the tree. |
| 160 |
func (t *Tree[T]) Size() int { |
| 161 |
return t.size |
| 162 |
} |
| 163 |
|
| 164 |
// Clear removes all entries from the tree. |
| 165 |
func (t *Tree[T]) Clear() { |
| 166 |
t.root = &node[T]{children: make(map[string]*node[T])} |
| 167 |
t.size = 0 |
| 168 |
} |
| 169 |
|
| 170 |
// Walk calls the given function for each path in the tree. |
| 171 |
// The function receives the path template and its associated value. |
| 172 |
// If the function returns false, iteration stops. |
| 173 |
func (t *Tree[T]) Walk(fn func(path string, value T) bool) { |
| 174 |
if t.root == nil { |
| 175 |
return |
| 176 |
} |
| 177 |
t.walkRecursive(t.root, fn) |
| 178 |
} |
| 179 |
|
| 180 |
func (t *Tree[T]) walkRecursive(n *node[T], fn func(path string, value T) bool) bool { |
| 181 |
if n.leaf != nil { |
| 182 |
if !fn(n.leaf.path, n.leaf.value) { |
| 183 |
return false |
| 184 |
} |
| 185 |
} |
| 186 |
|
| 187 |
for _, child := range n.children { |
| 188 |
if !t.walkRecursive(child, fn) { |
| 189 |
return false |
| 190 |
} |
| 191 |
} |
| 192 |
|
| 193 |
if n.paramChild != nil { |
| 194 |
if !t.walkRecursive(n.paramChild, fn) { |
| 195 |
return false |
| 196 |
} |
| 197 |
} |
| 198 |
|
| 199 |
return true |
| 200 |
} |
| 201 |
|
| 202 |
// splitPath splits a path into segments, removing empty segments. |
| 203 |
// "/users/{id}/posts" -> ["users", "{id}", "posts"] |
| 204 |
func splitPath(path string) []string { |
| 205 |
path = strings.Trim(path, "/") |
| 206 |
if path == "" { |
| 207 |
return nil |
| 208 |
} |
| 209 |
|
| 210 |
parts := strings.Split(path, "/") |
| 211 |
|
| 212 |
// Filter out empty segments (from double slashes, etc.) |
| 213 |
result := make([]string, 0, len(parts)) |
| 214 |
for _, p := range parts { |
| 215 |
if p != "" { |
| 216 |
result = append(result, p) |
| 217 |
} |
| 218 |
} |
| 219 |
return result |
| 220 |
} |
| 221 |
|
| 222 |
// isParam checks if a segment is a parameter (e.g., "{id}") |
| 223 |
func isParam(seg string) bool { |
| 224 |
return len(seg) > 2 && seg[0] == '{' && seg[len(seg)-1] == '}' |
| 225 |
} |
| 226 |
|
| 227 |
// extractParamName extracts the parameter name from a segment. |
| 228 |
// "{id}" -> "id", "{userId}" -> "userId" |
| 229 |
func extractParamName(seg string) string { |
| 230 |
if len(seg) > 2 && seg[0] == '{' && seg[len(seg)-1] == '}' { |
| 231 |
return seg[1 : len(seg)-1] |
| 232 |
} |
| 233 |
return seg |
| 234 |
} |