go.x2ox.com/sorbifolia/random@v0.0.0-20240520090142-6d8be5c4ed59/random_string.go (about) 1 package random 2 3 import ( 4 "go.x2ox.com/sorbifolia/pyrokinesis" 5 ) 6 7 var defaultRandString = newRandString() 8 9 type randString struct { 10 randBytes []byte 11 randBytesLen int 12 } 13 14 func newRandString() *randString { 15 return &randString{ 16 randBytes: []byte(randBytes), 17 randBytesLen: randBytesLen, 18 } 19 } 20 21 func (r *randString) RandString(rn []int) string { 22 arr := make([]byte, len(rn)) 23 for i := range arr { 24 arr[i] = r.randBytes[rn[i]] 25 } 26 return pyrokinesis.Bytes.ToString(arr) 27 } 28 29 func (r *randString) SetRandBytes(data []byte) *randString { 30 if len(data) > 256 { 31 panic("data too long") 32 } 33 if hasRepeat(data) { 34 panic("not repeatable") 35 } 36 return &randString{ 37 randBytesLen: len(data), 38 randBytes: data, 39 } 40 } 41 42 func hasRepeat[T comparable](arr []T) bool { 43 m := make(map[T]struct{}) 44 for _, v := range arr { 45 if _, ok := m[v]; ok { 46 return ok 47 } 48 m[v] = struct{}{} 49 } 50 return false 51 }