57 lines
1.0 KiB
Go
57 lines
1.0 KiB
Go
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)
|
|
}
|