github.com/solo-io/cue@v0.4.7/internal/core/runtime/index.go (about) 1 // Copyright 2020 CUE Authors 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 runtime 16 17 import ( 18 "sync" 19 20 "github.com/solo-io/cue/internal" 21 "github.com/solo-io/cue/internal/core/adt" 22 ) 23 24 func (r *Runtime) IndexToString(i int64) string { 25 return r.index.IndexToString(i) 26 } 27 28 func (r *Runtime) StringToIndex(s string) int64 { 29 return getKey(s) 30 } 31 32 func (r *Runtime) LabelStr(l adt.Feature) string { 33 return l.IdentString(r) 34 } 35 36 func (r *Runtime) StrLabel(str string) adt.Feature { 37 return r.Label(str, false) 38 } 39 40 func (r *Runtime) Label(s string, isIdent bool) adt.Feature { 41 index := r.StringToIndex(s) 42 typ := adt.StringLabel 43 if isIdent { 44 switch { 45 case internal.IsDef(s) && internal.IsHidden(s): 46 typ = adt.HiddenDefinitionLabel 47 case internal.IsDef(s): 48 typ = adt.DefinitionLabel 49 case internal.IsHidden(s): 50 typ = adt.HiddenLabel 51 } 52 } 53 f, _ := adt.MakeLabel(nil, index, typ) 54 return f 55 } 56 57 // TODO: move to Runtime as fields. 58 var ( 59 labelMap = map[string]int{} 60 labels = make([]string, 0, 1000) 61 mutex sync.RWMutex 62 ) 63 64 func init() { 65 // Ensure label 0 is assigned to _. 66 getKey("_") 67 } 68 69 func getKey(s string) int64 { 70 mutex.RLock() 71 p, ok := labelMap[s] 72 mutex.RUnlock() 73 if ok { 74 return int64(p) 75 } 76 mutex.Lock() 77 defer mutex.Unlock() 78 p, ok = labelMap[s] 79 if ok { 80 return int64(p) 81 } 82 p = len(labels) 83 labels = append(labels, s) 84 labelMap[s] = p 85 return int64(p) 86 } 87 88 func (x *index) IndexToString(i int64) string { 89 mutex.RLock() 90 s := labels[i] 91 mutex.RUnlock() 92 return s 93 }