Implement generics, fix race condition in network

This commit is contained in:
kayos@tcp.direct 2022-03-26 08:25:52 -07:00
parent f14edc3ef8
commit 1c8fd87a7f
Signed by: kayos
GPG Key ID: 4B841471B4BEE979
4 changed files with 25 additions and 25 deletions

View File

@ -4,8 +4,9 @@ import (
crip "crypto/rand"
"encoding/binary"
"math/rand"
"nullprogram.com/x/rng"
"time"
"nullprogram.com/x/rng"
)
func RandomStrChoice(choice []string) string {
@ -19,7 +20,7 @@ func RandomStrChoice(choice []string) string {
func GetCryptoSeed() int64 {
var seed int64
binary.Read(crip.Reader, binary.BigEndian, &seed)
_ = binary.Read(crip.Reader, binary.BigEndian, &seed)
return seed
}
@ -29,6 +30,11 @@ func GetOptimizedRand() *rand.Rand {
return rand.New(r)
}
func RNGUint32() uint32 {
rng := GetOptimizedRand()
return rng.Uint32()
}
func RNG(n int) int {
rng := GetOptimizedRand()
return rng.Intn(n)

View File

@ -5,6 +5,12 @@ import (
"testing"
)
func check[T comparable](zero T, one T, t *testing.T) {
if zero == one {
t.Errorf("hit a duplicate! %v == %v", zero, one)
}
}
func Test_RNG(t *testing.T) {
RandSleepMS(5)
if OneInA(1000000) {
@ -16,16 +22,9 @@ func Test_RNG(t *testing.T) {
}
for n := 0; n != 500; n++ {
zero := RNG(55555)
one := RNG(55555)
// t.Logf("Random0: %d Random1: %d", zero, one)
if zero == one {
t.Errorf("RNG hit a duplicate! %d == %d", zero, one)
}
zero = 0
one = 0
check(RNG(55555), RNG(55555), t)
check(RNGUint32(), RNGUint32(), t)
}
}
func randStrChecks(zero, one string, t *testing.T) {
@ -35,9 +34,7 @@ func randStrChecks(zero, one string, t *testing.T) {
if len(zero) != 55 || len(one) != 55 {
t.Fatalf("RandStr output length inconsistency, len(zero) is %d and len(one) is %d, but both should have been 55", len(zero), len(one))
}
if zero == one {
t.Fatalf("RandStr hit a duplicate, %s == %s", zero, one)
}
check(zero, one, t)
}
func Test_RandStr(t *testing.T) {

2
go.mod
View File

@ -1,6 +1,6 @@
module git.tcp.direct/kayos/common
go 1.17
go 1.18
require (
github.com/rs/zerolog v1.26.1

View File

@ -6,7 +6,7 @@ import ipa "inet.af/netaddr"
// returning a channel that will stream all the individual netaddr IPs within the given range or prefix.
// Alternatively, feed it a string in prefix or range format. (192.168.69.0/24) (192.168.69.0-192.168.69.254)
// Will return nil value if input is invalid.
func IterateNetRange(ips interface{}) chan *ipa.IP {
func IterateNetRange(ips interface{}) chan ipa.IP {
var addrs ipa.IPRange
switch ips.(type) {
@ -29,18 +29,15 @@ func IterateNetRange(ips interface{}) chan *ipa.IP {
return nil
}
ch := make(chan *ipa.IP)
go func(ret chan *ipa.IP) {
var head ipa.IP
head = addrs.From()
end := addrs.To()
for head != end {
ch := make(chan ipa.IP)
go func(ret chan ipa.IP) {
for head := addrs.From(); head != addrs.To(); head = head.Next() {
if !head.IsUnspecified() {
ret <- &head
ret <- head
} else {
close(ret)
}
head = head.Next()
}
close(ret)
}(ch)
return ch
}