name_lexem.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright 2015 go-swagger maintainers
  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 swag
  15. import (
  16. "unicode"
  17. "unicode/utf8"
  18. )
  19. type (
  20. lexemKind uint8
  21. nameLexem struct {
  22. original string
  23. matchedInitialism string
  24. kind lexemKind
  25. }
  26. )
  27. const (
  28. lexemKindCasualName lexemKind = iota
  29. lexemKindInitialismName
  30. )
  31. func newInitialismNameLexem(original, matchedInitialism string) nameLexem {
  32. return nameLexem{
  33. kind: lexemKindInitialismName,
  34. original: original,
  35. matchedInitialism: matchedInitialism,
  36. }
  37. }
  38. func newCasualNameLexem(original string) nameLexem {
  39. return nameLexem{
  40. kind: lexemKindCasualName,
  41. original: original,
  42. }
  43. }
  44. func (l nameLexem) GetUnsafeGoName() string {
  45. if l.kind == lexemKindInitialismName {
  46. return l.matchedInitialism
  47. }
  48. var (
  49. first rune
  50. rest string
  51. )
  52. for i, orig := range l.original {
  53. if i == 0 {
  54. first = orig
  55. continue
  56. }
  57. if i > 0 {
  58. rest = l.original[i:]
  59. break
  60. }
  61. }
  62. if len(l.original) > 1 {
  63. b := poolOfBuffers.BorrowBuffer(utf8.UTFMax + len(rest))
  64. defer func() {
  65. poolOfBuffers.RedeemBuffer(b)
  66. }()
  67. b.WriteRune(unicode.ToUpper(first))
  68. b.WriteString(lower(rest))
  69. return b.String()
  70. }
  71. return l.original
  72. }
  73. func (l nameLexem) GetOriginal() string {
  74. return l.original
  75. }
  76. func (l nameLexem) IsInitialism() bool {
  77. return l.kind == lexemKindInitialismName
  78. }