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