stufflog graphql server
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
902 B

  1. package generate
  2. import (
  3. "crypto/rand"
  4. "encoding/binary"
  5. mathRand "math/rand"
  6. "strconv"
  7. )
  8. const alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"
  9. func generateWeak(length int, prefix string) string {
  10. result := prefix
  11. for len(result) < length {
  12. result += string(alphabet[mathRand.Intn(len(alphabet))])
  13. }
  14. return result
  15. }
  16. // Generate generates an ID either strongly or weakly depending on the system.
  17. func Generate(length int, prefix string) string {
  18. var buffer [32]byte
  19. result := prefix
  20. offset := 0
  21. _, err := rand.Read(buffer[:32])
  22. if err != nil {
  23. return generateWeak(length, prefix)
  24. }
  25. for len(result) < length {
  26. result += strconv.FormatUint(binary.LittleEndian.Uint64(buffer[offset:]), 36)
  27. offset += 8
  28. if offset >= 32 {
  29. _, err = rand.Read(buffer[:32])
  30. if err != nil {
  31. return generateWeak(length, prefix)
  32. }
  33. offset = 0
  34. }
  35. }
  36. return result[:length]
  37. }