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

uuid.go 1.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright © 2023 OpenIM open source community. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package utils
  15. import (
  16. "fmt"
  17. "github.com/gofrs/uuid"
  18. )
  19. // GenUUID generate uuid.
  20. func GenUUID() string {
  21. return uuid.Must(uuid.NewV4()).String()
  22. }
  23. // GenUUIDWithoutHyphen generate uuid without hyphen.
  24. func GenUUIDWithoutHyphen() string {
  25. return toString(uuid.Must(uuid.NewV4()))
  26. }
  27. // encodeCanonical encodes the canonical RFC-4122 form of UUID u into the
  28. // first 36 bytes dst.
  29. func encodeCanonical(dst []byte, u uuid.UUID) {
  30. const hextable = "0123456789abcdef"
  31. dst[8] = '-'
  32. dst[13] = '-'
  33. dst[18] = '-'
  34. dst[23] = '-'
  35. for i, x := range [16]byte{
  36. 0, 2, 4, 6,
  37. 9, 11,
  38. 14, 16,
  39. 19, 21,
  40. 24, 26, 28, 30, 32, 34,
  41. } {
  42. c := u[i]
  43. dst[x] = hextable[c>>4]
  44. dst[x+1] = hextable[c&0x0f]
  45. }
  46. }
  47. // String returns a canonical RFC-4122 string representation of the UUID:
  48. // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, but delete separator -.
  49. func toString(u uuid.UUID) string {
  50. var buf [36]byte
  51. encodeCanonical(buf[:], u)
  52. return fmt.Sprintf("%s%s%s%s%s", buf[0:7], buf[9:12], buf[14:17], buf[19:22], buf[24:])
  53. }