Files
triplex/cmd/triplex-example/main.go
micha c8f218c032
Some checks failed
CI / test (push) Failing after 16s
Updated error handling in the example command tool.
2026-02-21 04:37:59 +01:00

76 lines
1.4 KiB
Go

// Copyright (c) 2026 Micha Hoiting
package main
import (
"crypto/rand"
"encoding/binary"
"errors"
"flag"
"fmt"
"os"
"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() {
complete := flag.String("complete", "", "complete code without checksum in format LLL-NNN-L")
flag.Parse()
if *complete != "" {
full, idx, err := serial.CompleteCode(*complete)
if err != nil {
fmt.Println("complete error:", err)
os.Exit(1)
}
fmt.Println("code:", full)
fmt.Println("idx:", idx)
os.Exit(0)
}
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")
os.Exit(1)
}
if errors.Is(err, serial.ErrNoAvailableIndex) {
fmt.Println("no available index found")
os.Exit(1)
}
fmt.Println("unexpected error:", err)
os.Exit(1)
}
fmt.Println("code:", code)
fmt.Println("idx:", idx)
}