github.com/geraldss/go/src@v0.0.0-20210511222824-ac7d0ebfc235/encoding/names.go (about) 1 // Copyright (c) 2017 Gerald Sangudi. All rights reserved. 2 3 package encoding 4 5 import ( 6 "sync" 7 ) 8 9 func HashName(in string) (out string) { 10 return NAME_HASH.Hash(in) 11 } 12 13 // Global hash of names used in name-value objects. 14 type NameHash struct { 15 sync.RWMutex 16 17 names map[string]string 18 } 19 20 const NAME_HASH_CAP = 16 * 1024 21 22 var NAME_HASH = &NameHash{ 23 names: make(map[string]string, NAME_HASH_CAP), 24 } 25 26 func (this *NameHash) Hash(in string) (out string) { 27 28 this.RLock() 29 out, ok := this.names[in] 30 this.RUnlock() 31 if ok { 32 return 33 } 34 35 this.Lock() 36 out, ok = this.names[in] 37 if !ok { 38 if len(this.names) < NAME_HASH_CAP { 39 this.names[in] = in 40 } 41 out = in 42 } 43 this.Unlock() 44 return 45 }