Various improvements.

This commit is contained in:
2026-02-21 00:34:57 +01:00
parent 8670c509e8
commit 09a1c8dd26
6 changed files with 160 additions and 11 deletions

View File

@@ -0,0 +1,56 @@
package main
import (
"crypto/rand"
"encoding/binary"
"errors"
"fmt"
"git.hoiting.org/micha/triplex/serial"
)
func alreadyUsedByClient(idx uint32) bool {
return idx%2 == 0
}
func myRandomIndex(max uint32) (uint32, error) {
if max == 0 {
return 0, fmt.Errorf("max must be > 0")
}
var buf [4]byte
if _, err := rand.Read(buf[:]); err != nil {
return 0, err
}
return binary.LittleEndian.Uint32(buf[:]) % max, nil
}
func main() {
opts := serial.RandomCodeOptions{
MaxAttempts: 500,
IsInUse: func(idx uint32) bool {
return alreadyUsedByClient(idx)
},
RandomIndex: func(max uint32) (uint32, error) {
return myRandomIndex(max)
},
}
code, idx, err := serial.RandomCodeWithOptions(opts)
if err != nil {
if errors.Is(err, serial.ErrRandomSourceFailed) {
fmt.Println("random source failed")
return
}
if errors.Is(err, serial.ErrNoAvailableIndex) {
fmt.Println("no available index found")
return
}
fmt.Println("unexpected error:", err)
return
}
fmt.Println("code:", code)
fmt.Println("idx:", idx)
}