Change BrokerContext from random number to counter

This commit is contained in:
NagyZoltanPeter 2025-12-17 14:55:58 +01:00
parent 4b696856c7
commit 800e497585
No known key found for this signature in database
GPG Key ID: 3E1F97CF4A7B6F42

View File

@ -1,4 +1,4 @@
import std/[strutils, sysrand]
import std/[strutils, concurrency/atomics]
type BrokerContext* = distinct uint32
@ -9,18 +9,10 @@ func `$`*(bc: BrokerContext): string =
const DefaultBrokerContext* = BrokerContext(0xCAFFE14E'u32)
var gContextCounter: Atomic[uint32]
proc NewBrokerContext*(): BrokerContext =
## Generates a random non-default broker context (as a raw uint32).
##
## The default broker context is reserved for the provider at index 0.
## This helper never returns that value.
for _ in 0 ..< 16:
let b = urandom(4)
if b.len != 4:
continue
let key =
(uint32(b[0]) shl 24) or (uint32(b[1]) shl 16) or (uint32(b[2]) shl 8) or
uint32(b[3])
if key != uint32(DefaultBrokerContext):
return BrokerContext(key)
BrokerContext(1'u32)
var nextId = gContextCounter.fetchAdd(1, moRelaxed)
if nextId == uint32(DefaultBrokerContext):
nextId = gContextCounter.fetchAdd(1, moRelaxed)
return BrokerContext(nextId)