util.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. package gdnative
  2. import "C"
  3. import (
  4. "strings"
  5. "unicode"
  6. "unsafe"
  7. )
  8. // unsafeToGoString will convert a null pointer with an underlying CString into
  9. // a Go string.
  10. func unsafeToGoString(p unsafe.Pointer) string {
  11. // Cast the pointer to a CString.
  12. cString := (*C.char)(p)
  13. goString := C.GoString(cString)
  14. return goString
  15. }
  16. // camelToSnake will convert the given string from camelcase to snake case.
  17. // Attribution:
  18. // Author: https://github.com/mantenie
  19. // Source: https://github.com/serenize/snaker
  20. func camelToSnake(s string) string { //nolint:deadcode,unused
  21. var result string
  22. var words []string
  23. var lastPos int
  24. rs := []rune(s)
  25. for i := 0; i < len(rs); i++ {
  26. if i > 0 && unicode.IsUpper(rs[i]) {
  27. if initialism := startsWithInitialism(s[lastPos:]); initialism != "" {
  28. words = append(words, initialism)
  29. i += len(initialism) - 1
  30. lastPos = i
  31. continue
  32. }
  33. words = append(words, s[lastPos:i])
  34. lastPos = i
  35. }
  36. }
  37. // append the last word
  38. if s[lastPos:] != "" {
  39. words = append(words, s[lastPos:])
  40. }
  41. for k, word := range words {
  42. if k > 0 {
  43. result += "_"
  44. }
  45. result += strings.ToLower(word)
  46. }
  47. return result
  48. }
  49. // startsWithInitialism returns the initialism if the given string begins with it
  50. func startsWithInitialism(s string) string { //nolint:unused
  51. var initialism string
  52. // the longest initialism is 5 char, the shortest 2
  53. for i := 1; i <= 5; i++ {
  54. if len(s) > i-1 && commonInitialisms[s[:i]] {
  55. initialism = s[:i]
  56. }
  57. }
  58. return initialism
  59. }
  60. // commonInitialisms, taken from
  61. // https://github.com/golang/lint/blob/206c0f020eba0f7fbcfbc467a5eb808037df2ed6/lint.go#L731
  62. var commonInitialisms = map[string]bool{ //nolint:unused
  63. "ACL": true,
  64. "API": true,
  65. "ASCII": true,
  66. "CPU": true,
  67. "CSS": true,
  68. "DNS": true,
  69. "EOF": true,
  70. "GUID": true,
  71. "HTML": true,
  72. "HTTP": true,
  73. "HTTPS": true,
  74. "ID": true,
  75. "IP": true,
  76. "JSON": true,
  77. "LHS": true,
  78. "OS": true,
  79. "QPS": true,
  80. "RAM": true,
  81. "RHS": true,
  82. "RPC": true,
  83. "SLA": true,
  84. "SMTP": true,
  85. "SQL": true,
  86. "SSH": true,
  87. "TCP": true,
  88. "TLS": true,
  89. "TTL": true,
  90. "UDP": true,
  91. "UI": true,
  92. "UID": true,
  93. "UUID": true,
  94. "URI": true,
  95. "URL": true,
  96. "UTF8": true,
  97. "VM": true,
  98. "XML": true,
  99. "XMPP": true,
  100. "XSRF": true,
  101. "XSS": true,
  102. }