...

Source file src/github.com/alibabacloud-go/tea-utils/service/util.go

Documentation: github.com/alibabacloud-go/tea-utils/service

     1  package service
     2  
     3  import (
     4  	"crypto/md5"
     5  	"crypto/rand"
     6  	"encoding/hex"
     7  	"hash"
     8  	rand2 "math/rand"
     9  )
    10  
    11  type UUID [16]byte
    12  
    13  const numBytes = "1234567890"
    14  
    15  func getUUID() (uuidHex string) {
    16  	uuid := newUUID()
    17  	uuidHex = hex.EncodeToString(uuid[:])
    18  	return
    19  }
    20  
    21  func randStringBytes(n int) string {
    22  	b := make([]byte, n)
    23  	for i := range b {
    24  		b[i] = numBytes[rand2.Intn(len(numBytes))]
    25  	}
    26  	return string(b)
    27  }
    28  
    29  func newUUID() UUID {
    30  	ns := UUID{}
    31  	safeRandom(ns[:])
    32  	u := newFromHash(md5.New(), ns, randStringBytes(16))
    33  	u[6] = (u[6] & 0x0f) | (byte(2) << 4)
    34  	u[8] = (u[8]&(0xff>>2) | (0x02 << 6))
    35  
    36  	return u
    37  }
    38  
    39  func newFromHash(h hash.Hash, ns UUID, name string) UUID {
    40  	u := UUID{}
    41  	h.Write(ns[:])
    42  	h.Write([]byte(name))
    43  	copy(u[:], h.Sum(nil))
    44  
    45  	return u
    46  }
    47  
    48  func safeRandom(dest []byte) {
    49  	if _, err := rand.Read(dest); err != nil {
    50  		panic(err)
    51  	}
    52  }
    53  

View as plain text