Files
iroh-tracker/examples/stack-example.go
cblgh 7bfd1fcf2c implement fixed-size evicting string stack data structure
this stack implementation has a fixed-size. new items are pushed to the
front and, if the capacity has been met, the last item gets evicted.  if
you push an item onto the stack that was already on the stack, this
"bumps" that item by merely moves the item to the front (as opposed to
allowing duplicates). the capacity is set at initialization.

the intended use case for this data structure is for the iroh-tracker to
only keep a fixed amount of topics and, per topic, a fixed amount of
peers. topics that are actively recalled get pushed to the front, and
peers within a topic that are seen often also get pushed to the front.

see examples/stack-example.go for how it can be used

eventually i'll refactor this to use just bytes instead as that is more
useful for the purpose of the tracker. this could also be an opportunity
to look into generics since string & byte are basically interchangeable.
2026-09-06 16:56:43 +02:00

47 lines
1.1 KiB
Go

package main
import (
"gomod.cblgh.org/iroh-tracker/stack"
"fmt"
)
const MAX_TOPICS = 5
const MAX_PEERS = 4
var topicToPeers map[string]*stack.Stack
var topics *stack.Stack
func main() {
topics = stack.NewStack(MAX_TOPICS)
topicToPeers = make(map[string]*stack.Stack)
fmt.Println("topics to peers", topicToPeers)
fmt.Println("topics slice", topics)
visit("hello.topic", "alex")
visit("nice.topic", "alex")
visit("good.topic", "alex")
visit("newer.topic", "alex")
visit("great.topic", "alex")
visit("newest.topic", "alex") // should evict hello.topic
visit("newest.topic", "alex1")
visit("newest.topic", "alex2")
visit("newest.topic", "alex3")
visit("newest.topic", "alex4")
fmt.Printf("%+v\n", topicToPeers)
fmt.Printf("%+v\n", topicToPeers["newest.topic"])
}
func visit(topic, peer string) {
peers, exists := topicToPeers[topic]
if !exists {
peers = stack.NewStack(MAX_PEERS)
topicToPeers[topic] = peers
fmt.Println("topic does not exist")
}
evicted := topics.Push(topic)
peers.Push(peer)
// forget about the old topic
if evicted != "" {
delete(topicToPeers, evicted)
}
}