Use a fully random async_id rather than a uuid

This commit is contained in:
Kovid Goyal 2022-08-26 10:39:18 +05:30
parent 4a49c3940a
commit b1f9139ca5
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
3 changed files with 20 additions and 3 deletions

View File

@ -39,7 +39,7 @@ func create_rc_CMD_NAME(args []string) (*utils.RemoteControlCmd, error) {
NoResponse: NO_RESPONSE_BASE,
}
if IS_ASYNC {
async_id, err := utils.HumanUUID4()
async_id, err := utils.HumanRandomId(128)
if err != nil {
return nil, err
}

View File

@ -3,6 +3,7 @@
package utils
import (
"crypto/rand"
"math"
"math/big"
@ -70,6 +71,15 @@ func CreateShortUUID(alphabet string) *ShortUUID {
return &ans
}
func (self *ShortUUID) Random(num_bits int64) (string, error) {
max := big.NewInt(0).Exp(big.NewInt(2), big.NewInt(num_bits), nil)
bi, err := rand.Int(rand.Reader, max)
if err != nil {
return "", err
}
return num_to_string(bi, self.alphabet, &self.alphabet_len, self.pad_to_length), nil
}
func (self *ShortUUID) Uuid4() (string, error) {
b, err := uuid.NewRandom()
if err != nil {
@ -92,3 +102,10 @@ func HumanUUID4() (string, error) {
}
return HumanUUID.Uuid4()
}
func HumanRandomId(num_bits int64) (string, error) {
if HumanUUID == nil {
HumanUUID = CreateShortUUID(HUMAN_ALPHABET)
}
return HumanUUID.Random(num_bits)
}

View File

@ -8,11 +8,11 @@ import (
)
func TestShortUUID(t *testing.T) {
a, err := HumanUUID4()
a, err := HumanRandomId(128)
if err != nil {
t.Fatal(err)
}
b, err := HumanUUID4()
b, err := HumanRandomId(128)
if err != nil {
t.Fatal(err)
}