github.com/drone/go-convert@v0.0.0-20240307072510-6bd371c65e61/internal/store/store.go (about) 1 // Copyright 2022 Harness, Inc. 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 package store 16 17 import "strconv" 18 19 // Identifiers stores identifiers. 20 type Identifiers struct { 21 store map[string]struct{} 22 } 23 24 // New returns a new identifier store. 25 func New() *Identifiers { 26 return &Identifiers{ 27 store: map[string]struct{}{}, 28 } 29 } 30 31 // Register registers a name with the store. 32 func (s *Identifiers) Register(name string) bool { 33 if _, ok := s.store[name]; ok { 34 return false 35 } 36 s.store[name] = struct{}{} 37 return true 38 } 39 40 // Generage generates and registeres a unique name with the 41 // store. If the base name is already registered, a unique 42 // suffix is appended to the name. 43 func (s *Identifiers) Generate(name ...string) string { 44 var base string 45 // choose the first non-empty name. 46 for _, s := range name { 47 if s != "" { 48 base = s 49 break 50 } 51 } 52 53 // register the name as-is 54 if s.Register(base) { 55 return base 56 } 57 // append a suffix to the name and register 58 // the first unique combination. 59 for i := 1; ; i++ { 60 next := base + strconv.Itoa(i) 61 if s.Register(next) { 62 return next 63 } 64 } 65 }