post_go19.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. //go:build go1.9
  15. // +build go1.9
  16. package swag
  17. import (
  18. "sort"
  19. "sync"
  20. )
  21. // indexOfInitialisms is a thread-safe implementation of the sorted index of initialisms.
  22. // Since go1.9, this may be implemented with sync.Map.
  23. type indexOfInitialisms struct {
  24. sortMutex *sync.Mutex
  25. index *sync.Map
  26. }
  27. func newIndexOfInitialisms() *indexOfInitialisms {
  28. return &indexOfInitialisms{
  29. sortMutex: new(sync.Mutex),
  30. index: new(sync.Map),
  31. }
  32. }
  33. func (m *indexOfInitialisms) load(initial map[string]bool) *indexOfInitialisms {
  34. m.sortMutex.Lock()
  35. defer m.sortMutex.Unlock()
  36. for k, v := range initial {
  37. m.index.Store(k, v)
  38. }
  39. return m
  40. }
  41. func (m *indexOfInitialisms) isInitialism(key string) bool {
  42. _, ok := m.index.Load(key)
  43. return ok
  44. }
  45. func (m *indexOfInitialisms) add(key string) *indexOfInitialisms {
  46. m.index.Store(key, true)
  47. return m
  48. }
  49. func (m *indexOfInitialisms) sorted() (result []string) {
  50. m.sortMutex.Lock()
  51. defer m.sortMutex.Unlock()
  52. m.index.Range(func(key, value interface{}) bool {
  53. k := key.(string)
  54. result = append(result, k)
  55. return true
  56. })
  57. sort.Sort(sort.Reverse(byInitialism(result)))
  58. return
  59. }